taler-merchant-demos

Python-based Frontends for the Demonstration Web site
Log | Files | Refs | README | LICENSE

merchant_samples.go (8487B)


      1 package web
      2 
      3 import (
      4 	_ "embed"
      5 	"encoding/base64"
      6 	"net/http"
      7 	"net/url"
      8 	"regexp"
      9 	"strings"
     10 	"time"
     11 
     12 	"git.taler.net/taler-merchant-demos/internal/backend"
     13 )
     14 
     15 func (a *App) registerSamplesRoutes() {
     16 	a.mux.HandleFunc("GET /merchant-samples", func(w http.ResponseWriter, r *http.Request) {
     17 		lang := a.bestLanguage(r.Header.Get("Accept-Language"))
     18 		w.Header().Add("Vary", "Accept-Language")
     19 		http.Redirect(w, r, forwardedPrefix(r)+"/"+lang+"/merchant-samples", http.StatusFound)
     20 	})
     21 	a.handleGet("/{lang}/merchant-samples", a.whenSamplesReady(a.samples))
     22 	a.handlePost("/{lang}/merchant-samples/orders", a.whenSamplesReady(a.createSampleOrder))
     23 	a.handleGet("/{lang}/merchant-samples/receipts/{id}", a.whenSamplesReady(a.sampleReceipt))
     24 }
     25 
     26 func (a *App) whenSamplesReady(next http.HandlerFunc) http.HandlerFunc {
     27 	return func(w http.ResponseWriter, r *http.Request) {
     28 		if !a.samplesReady.Load() {
     29 			w.Header().Set("Retry-After", "5")
     30 			a.renderError(w, r, http.StatusServiceUnavailable, requestLang(r), "Merchant samples are starting up. Please try again shortly.", nil)
     31 			return
     32 		}
     33 		next(w, r)
     34 	}
     35 }
     36 
     37 func (a *App) samplePage(r *http.Request, content any) page {
     38 	p := a.makePage(r, requestLang(r), "Merchant samples", content)
     39 	p.HeaderTitle = p.Title
     40 	p.HeaderURL = forwardedPrefix(r) + "/" + p.Lang + "/merchant-samples"
     41 	p.HeaderText = a.translatedHTML(p.Lang, "Try payments, discounts and subscriptions with your Taler wallet.")
     42 	p.LanguagePath = strings.TrimPrefix(r.URL.Path, "/"+p.Lang+"/")
     43 	return p
     44 }
     45 
     46 func (a *App) samples(w http.ResponseWriter, r *http.Request) {
     47 	a.render(w, "merchant-samples", a.samplePage(r, a.opts.Currency), http.StatusOK)
     48 }
     49 
     50 //go:embed assets/static/coffee.png
     51 var coffeePNG []byte
     52 
     53 //go:embed assets/static/croissant.png
     54 var croissantPNG []byte
     55 
     56 func (a *App) coffeeProduct(lang, quantity, price string) backend.Product {
     57 	return backend.Product{
     58 		Name:         a.catalogs.translate(lang, "Coffee"),
     59 		Description:  a.catalogs.translate(lang, "Freshly brewed coffee"),
     60 		UnitQuantity: quantity, Prices: []string{price},
     61 		Image: "data:image/png;base64," + base64.StdEncoding.EncodeToString(coffeePNG),
     62 	}
     63 }
     64 
     65 func (a *App) sampleOrder(lang, sample string) (backend.Order, bool) {
     66 	currency := a.opts.Currency
     67 	order := backend.Order{Version: 1}
     68 	couponOut := []backend.OrderOutput{{Type: "token", TokenFamilySlug: couponSlug}}
     69 	couponIn := []backend.OrderInput{{Type: "token", TokenFamilySlug: couponSlug}}
     70 	passOut := []backend.OrderOutput{{Type: "token", TokenFamilySlug: passSlug}}
     71 	fullPrice := a.catalogs.translate(lang, "Full price")
     72 	switch sample {
     73 	case "pay-v0", "pay-v1", "postcard":
     74 		order.Summary = a.catalogs.translate(lang, "Postcard")
     75 		if sample == "pay-v0" {
     76 			order.Version = 0
     77 			order.Amount = currency + ":1"
     78 		} else {
     79 			order.Choices = []backend.OrderChoice{{Amount: currency + ":1"}}
     80 			if sample == "postcard" {
     81 				order.Choices = append(order.Choices, backend.OrderChoice{Amount: "CHF:0.10"})
     82 			}
     83 		}
     84 	case "basket":
     85 		order.Summary = a.catalogs.translate(lang, "Café basket")
     86 		order.Choices = []backend.OrderChoice{{Amount: currency + ":7"}}
     87 		order.Products = []backend.Product{
     88 			a.coffeeProduct(lang, "2", currency+":4"),
     89 			{
     90 				Name:         a.catalogs.translate(lang, "Croissant"),
     91 				Description:  a.catalogs.translate(lang, "Butter croissant"),
     92 				UnitQuantity: "1", Prices: []string{currency + ":2"},
     93 				Image: "data:image/png;base64," + base64.StdEncoding.EncodeToString(croissantPNG),
     94 			},
     95 			{
     96 				Name:         a.catalogs.translate(lang, "Tea"),
     97 				Description:  a.catalogs.translate(lang, "Black tea"),
     98 				UnitQuantity: "1", Prices: []string{currency + ":1"},
     99 			},
    100 		}
    101 	case "coffee":
    102 		order.Summary = a.catalogs.translate(lang, "Coffee")
    103 		order.Products = []backend.Product{a.coffeeProduct(lang, "1", currency+":2")}
    104 		order.Choices = []backend.OrderChoice{
    105 			{Amount: currency + ":2", Description: a.catalogs.translate(lang, "Without coupon"), Outputs: couponOut},
    106 			{Amount: currency + ":1", Description: a.catalogs.translate(lang, "With one coupon"), Inputs: couponIn},
    107 			{
    108 				Amount: currency + ":0", Description: a.catalogs.translate(lang, "With two coupons"),
    109 				Inputs: []backend.OrderInput{{Type: "token", TokenFamilySlug: couponSlug, Count: 2}},
    110 			},
    111 		}
    112 	case "earn-multi":
    113 		order.Summary = a.catalogs.translate(lang, "Coffee with a coupon")
    114 		order.Choices = []backend.OrderChoice{
    115 			{Amount: currency + ":2", Outputs: couponOut},
    116 			{Amount: "CHF:0.20", Outputs: couponOut},
    117 		}
    118 	case "redeem-multi":
    119 		order.Summary = a.catalogs.translate(lang, "Coffee")
    120 		discounted := a.catalogs.translate(lang, "Use a coupon")
    121 		order.Choices = []backend.OrderChoice{
    122 			{Amount: currency + ":2", Description: fullPrice},
    123 			{Amount: currency + ":1", Description: discounted, Inputs: couponIn},
    124 			{Amount: "CHF:0.20", Description: fullPrice},
    125 			{Amount: "CHF:0.10", Description: discounted, Inputs: couponIn},
    126 		}
    127 	case "exhibition":
    128 		order.Summary = a.catalogs.translate(lang, "Visit the exhibition")
    129 		order.Choices = []backend.OrderChoice{
    130 			{Amount: currency + ":1", Description: a.catalogs.translate(lang, "Single entry")},
    131 			{Amount: currency + ":3", Description: a.catalogs.translate(lang, "Day pass"), Outputs: passOut},
    132 			{
    133 				Amount: currency + ":0", Description: a.catalogs.translate(lang, "Entry with pass"),
    134 				Inputs: []backend.OrderInput{{Type: "token", TokenFamilySlug: passSlug}}, Outputs: passOut,
    135 			},
    136 		}
    137 	default:
    138 		return backend.Order{}, false
    139 	}
    140 	return order, true
    141 }
    142 
    143 func (a *App) createSampleOrder(w http.ResponseWriter, r *http.Request) {
    144 	lang := requestLang(r)
    145 	sample := r.PostFormValue("sample")
    146 	// Accept forms opened before the coffee and exhibition buttons were combined.
    147 	switch sample {
    148 	case "earn", "redeem":
    149 		sample = "coffee"
    150 	case "pass", "admission":
    151 		sample = "exhibition"
    152 	}
    153 	order, ok := a.sampleOrder(lang, sample)
    154 	if !ok {
    155 		a.renderError(w, r, http.StatusBadRequest, lang, "Unknown payment sample", nil)
    156 		return
    157 	}
    158 	id, err := randomID()
    159 	if err != nil {
    160 		a.renderError(w, r, http.StatusInternalServerError, lang, "Internal server error", err)
    161 		return
    162 	}
    163 	base := a.samplesLandingURL.JoinPath(lang, "merchant-samples")
    164 	order.OrderID = id
    165 	order.FulfillmentURL = base.JoinPath("receipts", id).String()
    166 	order.PublicReorderURL = base.String()
    167 	now := time.Now()
    168 	payDeadline := now.Add(5 * time.Minute).Unix()
    169 	if sample == "exhibition" {
    170 		// A checkout issued today must finish within today's pass period.
    171 		nextMidnight := now.UTC().Truncate(24 * time.Hour).Add(24 * time.Hour)
    172 		payDeadline = min(payDeadline, nextMidnight.Unix())
    173 	}
    174 	order.PayDeadline = backend.Timestamp{Seconds: payDeadline}
    175 	order.WireTransferDeadline = backend.Timestamp{Seconds: now.Add(2 * time.Hour).Unix()}
    176 	var created backend.PostOrderResponse
    177 	merchant := a.opts.SamplesBackend
    178 	if err := merchant.Post(r.Context(), "private/orders", backend.PostOrderRequest{Order: order, CreateToken: true}, &created); err != nil {
    179 		a.renderError(w, r, http.StatusBadGateway, lang, "Backend could not create the order", err)
    180 		return
    181 	}
    182 	if created.OrderID != id || created.Token == "" {
    183 		a.renderError(w, r, http.StatusBadGateway, lang, "Invalid order response from merchant", nil)
    184 		return
    185 	}
    186 	paymentURL := merchant.URL("orders/"+id, url.Values{"token": {created.Token}})
    187 	http.Redirect(w, r, paymentURL, http.StatusSeeOther)
    188 }
    189 
    190 var sampleOrderID = regexp.MustCompile(`^[0-9a-f]{32}$`)
    191 
    192 func (a *App) sampleReceipt(w http.ResponseWriter, r *http.Request) {
    193 	lang := requestLang(r)
    194 	id := r.PathValue("id")
    195 	if !sampleOrderID.MatchString(id) {
    196 		a.renderError(w, r, http.StatusNotFound, lang, "Page not found", nil)
    197 		return
    198 	}
    199 	var status backend.OrderStatusResponse
    200 	err := a.opts.SamplesBackend.Get(r.Context(), "private/orders/"+id, nil, &status)
    201 	if backendStatus(err, http.StatusNotFound) {
    202 		a.renderError(w, r, http.StatusNotFound, lang, "Page not found", nil)
    203 		return
    204 	}
    205 	if err != nil {
    206 		a.renderError(w, r, http.StatusBadGateway, lang, "Backend request failed", err)
    207 		return
    208 	}
    209 	if status.OrderStatus == "unpaid" || status.OrderStatus == "claimed" {
    210 		a.renderError(w, r, http.StatusPaymentRequired, lang, "This order is awaiting payment.", nil)
    211 		return
    212 	}
    213 	amount, ok := status.SelectedAmount()
    214 	if status.OrderStatus != "paid" || !ok {
    215 		a.renderError(w, r, http.StatusBadGateway, lang, "Invalid order response from merchant", nil)
    216 		return
    217 	}
    218 	a.render(w, "sample-receipt", a.samplePage(r, amount), http.StatusOK)
    219 }