diff --git a/abocost.go b/abocost.go
new file mode 100644
index 0000000..9408b04
--- /dev/null
+++ b/abocost.go
@@ -0,0 +1,37 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+)
+
+// abocost handler
+func abocostHandler(response http.ResponseWriter, request *http.Request) {
+ body, err := ioutil.ReadAll(request.Body)
+ if err != nil {
+ panic(err)
+ }
+ log.Println(string(body))
+
+ var data map[string]int
+ err2 := json.Unmarshal([]byte(body), &data)
+ if err2 != nil {
+ log.Println("Error, invalid json: %v", err)
+ }
+ response.Header().Set("Content-Type", "text/json; charset=utf-8")
+ fmt.Fprintf(response, "{\n")
+ first := true
+ for key, value := range data {
+ fmt.Println("Key:", key, "Value:", value)
+ if first {
+ first = false
+ } else {
+ fmt.Fprintf(response, " ,")
+ }
+ fmt.Fprintf(response, " \"%s\": [ %d, %d, \"%s\", \"%s\" ]\n", key, int(value), int(getYearlyAboCost(key)*int(value)), getActiveUntil(key), getDevAlias(key))
+ }
+ fmt.Fprintf(response, "}\n")
+}
diff --git a/main.go b/main.go
index bdc5d86..d0d45e7 100644
--- a/main.go
+++ b/main.go
@@ -94,6 +94,7 @@ func main() {
http.HandleFunc("/logout", logoutHandler)
http.HandleFunc("/confirm", confirmHandler)
http.HandleFunc("/metrics", metricsHandler)
+ http.HandleFunc("/abocost", abocostHandler)
http.HandleFunc("/downloadmetrics", downloadmetricsHandler)
http.HandleFunc("/order", orderHandler)
http.HandleFunc("/save_tracker_settings", save_tracker_settingsHandler)
diff --git a/persistence.go b/persistence.go
index b6a226f..9ff0014 100644
--- a/persistence.go
+++ b/persistence.go
@@ -193,6 +193,31 @@ func getActiveUntil(deveui string) string {
return res
}
+func getYearlyAboCost(deveui string) int {
+ res := 0
+
+ logit("getYearlyAboCost: Deveui: " + deveui)
+
+ conn := globalPool.Get()
+ defer conn.Close()
+
+ // first we get the default
+ yearlyAboCostDefault, err := redis.Int(conn.Do("HGET", "settings", "default_yearly_abo_cost"))
+ if err == nil {
+ yearlyAboCost, err := redis.Int(conn.Do("HGET", devPrefix+deveui, "yearly_abo_cost"))
+ if err == nil {
+ res = yearlyAboCost
+ } else {
+ res = yearlyAboCostDefault
+ }
+ } else {
+ log.Print(err)
+
+ }
+
+ return res
+}
+
func AboExpired(deveui string) bool {
active_until := getActiveUntil(deveui)
diff --git a/snippets/order.html b/snippets/order.html
index a3a3b95..b07dc8c 100644
--- a/snippets/order.html
+++ b/snippets/order.html
@@ -33,7 +33,7 @@
GPS Tracker mit integriertem Akku
USB-Netzadapter mit Ladekabel USB-Typ-A
2 Dual Lock Klettpad 25 x 25mm zum optionalen einfachen Befestigen
- 12 Monate Abo, anschliessend CHF 5.00 pro Monat
+ 12 Monate Abo, anschliessend CHF 3.00 pro Monat
diff --git a/static/js/tracker.js b/static/js/tracker.js
index 0ae39ad..73edfc4 100644
--- a/static/js/tracker.js
+++ b/static/js/tracker.js
@@ -1,3 +1,6 @@
+// dictionary: deveui as key, count as value
+var abos_to_buy = {}
+
function validate(what, text) {
if (what == 'alias') {
var re = /^[a-zA-Z0-9 ]{1,25}$/;
@@ -5,7 +8,44 @@ function validate(what, text) {
return re.test(text);
}
+function HandleAbocostResponse(data) {
+ var ordered = Object.keys(data).sort().reduce(
+ (obj, key) => {
+ obj[key] = data[key];
+ return obj;
+ },
+ {}
+ );
+
+ counter = 0;
+ total_amount = 0;
+ charge_data = '';
+ console.log("Response: ");
+ console.log(data);
+ abo_table = '
';
+ abo_table += '| Alias | verlängern bis | Betrag |
';
+ jQuery.each(ordered, function (index, val) {
+ counter += 1;
+ abo_table += '| ' + val[3] + ' | ' + moment(val[2], 'DD.MM.YYYY').add('years', val[0]).format('DD.MM.YYYY') + ' | ' + (val[1] / 100).toFixed(2) + ' |
';
+ total_amount += (val[1] / 100);
+ if (charge_data == '') {
+ charge_data = index + ":" + val[0] + ":" + val[1];
+ } else {
+ charge_data += "," + index + ":" + val[0] + ":" + val[1];
+ }
+ });
+ abo_table += '| Total CHF | | ' + (total_amount).toFixed(2) + ' |
';
+ abo_table += "
";
+ if (counter > 0) {
+ $("#abos_verlaengern").html(abo_table);
+ console.log("charge_data: " + charge_data);
+ $("#charge_data").html(charge_data);
+ $("#cart").addClass("is-active");
+ }
+}
+
$(document).ready(function () {
+ abos_to_buy = {};
$(".show-modal").click(function () {
$("#alias_exclamation").hide();
var alias = $(this).prev().html();
@@ -26,11 +66,18 @@ $(document).ready(function () {
});
$(".abo_plus").click(function () {
+ var deveui = $(this).prev().attr('id').replace("abo_add_years_", "");
+ console.log(deveui);
el = $(this).parent().find(".abo_add_years");
el_text = $(this).parent().parent().find(".abo_add_years_text");
counter = Number(el.html());
if (counter < 3) {
counter = counter + 1;
+ if (deveui in abos_to_buy) {
+ abos_to_buy[deveui] += 1;
+ } else {
+ abos_to_buy[deveui] = 1;
+ }
el.html(counter);
if (counter == 1) {
el_text.html("+" + counter + " Jahr");
@@ -38,15 +85,23 @@ $(document).ready(function () {
el_text.html("+" + counter + " Jahre");
}
}
+ console.log("abos_to_buy: %o", abos_to_buy);
});
$(".abo_minus").click(function () {
+ var deveui = $(this).prev().attr('id').replace("abo_", "");
el = $(this).parent().find(".abo_add_years");
el_text = $(this).parent().parent().find(".abo_add_years_text");
counter = Number(el.html());
if (counter > 0) {
counter = counter - 1;
el.html(counter);
+ if (deveui in abos_to_buy) {
+ abos_to_buy[deveui] -= 1;
+ if (abos_to_buy[deveui] == 0) {
+ delete abos_to_buy[deveui];
+ }
+ }
if (counter == 0) {
el_text.html(" ");
} else if (counter == 1) {
@@ -55,6 +110,8 @@ $(document).ready(function () {
el_text.html("+" + counter + " Jahre");
}
}
+ console.log("deveui: %s", deveui);
+ console.log("abos_to_buy: %o", abos_to_buy);
});
function add_years(dt, n) {
@@ -62,36 +119,29 @@ $(document).ready(function () {
}
$(".abo_pay").click(function () {
+ console.log(Object.keys(abos_to_buy).length);
+ if (Object.keys(abos_to_buy).length < 1) {
+ return;
+ }
+
loadStripeLibrary();
- counter = 0;
- charge_data = '';
- abo_table = '
';
- abo_table += '| Alias | verlängern bis | Betrag |
';
- $(".tracker").each(function (index) {
- this_count = Number($(this).find(".abo_add_years").html());
- if (this_count > 0) {
- counter += this_count;
- paid_until = $(this).find(".paid_until").html();
- if (moment(paid_until, 'DD.MM.YYYY') < moment()) {
- this_date = moment().format('DD.MM.YYYY');
- } else {
- this_date = paid_until;
- }
- abo_table += '| ' + $(this).find('.alias').html() + ' | ' + moment(this_date, 'DD.MM.YYYY').add('years', this_count).format('DD.MM.YYYY') + ' | ' + (this_count * 60).toFixed(2) + ' |
';
- if (charge_data == '') {
- charge_data = $(this).find("div").first().attr('id') + ":" + this_count;
- } else {
- charge_data += "," + $(this).find("div").first().attr('id') + ":" + this_count;
- }
+
+ $.ajax({
+ url: "abocost",
+ type: "POST", //send it through post method
+ dataType: "json",
+ data: JSON.stringify(abos_to_buy),
+ success: function(response) {
+ console.log("SUCCESS");
+ console.log(response);
+ HandleAbocostResponse(response);
+ },
+ error: function(xhr) {
+ console.log("ERROR");
+ console.log(xhr);
}
});
- abo_table += '| Total CHF | | ' + (counter * 60).toFixed(2) + ' |
';
- abo_table += "
";
- if (counter > 0) {
- $("#abos_verlaengern").html(abo_table);
- $("#charge_data").html(charge_data);
- $("#cart").addClass("is-active");
- }
+
});
$("#modal-close").click(function () {
@@ -157,7 +207,7 @@ function loadStripeLibrary() {
function SetupStripe() {
// Set your publishable key: remember to change this to your live publishable key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
- stripe = Stripe('pk_live_51Icq29K2XyHQRTs2oNQMPT75m7J96ajcKDADEE8FCSA3WWD98je6IZgN0E7Q2t5Vccdu1ar5kQZUIjbPhRluTkS500rgdMr0dF');
+ stripe = Stripe('pk_test_51Icq29K2XyHQRTs2DeltUIWrbFb5evfJVGaQzMv4r50g8Q7HAUkSFr7BBGv0aP1damXIhM6fZ4Yf9Wz0qW6TpTVi00dWcW7J1O');
elements = stripe.elements({ locale: "de" });
// Set up Stripe.js and Elements to use in checkout form
diff --git a/stripe.go b/stripe.go
index ade75b5..a8da4ec 100644
--- a/stripe.go
+++ b/stripe.go
@@ -32,16 +32,18 @@ func getstripepaymentintentHandler(response http.ResponseWriter, request *http.R
var abo_years = 0
var items []string
+ amount := 0
for _, tracker := range trackers {
items = strings.Split(tracker, ":")
if len(items) == 2 {
abo_count, err := strconv.Atoi(items[1])
if err == nil {
abo_years += abo_count
+ amount += (abo_count * getYearlyAboCost(items[0]))
}
}
}
- abo_amount := int64(abo_years * 6000)
+ abo_amount := int64(amount)
stripe.Key = getStripeKey()
@@ -70,12 +72,13 @@ func HandlePayment(user string, charge_data string, amount int64) {
charge_data_email_text = charge_data_email_text + strings.Repeat("-", 62) + "\n"
for _, token := range strings.Split(charge_data, ",") {
res := strings.Split(token, ":")
- if (len(res)) == 2 {
+ if (len(res)) == 3 {
deveui := res[0]
years, _ := strconv.Atoi(res[1])
+ amount, _ := strconv.Atoi(res[2])
fmt.Printf("prolongActivation %s: %d\n", deveui, years)
prolongActivation(deveui, years)
- line := fmt.Sprintf("%-30s %20s %10.2f\n", getDevAlias(deveui), getActiveUntil(deveui), float64(60*years))
+ line := fmt.Sprintf("%-30s %20s %10.2f\n", getDevAlias(deveui), getActiveUntil(deveui), float64(amount / 100))
charge_data_email_text = charge_data_email_text + line
}
}