"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 __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 __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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
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
 */
var react_1 = require("react");
var api_1 = __importDefault(require("lib/hooks/api"));
var loading_1 = __importDefault(require("components/share/loading"));
var A_1 = __importDefault(require("components/misc/A"));
var timestamp_1 = __importDefault(require("components/misc/timestamp"));
var antd_1 = require("antd");
var misc_1 = require("@cocalc/util/misc");
var help_email_1 = __importDefault(require("components/misc/help-email"));
var icon_1 = require("@cocalc/frontend/components/icon");
var license_1 = __importDefault(require("components/licenses/license"));
var mounted_1 = __importDefault(require("lib/hooks/mounted"));
var post_1 = __importDefault(require("lib/api/post"));
function Description(_a) {
    var e_1, _b;
    var _c, _d;
    var latest_invoice = _a.latest_invoice, metadata = _a.metadata, invoices = _a.invoices;
    try {
        for (var _e = __values(invoices.data), _f = _e.next(); !_f.done; _f = _e.next()) {
            var invoice = _f.value;
            if (latest_invoice != invoice.id)
                continue;
            var cnt = (_d = (_c = invoice.lines) === null || _c === void 0 ? void 0 : _c.total_count) !== null && _d !== void 0 ? _d : 1;
            var url = invoice.hosted_invoice_url;
            return ((0, jsx_runtime_1.jsxs)("div", __assign({ 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, __assign({ href: url }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "external-link" }), " Invoice"] })) })), (metadata === null || metadata === void 0 ? void 0 : metadata.license_id) && ((0, jsx_runtime_1.jsxs)("div", { children: ["License: ", (0, jsx_runtime_1.jsx)(license_1.default, { license_id: metadata === null || metadata === void 0 ? void 0 : metadata.license_id })] }))] })));
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return null;
}
function Period(_a) {
    var current_period_start = _a.current_period_start, current_period_end = _a.current_period_end, cancel_at_period_end = _a.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(_a) {
    var status = _a.status;
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, misc_1.capitalize)(status) });
}
function Cost(_a) {
    var plan = _a.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(_a) {
    var _this = this;
    var cancel_at_period_end = _a.cancel_at_period_end, cancel_at = _a.cancel_at, id = _a.id, onChange = _a.onChange;
    var _b = __read((0, react_1.useState)(""), 2), error = _b[0], setError = _b[1];
    var _c = __read((0, react_1.useState)(false), 2), cancelling = _c[0], setCancelling = _c[1];
    var isMounted = (0, mounted_1.default)();
    var isCancelled = cancel_at_period_end || cancel_at != null;
    return ((0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsxs)(antd_1.Popconfirm, __assign({ placement: "bottomLeft", title: (0, jsx_runtime_1.jsxs)("div", __assign({ 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: function () { return __awaiter(_this, void 0, void 0, function () {
                var err_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            setCancelling(true);
                            setError("");
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, 4, 5]);
                            return [4 /*yield*/, (0, post_1.default)("billing/cancel-subscription", { id: id })];
                        case 2:
                            _a.sent();
                            return [3 /*break*/, 5];
                        case 3:
                            err_1 = _a.sent();
                            if (!isMounted.current)
                                return [2 /*return*/];
                            setError(err_1.message);
                            return [3 /*break*/, 5];
                        case 4:
                            if (!isMounted.current)
                                return [2 /*return*/];
                            setCancelling(false);
                            onChange();
                            return [7 /*endfinally*/];
                        case 5: return [2 /*return*/];
                    }
                });
            }); }, okText: "Yes, cancel at period end (do not auto-renew)", cancelText: "Make no change" }, { children: [(0, jsx_runtime_1.jsx)(antd_1.Button, __assign({ disabled: isCancelled || cancelling, type: "dashed" }, { children: cancelling ? ((0, jsx_runtime_1.jsx)(loading_1.default, __assign({ delay: 0 }, { children: "Cancelling..." }))) : ("Cancel".concat(isCancelled ? "led" : "")) })), error && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { style: { marginTop: "15px" }, type: "error", message: "Error: ".concat(error) }))] })) }));
}
function columns(invoices, onChange) {
    return [
        {
            responsive: ["xs"],
            title: "Subscriptions",
            render: function (_, sub) { return ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(Description, __assign({}, sub, { invoices: invoices })), "Status: ", (0, jsx_runtime_1.jsx)(Status, __assign({}, sub)), (0, jsx_runtime_1.jsx)("br", {}), "Period: ", (0, jsx_runtime_1.jsx)(Period, __assign({}, sub)), (0, jsx_runtime_1.jsx)("br", {}), "Cost: ", (0, jsx_runtime_1.jsx)(Cost, __assign({}, sub)), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)(Cancel, __assign({}, sub, { onChange: onChange }))] })); },
        },
        {
            responsive: ["sm"],
            title: "Description",
            width: "50%",
            render: function (_, sub) { return (0, jsx_runtime_1.jsx)(Description, __assign({}, sub, { invoices: invoices })); },
        },
        {
            responsive: ["sm"],
            title: "Status",
            align: "center",
            render: function (_, sub) { return (0, jsx_runtime_1.jsx)(Status, __assign({}, sub)); },
            sorter: { compare: function (a, b) { return (0, misc_1.cmp)(a.status, b.status); } },
        },
        {
            responsive: ["sm"],
            title: "Period",
            align: "center",
            render: function (_, sub) { return (0, jsx_runtime_1.jsx)(Period, __assign({}, sub)); },
        },
        {
            responsive: ["sm"],
            title: "Cost",
            sorter: { compare: function (a, b) { return (0, misc_1.cmp)(a.plan.amount, b.plan.amount); } },
            render: function (_, sub) { return (0, jsx_runtime_1.jsx)(Cost, __assign({}, sub)); },
        },
        {
            responsive: ["sm"],
            title: "Cancel",
            align: "center",
            render: function (_, sub) { return (0, jsx_runtime_1.jsx)(Cancel, __assign({}, sub, { onChange: onChange })); },
        },
    ];
}
function Subscriptions() {
    var _a, _b, _c, _d, _e, _f;
    var subscriptions = (0, api_1.default)("billing/get-subscriptions");
    var 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 (", (_c = (_b = (_a = subscriptions.result) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0, ")"] }), (0, jsx_runtime_1.jsxs)("div", __assign({ 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, __assign({ 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: (_e = (_d = subscriptions.result) === null || _d === void 0 ? void 0 : _d.data) !== null && _e !== void 0 ? _e : [], rowKey: "id", pagination: { hideOnSinglePage: true, pageSize: 100 }, style: { overflowX: "auto" } }), ((_f = subscriptions.result) === null || _f === void 0 ? void 0 : _f.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