"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const 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
 */
const react_1 = require("react");
const api_1 = __importDefault(require("lib/hooks/api"));
const loading_1 = __importDefault(require("components/share/loading"));
const A_1 = __importDefault(require("components/misc/A"));
const timestamp_1 = __importDefault(require("components/misc/timestamp"));
const antd_1 = require("antd");
const misc_1 = require("@cocalc/util/misc");
const help_email_1 = __importDefault(require("components/misc/help-email"));
const icon_1 = require("@cocalc/frontend/components/icon");
const license_1 = __importDefault(require("components/licenses/license"));
const mounted_1 = __importDefault(require("lib/hooks/mounted"));
const post_1 = __importDefault(require("lib/api/post"));
function Description({ latest_invoice, metadata, invoices }) {
    for (const invoice of invoices.data) {
        if (latest_invoice != invoice.id)
            continue;
        const cnt = invoice.lines?.total_count ?? 1;
        const url = invoice.hosted_invoice_url;
        return ((0, jsx_runtime_1.jsxs)("div", { style: { wordWrap: "break-word", wordBreak: "break-word" }, children: [invoice.lines.data[0].description, cnt > 1 && ", etc.", url && ((0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsxs)(A_1.default, { href: url, children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "external-link" }), " Invoice"] }) })), metadata?.license_id && ((0, jsx_runtime_1.jsxs)("div", { children: ["License: ", (0, jsx_runtime_1.jsx)(license_1.default, { license_id: metadata?.license_id })] }))] }));
    }
    return null;
}
function Period({ current_period_start, current_period_end, cancel_at_period_end, }) {
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(timestamp_1.default, { epoch: 1000 * current_period_start, dateOnly: true, absolute: true }), " \u2013", " ", (0, jsx_runtime_1.jsx)(timestamp_1.default, { epoch: 1000 * current_period_end, dateOnly: true, absolute: true }), cancel_at_period_end && ((0, jsx_runtime_1.jsxs)("span", { children: [(0, jsx_runtime_1.jsx)("br", {}), "(will cancel at period end)"] }))] }));
}
function Status({ status }) {
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, misc_1.capitalize)(status) });
}
function Cost({ plan }) {
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, misc_1.stripeAmount)(plan.amount, plan.currency), " for", " ", (0, misc_1.planInterval)(plan.interval, plan.interval_count)] }));
}
function Cancel({ cancel_at_period_end, cancel_at, id, onChange, }) {
    const [error, setError] = (0, react_1.useState)("");
    const [cancelling, setCancelling] = (0, react_1.useState)(false);
    const isMounted = (0, mounted_1.default)();
    const isCancelled = cancel_at_period_end || cancel_at != null;
    return ((0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsxs)(antd_1.Popconfirm, { placement: "bottomLeft", title: (0, jsx_runtime_1.jsxs)("div", { style: { maxWidth: "500px" }, children: ["Cancel? Are you sure you want to", " ", (0, jsx_runtime_1.jsx)("b", { children: "cancel this subscription at period end" }), "? If you cancel your subscription, it will run to the end of the subscription period, but will not be renewed when the current (already paid for) period ends. If you need further clarification or need a refund,", " ", (0, jsx_runtime_1.jsx)(help_email_1.default, { lower: true }), "."] }), onConfirm: async () => {
                setCancelling(true);
                setError("");
                try {
                    await (0, post_1.default)("billing/cancel-subscription", { id });
                }
                catch (err) {
                    if (!isMounted.current)
                        return;
                    setError(err.message);
                }
                finally {
                    if (!isMounted.current)
                        return;
                    setCancelling(false);
                    onChange();
                }
            }, okText: "Yes, cancel at period end (do not auto-renew)", cancelText: "Make no change", children: [(0, jsx_runtime_1.jsx)(antd_1.Button, { disabled: isCancelled || cancelling, type: "dashed", children: cancelling ? ((0, jsx_runtime_1.jsx)(loading_1.default, { delay: 0, children: "Cancelling..." })) : (`Cancel${isCancelled ? "led" : ""}`) }), error && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: { marginTop: "15px" }, type: "error", message: `Error: ${error}` }))] }) }));
}
function columns(invoices, onChange) {
    return [
        {
            responsive: ["xs"],
            title: "Subscriptions",
            render: (_, sub) => ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(Description, { ...sub, invoices: invoices }), "Status: ", (0, jsx_runtime_1.jsx)(Status, { ...sub }), (0, jsx_runtime_1.jsx)("br", {}), "Period: ", (0, jsx_runtime_1.jsx)(Period, { ...sub }), (0, jsx_runtime_1.jsx)("br", {}), "Cost: ", (0, jsx_runtime_1.jsx)(Cost, { ...sub }), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)(Cancel, { ...sub, onChange: onChange })] })),
        },
        {
            responsive: ["sm"],
            title: "Description",
            width: "50%",
            render: (_, sub) => (0, jsx_runtime_1.jsx)(Description, { ...sub, invoices: invoices }),
        },
        {
            responsive: ["sm"],
            title: "Status",
            align: "center",
            render: (_, sub) => (0, jsx_runtime_1.jsx)(Status, { ...sub }),
            sorter: { compare: (a, b) => (0, misc_1.cmp)(a.status, b.status) },
        },
        {
            responsive: ["sm"],
            title: "Period",
            align: "center",
            render: (_, sub) => (0, jsx_runtime_1.jsx)(Period, { ...sub }),
        },
        {
            responsive: ["sm"],
            title: "Cost",
            sorter: { compare: (a, b) => (0, misc_1.cmp)(a.plan.amount, b.plan.amount) },
            render: (_, sub) => (0, jsx_runtime_1.jsx)(Cost, { ...sub }),
        },
        {
            responsive: ["sm"],
            title: "Cancel",
            align: "center",
            render: (_, sub) => (0, jsx_runtime_1.jsx)(Cancel, { ...sub, onChange: onChange }),
        },
    ];
}
function Subscriptions() {
    const subscriptions = (0, api_1.default)("billing/get-subscriptions");
    const invoices = (0, api_1.default)("billing/get-invoices-and-receipts");
    if (subscriptions.error) {
        return (0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: subscriptions.error });
    }
    if (!subscriptions.result) {
        return (0, jsx_runtime_1.jsx)(loading_1.default, {});
    }
    if (invoices.error) {
        return (0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: invoices.error });
    }
    if (!invoices.result) {
        return (0, jsx_runtime_1.jsx)(loading_1.default, {});
    }
    function onChange() {
        subscriptions.call();
        invoices.call();
    }
    return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsxs)("h3", { children: ["Your Subscriptions (", subscriptions.result?.data?.length ?? 0, ")"] }), (0, jsx_runtime_1.jsxs)("div", { style: { maxWidth: "800px", margin: "15px 0" }, children: ["Your subscriptions are listed below. You can view invoices, get information about the license or plan corresponding to a subscription, and cancel a subscription at period end. You can also", " ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/store/site-license", children: "create a new site license subscription" }), ". If you have any questions ", (0, jsx_runtime_1.jsx)(help_email_1.default, { lower: true }), "."] }), (0, jsx_runtime_1.jsx)(antd_1.Table, { columns: columns(invoices.result, onChange), dataSource: subscriptions.result?.data ?? [], rowKey: "id", pagination: { hideOnSinglePage: true, pageSize: 100 }, style: { overflowX: "auto" } }), subscriptions.result?.has_more && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: { margin: "15px" }, type: "warning", showIcon: true, message: "WARNING: Some of your subscriptions are not displayed above, since there are so many." }))] }));
}
exports.default = Subscriptions;
//# sourceMappingURL=subscriptions.js.map