main.js (2670B)
1 import * as etc from "/lib/etc.js" 2 import * as api from "/lib/api.js" 3 import * as ui from "/lib/ui.js" 4 5 etc.handle_wrap(main) 6 7 function main() { 8 ui.wait("Please wait...") 9 10 etc.userService() 11 .then(function(service) { 12 if (service) { 13 window.location.href = "/settings/billing" 14 } else { 15 api.fetch("GET", "services") 16 .then(function(services) { 17 if (services.length === 1) { 18 chooseService(services[0]) 19 } else { 20 for (let service in services) { 21 addService(services[service]) 22 } 23 ui.wait() 24 document.getElementById("services") 25 .removeAttribute("hidden", false) 26 } 27 }) 28 } 29 }) 30 .catch(function() { 31 // Assume they need to signup for now 32 window.location.href = "/register" 33 }) 34 } 35 36 function chooseService(service) { 37 console.log("Choose service", service.id) 38 39 if (!api.authorized()) { 40 window.location.href = "/register" 41 } 42 43 api.verifiedEmail() 44 .then(function(email) { 45 if (!email) { 46 window.location.href = "/settings/verify-email" 47 return 48 } 49 api.fetch("POST", "users/:user/services/checkout", 50 { prices: [ service.prices[0].id ] }).then(function(body) { 51 window.location.href = body.url 52 }) 53 .catch(function(err) { 54 console.error("Unable to checkout:", err) 55 etc.error("There was an unexpected error.") 56 }) 57 }) 58 } 59 60 function addService(service) { 61 let container = document.createElement("div") 62 container.classList.add("service") 63 64 let info = container 65 66 let button = document.createElement("input") 67 button.setAttribute("type", "button") 68 button.setAttribute("value", "Choose " + service.name) 69 button.addEventListener("click", function() { chooseService(service) }) 70 71 let name = info.appendChild(document.createElement("span")) 72 name.classList.add("name") 73 name.appendChild(document.createTextNode(service.name)) 74 75 info.appendChild(document.createTextNode(" ")) 76 77 let price = info.appendChild(document.createElement("span")) 78 price.classList.add("price") 79 price.appendChild(document.createTextNode(costDuration(service.prices[0]))) 80 81 if (service.description != null) { 82 let desc = info.appendChild(document.createElement("p")) 83 desc.appendChild(document.createTextNode(service.description)) 84 desc.classList.add("description") 85 } 86 87 container.appendChild(button) 88 document.getElementById("services") 89 .appendChild(container) 90 } 91 92 function costDuration(price) { 93 return "$" + String(price.amount / 100) + "/" + durationString(price) 94 } 95 96 function durationString(price) { 97 if (price.interval != "month") { 98 throw new Error("Expecting month") 99 } 100 if (price.intervalCount === 1) { 101 return "mo" 102 } 103 return String(price.intervalCount) + "mo" 104 }