Skip to content

Commit

Permalink
a lot changes
Browse files Browse the repository at this point in the history
  • Loading branch information
lhhong committed Feb 20, 2017
1 parent ba70c8e commit b72f40c
Show file tree
Hide file tree
Showing 17 changed files with 263 additions and 20 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ logs/
privateDB/
ethereum/src/main/resources/user.conf
datafile.mv.db
datafile.trace.db
datafile.trace.db
app-main/npm-debug.log
4 changes: 2 additions & 2 deletions app-main/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@
<!-- endbuild -->


<script>
<!--<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-X');
ga('send', 'pageview');
</script>
</script>-->
<!-- Custom CSS -->

<!-- Custom Fonts -->
Expand Down
11 changes: 2 additions & 9 deletions app-main/scripts/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ angular
'scripts/directives/timeline/timeline.js',
'scripts/directives/notifications/notifications.js',
'scripts/directives/chat/chat.js',
'scripts/directives/dashboard/stats/stats.js'
'scripts/directives/dashboard/stats/stats.js',
'scripts/services/transaction-service.js'
]
})
}
Expand Down Expand Up @@ -146,14 +147,6 @@ angular
templateUrl:'views/form.html',
url:'/form'
})
.state('dashboard.blank',{
templateUrl:'views/pages/blank.html',
url:'/blank'
})
.state('login',{
templateUrl:'views/pages/login.html',
url:'/login'
})
.state('dashboard.chart',{
templateUrl:'views/chart.html',
url:'/chart',
Expand Down
14 changes: 13 additions & 1 deletion app-main/scripts/controllers/MyPredictions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,21 @@
* Controller of the sbAdminApp
*/
angular.module('sbAdminApp')
.controller('PredictCtrl', ['$scope', 'txService', function($scope, txService) {
.controller('PredictCtrl', ['$interval', '$scope', 'txService', function($interval, $scope, txService) {

console.log("loaded");
$scope.balance = 0;

var reloadData = function() {
txService.getEther(function(balance) {
$scope.balance = balance;
})
}

$interval(function() {
reloadData();
}, 5000)

$scope.predictions = [{
'SKU' : '00123123',
'product': 'Apples',
Expand Down
16 changes: 14 additions & 2 deletions app-main/scripts/controllers/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,17 @@
* Controller of the sbAdminApp
*/
angular.module('sbAdminApp')
.controller('MainCtrl', function($scope,$position) {
});
.controller('MainCtrl', ['$scope', '$position', '$interval', 'txService', function($scope, $position, $interval, txService) {
console.log("main controller loaded");
$scope.balance = 0;

var reloadData = function() {
txService.getEther(function(balance) {
$scope.balance = balance;
})
}

$interval(function() {
reloadData();
}, 5000)
}]);
3 changes: 3 additions & 0 deletions app-main/views/dashboard/MyPredictions.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
<div class="col-lg-12">
<h1 class="page-header"><i class="fa fa-bar-chart-o fa-fw"></i><em> MyPredictions</em></h1>
</div>
<div class="pull-right">
<h3>Current ether balance: <em>{{ balance }}</em></h3>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
Expand Down
1 change: 1 addition & 0 deletions app-main/views/dashboard/home.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<div>
<div>{{ balance }}</div>
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Crumbs <em>Dashboard</em></h1>
Expand Down
5 changes: 3 additions & 2 deletions ethereum/src/main/java/com/crumbs/WebSocketConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ public void configureMessageBroker(MessageBrokerRegistry config) {

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/crumbs")
.withSockJS();
registry.addEndpoint("/crumbs").setAllowedOrigins("*")
// .withSockJS()
;
}


Expand Down
22 changes: 22 additions & 0 deletions ethereum/src/main/java/com/crumbs/models/Prediction.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.crumbs.models;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

/**
* Created by low on 19/2/17 10:57 AM.
*/
@Getter
@Setter
public class Prediction {

private ProductVM product;
private List<RemainingStock> stock = new ArrayList<>();

public void addToStockList(RemainingStock remainingStock) {
stock.add(remainingStock);
}
}
17 changes: 17 additions & 0 deletions ethereum/src/main/java/com/crumbs/models/RemainingStock.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.crumbs.models;

import lombok.Getter;
import lombok.Setter;

/**
* Created by low on 19/2/17 11:03 AM.
*/
@Getter
@Setter
public class RemainingStock {

private int quantity;
private double urgency;
private String urgencyLevel;
private int percentExtra;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
Expand All @@ -13,4 +14,5 @@
@Repository
public interface SalesRecordRepo extends JpaRepository<SalesRecord, Long> {
List<SalesRecord> findByProductOrderByDateAsc(Product product);
List<SalesRecord> findByProductOrderByDateBeforeByDateAsc(Product product, Date date);
}
24 changes: 24 additions & 0 deletions ethereum/src/main/java/com/crumbs/rest/PredictionCtrl.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,34 @@
package com.crumbs.rest;

import com.crumbs.models.Prediction;
import com.crumbs.services.PredictionSrvc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
* Created by low on 16/2/17 10:33 PM.
*/
@RestController
public class PredictionCtrl {

private static final Logger logger = LoggerFactory.getLogger(PredictionCtrl.class);

@Autowired
PredictionSrvc predictionSrvc;

@RequestMapping(method = GET, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public List<Prediction> getPredictions() {
return predictionSrvc.getAllPredictions();
}
}
14 changes: 14 additions & 0 deletions ethereum/src/main/java/com/crumbs/rest/TestControllers.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import com.crumbs.ethereum.AccountBean;
import com.crumbs.ethereum.EthereumBean;
import com.crumbs.services.ContractService;
import com.crumbs.services.WebSocketSrvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Random;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
Expand All @@ -27,6 +29,18 @@ public class TestControllers {
@Autowired
private ContractService contractService;

@Autowired
private WebSocketSrvc webSocketSrvc;

static Random r = new Random();

@RequestMapping(value = "/random-test", method = GET)
@ResponseBody
public long testWebSocket() {
//webSocketSrvc.sendBalance(r.nextLong());
return r.nextLong();
}

@RequestMapping(value = "/sample-contract", method = GET)
@ResponseBody
public void sendSampleContract() throws IOException {
Expand Down
84 changes: 81 additions & 3 deletions ethereum/src/main/java/com/crumbs/services/PredictionSrvc.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package com.crumbs.services;

import com.crumbs.models.StockUpdate;
import com.crumbs.models.TransactionVM;
import com.crumbs.models.*;
import com.crumbs.repositories.SalesRecordRepo;
import com.crumbs.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -25,8 +26,40 @@ public class PredictionSrvc {
@Autowired
InventoryService inventoryService;

public void test() {
@Autowired
SalesRecordRepo salesRecordRepo;

public List<Prediction> getAllPredictions() {
restTemplate.postForEntity("url", Integer[].class, Integer[].class);
List<Prediction> predictions = new ArrayList<>();
//TODO for each product, send array with buildArrayQuery to python and call buildPredictionVM for the product demand
return predictions;
}

public List<Integer> buildArrayQuery(String product) {
Product p = new Product();
p.setName(product);
List<SalesRecord> salesRecords = salesRecordRepo.findByProductOrderByDateBeforeByDateAsc(p, DateUtil.today());
List<Integer> query = new ArrayList<>();
salesRecords.forEach((record) -> query.add(record.getQuantity()));
return query;
}

public Prediction buildPrediction(List<Integer> demand, String product) {
List<Integer> aggregatedStock = aggregatedStock(demand, product);
ProductVM productVM = inventoryService.getProduct(product);
Prediction prediction = new Prediction();
prediction.setProduct(productVM);
for (int i = 0; i < 7; i++) {
RemainingStock stock = new RemainingStock();
stock.setQuantity(aggregatedStock.get(i));
double urgency = calculateUrgency(demand.get(i), aggregatedStock.get(i));
stock.setUrgency(urgency);
stock.setUrgencyLevel(getUrgencyLevel(urgency));
stock.setPercentExtra((int) (100*calcPercentExtra(demand.get(i), aggregatedStock.get(i))));
prediction.addToStockList(stock);
}
return prediction;
}

public List<Integer> aggregatedStock(List<Integer> demand, String product) {
Expand Down Expand Up @@ -56,4 +89,49 @@ public List<Integer> aggregatedStock(List<Integer> demand, String product) {

return predictedStock;
}

private String getUrgencyLevel(double urgency) {
List<Double> threshold = calcThreshold();
if (urgency > threshold.get(0)) {
return "red";
}
if (urgency > threshold.get(1)) {
return "orange";
}
if (urgency > threshold.get(2)) {
return "yellow";
}
else {
return "green";
}
}

private double calcPercentExtra(int demand, int predictedStock) {
return ((double) predictedStock) / ((double) demand);
}

private double calculateUrgency(int demand, int predictedStock) {
return urgencyFunction(calcPercentExtra(demand, predictedStock));
}

private final double perfectPercentage = 0.15;
private final double multiplicator = 4;

private double urgencyFunction(double x) {
x = (x - perfectPercentage) * multiplicator;
return ((x* x) * (1- sigmoid(x, 4))) + ((x*x/6) * sigmoid(x, 6));
}

private double sigmoid(double x, int alpha) {
return (1d / (1 + Math.exp(-alpha * x)));
}

private List<Double> calcThreshold() {
List<Double> threshold = new ArrayList<>();
double severeUrgency = urgencyFunction(0d);
threshold.add(severeUrgency);
threshold.add(severeUrgency*2/3);
threshold.add(severeUrgency/3);
return threshold;
}
}
2 changes: 2 additions & 0 deletions ethereum/src/main/java/com/crumbs/services/WebSocketSrvc.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

/**
* Created by low on 18/2/17 6:08 PM.
*/
@Service
public class WebSocketSrvc {
@Autowired
SimpMessagingTemplate messagingTemplate;
Expand Down
25 changes: 25 additions & 0 deletions ethereum/src/main/java/com/crumbs/util/FoodList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.crumbs.util;

import com.alibaba.fastjson.JSON;

import java.util.*;

/**
* Created by low on 20/2/17 6:10 PM.
*/
public class FoodList {

public static Map<String, String> all;

public static Map<String, String> allFood() {
if (all == null) {
Map<String, String> map = new HashMap<>();
map.put("Apple", "Fruits");
map.put("Orange", "Fruits");
map.put("Daisy Milk", "Dairy");
map.put("Yogurt", "Dairy");
all = map;
}
return all;
}
}
Loading

0 comments on commit b72f40c

Please sign in to comment.