payment modifications

This commit is contained in:
Joerg Lehmann 2021-04-05 19:46:35 +02:00
parent 459295043c
commit f58e1bc40b
6 changed files with 148 additions and 32 deletions

37
abocost.go Normal file
View File

@ -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")
}

View File

@ -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)

View File

@ -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)

View File

@ -33,7 +33,7 @@
<li>GPS Tracker mit integriertem Akku</li>
<li>USB-Netzadapter mit Ladekabel USB-Typ-A</li>
<li>2 Dual Lock Klettpad 25 x 25mm zum optionalen einfachen Befestigen</li>
<li>12 Monate Abo, <span class="has-text-weight-bold">anschliessend CHF 5.00 pro Monat</span></li>
<li>12 Monate Abo, <span class="has-text-weight-bold">anschliessend CHF 3.00 pro Monat</span></li>
</ul>
</div>
<div class="columns">

View File

@ -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 = '<table class="table is-bordered is-fullwidth" >';
abo_table += '<tr><th class="is-2">Alias</th><th>verl&auml;ngern bis</th><th class="has-text-right">Betrag</th></tr>';
jQuery.each(ordered, function (index, val) {
counter += 1;
abo_table += '<tr><td>' + val[3] + '</td><td>' + moment(val[2], 'DD.MM.YYYY').add('years', val[0]).format('DD.MM.YYYY') + '</td><td class="has-text-right">' + (val[1] / 100).toFixed(2) + '</td></tr>';
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 += '<tr><td>Total CHF</td><td></td><td class="has-text-right">' + (total_amount).toFixed(2) + '</td></tr>';
abo_table += "</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("&nbsp;");
} 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 = '<table class="table is-bordered is-fullwidth" >';
abo_table += '<tr><th class="is-2">Alias</th><th>verl&auml;ngern bis</th><th class="has-text-right">Betrag</th></tr>';
$(".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 += '<tr><td>' + $(this).find('.alias').html() + '</td><td>' + moment(this_date, 'DD.MM.YYYY').add('years', this_count).format('DD.MM.YYYY') + '</td><td class="has-text-right">' + (this_count * 60).toFixed(2) + '</td></tr>';
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 += '<tr><td>Total CHF</td><td></td><td class="has-text-right">' + (counter * 60).toFixed(2) + '</td></tr>';
abo_table += "</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

View File

@ -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
}
}