"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreditCard = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
/*
 *  This file is part of CoCalc: Copyright © 2021 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
/* Show payment methods.

TODO: we are only showing the credit card payment sources at present.
There are other types of sources, e.g., "ACH credit transfer".

In the *near* future we will support more payment methods!
*/
var react_1 = require("react");
var react_dom_1 = __importDefault(require("react-dom"));
var api_1 = __importDefault(require("lib/hooks/api"));
var loading_1 = __importDefault(require("components/share/loading"));
var help_email_1 = __importDefault(require("components/misc/help-email"));
var A_1 = __importDefault(require("components/misc/A"));
var antd_1 = require("antd");
var icon_1 = require("@cocalc/frontend/components/icon");
var post_1 = __importDefault(require("lib/api/post"));
var misc_1 = require("@cocalc/util/misc");
var use_customize_1 = __importDefault(require("lib/use-customize"));
var script_1 = __importDefault(require("next/script"));
var mounted_1 = __importDefault(require("lib/hooks/mounted"));
var site_name_1 = __importDefault(require("components/share/site-name"));
var sales_tax_1 = __importDefault(require("@cocalc/util/stripe/sales-tax"));
var STRIPE_CLIENT_LIBRARY = "https://js.stripe.com/v3/";
function Brand(_a) {
    var brand = _a.brand;
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(brand === null || brand === void 0 ? void 0 : brand.includes(" ")) ? ("") : ((0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "cc-".concat(brand === null || brand === void 0 ? void 0 : brand.toLowerCase()) })), " ", brand] }));
}
function Number(_a) {
    var last4 = _a.last4;
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "**** **** **** ".concat(last4) });
}
function ExpirationDate(_a) {
    var exp_month = _a.exp_month, exp_year = _a.exp_year;
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "".concat(exp_month, "/").concat(exp_year) });
}
function PaymentSourceActions(_a) {
    var _this = this;
    var onChange = _a.onChange, default_source = _a.default_source, brand = _a.brand, last4 = _a.last4, id = _a.id;
    var isMounted = (0, mounted_1.default)();
    var _b = __read((0, react_1.useState)(""), 2), error = _b[0], setError = _b[1];
    return ((0, jsx_runtime_1.jsxs)("div", { children: [error && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: error, style: { marginBottom: "5px" } })), default_source ? ((0, jsx_runtime_1.jsx)(antd_1.Popconfirm, __assign({ placement: "topLeft", showCancel: false, title: (0, jsx_runtime_1.jsxs)("div", __assign({ style: { width: "400px" } }, { children: ["The default payment method is the", " ", (0, jsx_runtime_1.jsxs)("b", { children: [brand, " card ending in ...", last4] }), ". It will be used by default for subscriptions and new purchases."] })), okText: "OK" }, { children: (0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ type: "primary", style: { marginRight: "5px", marginBottom: "5px" } }, { children: "Default" })) }))) : ((0, jsx_runtime_1.jsx)(antd_1.Popconfirm, __assign({ placement: "topLeft", title: (0, jsx_runtime_1.jsxs)("div", __assign({ style: { width: "400px" } }, { children: ["Do you want to set the", " ", (0, jsx_runtime_1.jsxs)("b", { children: [brand, " card ending in ...", last4] }), " ", "to be the default for subscriptions and new purchases?"] })), onConfirm: function () { return __awaiter(_this, void 0, void 0, function () {
                    var err_1;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                setError("");
                                return [4 /*yield*/, (0, post_1.default)("/billing/set-default-source", {
                                        default_source: id,
                                    })];
                            case 1:
                                _a.sent();
                                if (!isMounted.current)
                                    return [2 /*return*/];
                                onChange === null || onChange === void 0 ? void 0 : onChange();
                                return [3 /*break*/, 3];
                            case 2:
                                err_1 = _a.sent();
                                if (!isMounted.current)
                                    return [2 /*return*/];
                                setError(err_1.message);
                                return [3 /*break*/, 3];
                            case 3: return [2 /*return*/];
                        }
                    });
                }); }, okText: "Yes", cancelText: "No" }, { children: (0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ type: "dashed", style: { marginRight: "5px", marginBottom: "5px" } }, { children: "Default" })) }))), (0, jsx_runtime_1.jsx)(antd_1.Popconfirm, __assign({ placement: "topLeft", title: (0, jsx_runtime_1.jsxs)("div", __assign({ style: { width: "400px" } }, { children: ["Do you want to delete the", " ", (0, jsx_runtime_1.jsxs)("b", { children: [brand, " card ending in ...", last4] }), "? It will no longer be used for subscriptions and you will have to enter it again to use it to make a purchase."] })), onConfirm: function () { return __awaiter(_this, void 0, void 0, function () {
                    var err_2;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                setError("");
                                return [4 /*yield*/, (0, post_1.default)("/billing/delete-payment-method", { id: id })];
                            case 1:
                                _a.sent();
                                onChange === null || onChange === void 0 ? void 0 : onChange();
                                return [3 /*break*/, 3];
                            case 2:
                                err_2 = _a.sent();
                                setError(err_2.message);
                                return [3 /*break*/, 3];
                            case 3: return [2 /*return*/];
                        }
                    });
                }); }, okText: "Yes, delete this card", cancelText: "Cancel" }, { children: (0, jsx_runtime_1.jsxs)(antd_1.Button, __assign({ type: "dashed" }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "trash" }), " Delete"] })) }))] }));
}
var columns = function (onChange) { return [
    {
        responsive: ["xs"],
        title: "Card",
        render: function (_, card) { return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(CreditCard, __assign({}, card)), (0, jsx_runtime_1.jsx)(PaymentSourceActions, __assign({}, card, { onChange: onChange }))] })); },
    },
    {
        responsive: ["sm"],
        title: "Type",
        dataIndex: "brand",
        render: function (_, card) { return (0, jsx_runtime_1.jsx)(Brand, __assign({}, card)); },
    },
    {
        responsive: ["sm"],
        title: "Number",
        dataIndex: "last4",
        render: function (_, card) { return (0, jsx_runtime_1.jsx)(Number, __assign({}, card)); },
    },
    {
        responsive: ["sm"],
        title: "Expiration Date",
        align: "center",
        render: function (_, card) { return (0, jsx_runtime_1.jsx)(ExpirationDate, __assign({}, card)); },
    },
    {
        responsive: ["sm"],
        title: "Country",
        dataIndex: "country",
        align: "center",
    },
    {
        responsive: ["sm"],
        title: "Postal Code",
        dataIndex: "address_zip",
        align: "center",
    },
    {
        responsive: ["sm"],
        title: "",
        render: function (_, card) { return (0, jsx_runtime_1.jsx)(PaymentSourceActions, __assign({}, card, { onChange: onChange })); },
    },
]; };
function PaymentMethods(_a) {
    var e_1, _b, e_2, _c;
    var _d;
    var startMinimized = _a.startMinimized, setTaxRate = _a.setTaxRate;
    var _e = __read((0, react_1.useState)(!!startMinimized), 2), minimized = _e[0], setMinimized = _e[1];
    var _f = (0, api_1.default)("billing/get-customer"), result = _f.result, error = _f.error, call = _f.call;
    if (error) {
        return (0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: error });
    }
    if (!result) {
        return (0, jsx_runtime_1.jsx)(loading_1.default, { center: true });
    }
    // set default so can use in table
    var default_source = result.default_source;
    var cards = [];
    if (result.sources != null) {
        var _loop_1 = function (row) {
            if (row.id == default_source) {
                row.default_source = true;
                if (setTaxRate != null) {
                    // TODO: setTimeout as a quick fix. You can't change the state while the parent is rendering
                    // Cannot update a component (`Checkout`) while rendering a different component `PaymentMethods`).
                    setTimeout(function () { return setTaxRate((0, sales_tax_1.default)(row.address_zip)); }, 0);
                }
            }
            if (row.id.startsWith("card_")) {
                cards.push(row);
            }
        };
        try {
            for (var _g = __values(result.sources.data), _h = _g.next(); !_h.done; _h = _g.next()) {
                var row = _h.value;
                _loop_1(row);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
    // sort by data rather than what comes back, so changing
    // default stays stable (since moving is confusing).
    cards.sort(function (x, y) { return (0, misc_1.cmp)(x.id, y.id); });
    if (minimized) {
        var defaultCard = undefined;
        try {
            for (var cards_1 = __values(cards), cards_1_1 = cards_1.next(); !cards_1_1.done; cards_1_1 = cards_1.next()) {
                var card = cards_1_1.value;
                if (card.default_source) {
                    defaultCard = card;
                    break;
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (cards_1_1 && !cards_1_1.done && (_c = cards_1.return)) _c.call(cards_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
        if (defaultCard) {
            return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(A_1.default, __assign({ onClick: function () { return setMinimized(false); } }, { children: "Change" })), (0, jsx_runtime_1.jsx)(CreditCard, __assign({}, defaultCard))] }));
        }
    }
    return ((0, jsx_runtime_1.jsxs)("div", { children: [startMinimized && cards.length > 0 && ((0, jsx_runtime_1.jsx)("div", __assign({ style: { float: "right", marginRight: "15px" } }, { children: (0, jsx_runtime_1.jsxs)(A_1.default, __assign({ onClick: function () { return setMinimized(true); } }, { children: ["Close ", (0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "times" })] })) }))), !startMinimized && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)("h3", { children: ["Credit Cards (", cards.length, ")"] }), cards.length > 0 ? ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "These are the credit cards that you have currently setup." })) : ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: "Please enter your credit card below." })), " "] })), (0, jsx_runtime_1.jsx)(AddPaymentMethod, { defaultAdding: cards.length == 0, onChange: call, style: { marginTop: "15px", marginBottom: "5px" } }), cards.length > 0 && ((0, jsx_runtime_1.jsx)(antd_1.Table, { columns: columns(call), dataSource: cards, rowKey: "id", style: { marginTop: "15px", overflowX: "auto" }, pagination: { hideOnSinglePage: true, pageSize: 100 } })), ((_d = result.sources) === null || _d === void 0 ? void 0 : _d.has_more) && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "warning", showIcon: true, message: "WARNING: Some of your cards may not be displayed above, since there are so many." }))] }));
}
exports.default = PaymentMethods;
function AddPaymentMethod(_a) {
    var _this = this;
    var onChange = _a.onChange, style = _a.style, defaultAdding = _a.defaultAdding;
    var _b = __read((0, react_1.useState)(""), 2), error = _b[0], setError = _b[1];
    var _c = __read((0, react_1.useState)(!!defaultAdding), 2), adding = _c[0], setAdding = _c[1];
    var _d = __read((0, react_1.useState)(false), 2), creating = _d[0], setCreating = _d[1];
    var _e = __read((0, react_1.useState)(null), 2), stripe = _e[0], setStripe = _e[1];
    var cardRef = (0, react_1.useRef)();
    var stripePublishableKey = (0, use_customize_1.default)().stripePublishableKey;
    var isMounted = (0, mounted_1.default)();
    (0, react_1.useEffect)(function () {
        if (!adding || !cardRef.current)
            return;
        if (stripe != null) {
            stripe.card.mount(react_dom_1.default.findDOMNode(cardRef.current));
        }
        else {
            if (window.Stripe == null)
                return;
            var stripe_1 = window.Stripe(stripePublishableKey);
            var card = stripe_1.elements().create("card");
            if (card == null)
                throw Error("bug -- card cannot be null");
            setStripe({ stripe: stripe_1, card: card });
            card.mount(react_dom_1.default.findDOMNode(cardRef.current));
        }
    }, [adding, stripe]);
    return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: style }, { children: [(0, jsx_runtime_1.jsxs)(antd_1.Button, __assign({ disabled: adding, onClick: function () { return setAdding(true); } }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "plus-circle" }), " Add Credit Card"] })), adding && ((0, jsx_runtime_1.jsxs)("div", __assign({ style: {
                    border: "1px solid #ddd",
                    padding: "15px",
                    borderRadius: "5px",
                    maxWidth: "600px",
                    margin: "15px auto",
                } }, { children: [(0, jsx_runtime_1.jsx)(script_1.default, { src: STRIPE_CLIENT_LIBRARY, onLoad: function () {
                            var stripe = window.Stripe(stripePublishableKey);
                            var card = stripe.elements().create("card");
                            if (card == null)
                                throw Error("bug -- card cannot be null");
                            setStripe({ stripe: stripe, card: card });
                        }, onError: function () {
                            setError("Stripe script failed to load. Make sure your browser is not blocking ".concat(STRIPE_CLIENT_LIBRARY, ", then refresh this page."));
                        } }), error && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", showIcon: true, message: error, style: { margin: "15px 0" } })), (0, jsx_runtime_1.jsxs)("div", __assign({ style: { textAlign: "center" } }, { children: [(0, jsx_runtime_1.jsx)("div", { ref: cardRef, style: {
                                    border: "1px solid lightgray",
                                    borderRadius: "5px",
                                    margin: "5px auto 20px auto",
                                    maxWidth: "400px",
                                    padding: "15px 10px",
                                    boxShadow: "5px 5px 5px lightgray",
                                } }), (0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ style: { marginRight: "5px" }, onClick: function () { return setAdding(false); }, disabled: creating }, { children: "Cancel" })), (0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ disabled: creating, type: "primary", onClick: function () { return __awaiter(_this, void 0, void 0, function () {
                                    var token, result, err_3, err_4;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                setCreating(true);
                                                _a.label = 1;
                                            case 1:
                                                _a.trys.push([1, , 9, 10]);
                                                token = void 0;
                                                _a.label = 2;
                                            case 2:
                                                _a.trys.push([2, 4, , 5]);
                                                return [4 /*yield*/, (stripe === null || stripe === void 0 ? void 0 : stripe.stripe.createToken(stripe.card))];
                                            case 3:
                                                result = _a.sent();
                                                if (!isMounted.current)
                                                    return [2 /*return*/];
                                                if (result.error) {
                                                    throw Error(result.error.message);
                                                }
                                                (token = result.token);
                                                return [3 /*break*/, 5];
                                            case 4:
                                                err_3 = _a.sent();
                                                if (!isMounted.current)
                                                    return [2 /*return*/];
                                                setError(err_3.message);
                                                return [2 /*return*/];
                                            case 5:
                                                _a.trys.push([5, 7, , 8]);
                                                return [4 /*yield*/, (0, post_1.default)("/billing/create-payment-method", {
                                                        id: token.id,
                                                    })];
                                            case 6:
                                                _a.sent();
                                                if (!isMounted.current)
                                                    return [2 /*return*/];
                                                onChange === null || onChange === void 0 ? void 0 : onChange();
                                                setAdding(false);
                                                return [3 /*break*/, 8];
                                            case 7:
                                                err_4 = _a.sent();
                                                setError(err_4.message);
                                                return [3 /*break*/, 8];
                                            case 8: return [3 /*break*/, 10];
                                            case 9:
                                                if (!isMounted.current)
                                                    return [2 /*return*/];
                                                setCreating(false);
                                                return [7 /*endfinally*/];
                                            case 10: return [2 /*return*/];
                                        }
                                    });
                                }); } }, { children: creating ? ((0, jsx_runtime_1.jsx)(loading_1.default, __assign({ center: true, delay: 0 }, { children: "Adding Card..." }))) : ("Add Card") }))] })), (0, jsx_runtime_1.jsxs)("div", __assign({ style: { color: "#666", marginTop: "15px" } }, { children: [(0, jsx_runtime_1.jsx)(site_name_1.default, {}), " does not directly store any credit card numbers; instead they are stored securely by", " ", (0, jsx_runtime_1.jsx)(A_1.default, __assign({ href: "https://stripe.com/", external: true }, { children: "Stripe" })), ". PayPal or wire transfers for non-recurring purchases above $100 are also possible. ", (0, jsx_runtime_1.jsx)(help_email_1.default, {}), "."] }))] })))] })));
}
function CreditCard(props) {
    var brand = props.brand, last4 = props.last4, exp_month = props.exp_month, exp_year = props.exp_year, country = props.country, address_zip = props.address_zip;
    return ((0, jsx_runtime_1.jsxs)("div", __assign({ style: {
            backgroundColor: "#f0f0ff",
            border: "1px solid lightgrey",
            margin: "15px 0",
            padding: "10px",
            borderRadius: "5px",
            maxWidth: "300px",
        } }, { children: [(0, jsx_runtime_1.jsx)(Brand, { brand: brand }), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)(Number, { last4: last4 }), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)(ExpirationDate, { exp_month: exp_month, exp_year: exp_year }), (0, jsx_runtime_1.jsx)("br", {}), country, " ", address_zip, (0, jsx_runtime_1.jsx)("br", {})] })));
}
exports.CreditCard = CreditCard;
//# sourceMappingURL=payment-methods.js.map