"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Quota = exports.quotaColumn = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/*
 *  This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
const icon_1 = require("@cocalc/frontend/components/icon");
const misc_1 = require("@cocalc/util/misc");
const antd_1 = require("antd");
const avatar_1 = __importDefault(require("components/account/avatar"));
const name_1 = __importDefault(require("components/account/name"));
const select_users_1 = __importDefault(require("components/account/select-users"));
const A_1 = __importDefault(require("components/misc/A"));
const timestamp_1 = __importDefault(require("components/misc/timestamp"));
const loading_1 = __importDefault(require("components/share/loading"));
const post_1 = __importDefault(require("lib/api/post"));
const api_1 = __importDefault(require("lib/hooks/api"));
const use_customize_1 = __importDefault(require("lib/use-customize"));
const react_1 = require("react");
const editable_license_1 = require("./editable-license");
const license_1 = __importStar(require("./license"));
const renderTimestamp = (epoch) => (0, jsx_runtime_1.jsx)(timestamp_1.default, { epoch: epoch });
exports.quotaColumn = {
    title: ((0, jsx_runtime_1.jsxs)(antd_1.Popover, { title: "Quota", content: (0, jsx_runtime_1.jsx)("div", { style: { maxWidth: "75ex" }, children: "This is the license quota. If the license is active on a project, its quotas will be set to at least the values listed here." }), children: ["Quota", " "] })),
    width: "35%",
    responsive: ["sm"],
    render: (_, license) => (0, jsx_runtime_1.jsx)(Quota, { ...license }),
};
function Quota({ quota, state, upgrades }) {
    return state != null && state != "running" ? ((0, jsx_runtime_1.jsx)("span", { children: "\u2014" })) : ((0, jsx_runtime_1.jsxs)("span", { style: {
            wordWrap: "break-word",
            wordBreak: "break-word",
        }, children: [quota && (0, jsx_runtime_1.jsx)(license_1.Quota, { quota: quota }), upgrades && (0, jsx_runtime_1.jsx)("pre", { children: JSON.stringify(upgrades) })] }));
}
exports.Quota = Quota;
function TitleDescId({ title, description, id, onChange }) {
    return ((0, jsx_runtime_1.jsxs)("div", { style: {
            wordWrap: "break-word",
            wordBreak: "break-word",
            color: "#333",
        }, children: [(0, jsx_runtime_1.jsx)("div", { style: { fontFamily: "monospace", fontSize: "9pt" }, children: (0, jsx_runtime_1.jsx)(license_1.default, { license_id: id }) }), (0, jsx_runtime_1.jsx)(editable_license_1.EditableTitle, { license_id: id, title: title, onChange: onChange }), (0, jsx_runtime_1.jsx)(editable_license_1.EditableDescription, { license_id: id, description: description, onChange: onChange })] }));
}
function Managers({ managers, id, onChange }) {
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("div", { style: { maxHeight: "65px", overflowY: "auto" }, children: managers.map((account_id) => ((0, jsx_runtime_1.jsx)(avatar_1.default, { style: { margin: "0 5px 5px 0" }, account_id: account_id, size: 24, extra: (0, jsx_runtime_1.jsx)(RemoveManager, { license_id: id, managers: managers, account_id: account_id, onChange: onChange }) }, account_id))) }), (0, jsx_runtime_1.jsx)(AddManagers, { license_id: id, managers: managers, onChange: onChange })] }));
}
function RunLimit({ run_limit }) {
    return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: run_limit });
}
function LastUsed({ last_used }) {
    return renderTimestamp(last_used);
}
function Created({ created }) {
    return renderTimestamp(created);
}
function columns(onChange) {
    return [
        {
            responsive: ["xs"],
            title: "Managed Licenses",
            render: (_, license) => ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(TitleDescId, { ...license, onChange: onChange }), (0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsx)(license_1.DateRange, { ...license }) }), " ", "Run Limit: ", (0, jsx_runtime_1.jsx)(RunLimit, { ...license }), (0, jsx_runtime_1.jsxs)("div", { children: ["Quota: ", (0, jsx_runtime_1.jsx)(Quota, { ...license })] }), "Last Used: ", (0, jsx_runtime_1.jsx)(LastUsed, { ...license }), (0, jsx_runtime_1.jsx)("br", {}), "Created: ", (0, jsx_runtime_1.jsx)(Created, { ...license }), (0, jsx_runtime_1.jsxs)("div", { style: { border: "1px solid lightgrey", padding: "5px 15px" }, children: ["Managers ", (0, jsx_runtime_1.jsx)(Managers, { ...license, onChange: onChange })] })] })),
        },
        {
            responsive: ["sm"],
            title: ((0, jsx_runtime_1.jsx)(antd_1.Popover, { placement: "top", title: "Id, Title and Description of the License", content: (0, jsx_runtime_1.jsx)("div", { style: { maxWidth: "75ex" }, children: "The first line is the id of the license, which anybody can enter in various places to upgrade projects or courses. The title and description of the license help you keep track of what the license is for, and you can edit both fields here as well by clicking on them." }), children: "License" })),
            key: "title",
            width: "40%",
            sorter: { compare: (a, b) => (0, misc_1.cmp)(a.title, b.title) },
            render: (_, license) => ((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(TitleDescId, { ...license, onChange: onChange }), (0, jsx_runtime_1.jsx)("div", { children: (0, jsx_runtime_1.jsx)(license_1.DateRange, { ...license }) })] })),
        },
        {
            responsive: ["sm"],
            width: "15%",
            title: ((0, jsx_runtime_1.jsx)(antd_1.Popover, { title: "Managers", content: (0, jsx_runtime_1.jsx)("div", { style: { maxWidth: "75ex" }, children: "These are the managers of this license. They can see extra information about the license, the license is included in any dropdown where they can select a license, and they can add or remove other license managers. You are a manager of all licenses listed here." }), children: "Managers" })),
            key: "managers",
            render: (_, license) => (0, jsx_runtime_1.jsx)(Managers, { ...license, onChange: onChange }),
        },
        {
            responsive: ["sm"],
            title: ((0, jsx_runtime_1.jsx)(antd_1.Popover, { placement: "top", title: "Run Limit", content: (0, jsx_runtime_1.jsx)("div", { style: { maxWidth: "75ex" }, children: "The maximum number of simultaneous running projects that this license can upgrade. You can apply the license to any number of projects, but it only impacts this many projects at once." }), children: "Run Limit" })),
            align: "center",
            render: (_, license) => (0, jsx_runtime_1.jsx)(RunLimit, { ...license }),
            sorter: { compare: (a, b) => (0, misc_1.cmp)(a.run_limit, b.run_limit) },
        },
        exports.quotaColumn,
        {
            responsive: ["sm"],
            title: ((0, jsx_runtime_1.jsxs)(antd_1.Popover, { placement: "top", title: "When License was Last Used", content: (0, jsx_runtime_1.jsx)("div", { style: { maxWidth: "75ex" }, children: "This is when this license was last used to upgrade a project when the project was starting. It's the point in time when the project started." }), children: ["Last Used", " "] })),
            render: (_, license) => (0, jsx_runtime_1.jsx)(LastUsed, { ...license }),
            sorter: { compare: (a, b) => (0, misc_1.cmp)(a.last_used, b.last_used) },
        },
        /*   {
          responsive: ["sm"],
          title: (
            <Popover
              placement="top"
              title="When License Becomes Activate"
              content={
                <div style={{ maxWidth: "75ex" }}>
                  This is when the license becomes active. In can be in the future,
                  in which case the license will be valid and useful in the future,
                  but not right now.
                </div>
              }
            >
              Activates{" "}
            </Popover>
          ),
          render: (_, license) => <Activates {...license} />,
          sorter: { compare: (a, b) => cmp(a.activates, b.activates) },
        },
        {
          responsive: ["sm"],
          title: (
            <Popover
              placement="top"
              title="When License Expires"
              content={
                <div style={{ maxWidth: "75ex" }}>
                  This is when the license expires. Unless there is a subscription
                  that renews it, after this point in time the license will stop
                  upgrading projects.
                </div>
              }
            >
              Expires{" "}
            </Popover>
          ),
          render: (_, license) => <Expires {...license} />,
          sorter: { compare: (a, b) => cmp(a.expires, b.expires) },
        },*/
        {
            responsive: ["sm"],
            title: ((0, jsx_runtime_1.jsxs)(antd_1.Popover, { placement: "top", title: "When License was Created", content: (0, jsx_runtime_1.jsx)("div", { style: { maxWidth: "75ex" }, children: "This is when the license was created." }), children: ["Created", " "] })),
            render: (_, license) => (0, jsx_runtime_1.jsx)(Created, { ...license }),
            sorter: { compare: (a, b) => (0, misc_1.cmp)(a.created, b.created) },
        },
    ];
}
function ManagedLicenses() {
    let { result, error, call } = (0, api_1.default)("licenses/get-managed");
    const [search, setSearch] = (0, react_1.useState)("");
    const [showExpired, setShowExpired] = (0, react_1.useState)(false);
    const numExpired = (0, react_1.useMemo)(() => {
        if (!result)
            return 0;
        let n = 0;
        const t = new Date().valueOf();
        for (const x of result) {
            if (x.expires && x.expires <= t) {
                n += 1;
            }
        }
        return n;
    }, [result]);
    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, { style: { fontSize: "16pt", margin: "auto" } });
    }
    if (search) {
        result = doSearch(result, search);
    }
    if (!showExpired) {
        // filter out anything that is expired
        result = removeExpired(result);
    }
    function onChange() {
        call();
    }
    return ((0, jsx_runtime_1.jsxs)("div", { style: { width: "100%", overflowX: "auto", minHeight: "50vh" }, children: [(0, jsx_runtime_1.jsxs)("h3", { children: ["Licenses that you Manage (", result.length, ")"] }), "These are the licenses that you have purchased or been added to manage. You can add other people as managers of any of these licenses, if they need to be able to use these licenses to upgrade projects. You can also", " ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/billing/subscriptions", children: "manage your purchased subscriptions" }), " ", "and browse ", (0, jsx_runtime_1.jsx)(A_1.default, { href: "/billing/receipts", children: "your receipts and invoices" }), ".", (0, jsx_runtime_1.jsxs)("div", { style: { margin: "15px 0" }, children: [(0, jsx_runtime_1.jsxs)(antd_1.Checkbox, { disabled: numExpired == 0, style: { float: "right" }, checked: showExpired, onChange: (e) => setShowExpired(e.target.checked), children: ["Show Expired (", numExpired, ")"] }), (0, jsx_runtime_1.jsx)(antd_1.Input.Search, { placeholder: "Search...", allowClear: true, onChange: (e) => setSearch(e.target.value), style: { width: "50ex", maxWidth: "100%" } })] }), (0, jsx_runtime_1.jsx)(antd_1.Table, { columns: columns(onChange), dataSource: result, rowKey: "id", style: { marginTop: "15px" }, pagination: { hideOnSinglePage: true, pageSize: 100 } })] }));
}
exports.default = ManagedLicenses;
function doSearch(data, search) {
    const v = (0, misc_1.search_split)(search.toLowerCase().trim());
    const w = [];
    for (const x of data) {
        if (x["search"] == null) {
            x["search"] = `${x["title"] ?? ""} ${x["description"] ?? ""} ${x["id"]} ${x["info"]?.purchased?.subscription}`.toLowerCase();
        }
        if ((0, misc_1.search_match)(x["search"], v)) {
            w.push(x);
        }
    }
    return w;
}
function removeExpired(data) {
    const data1 = [];
    const now = new Date().valueOf();
    for (const x of data) {
        if (!(x.expires != null && x.expires <= now)) {
            data1.push(x);
        }
    }
    return data1;
}
function AddManagers({ license_id, managers, onChange }) {
    const [adding, setAdding] = (0, react_1.useState)(false);
    const [accountIds, setAccountIds] = (0, react_1.useState)([]);
    const [error, setError] = (0, react_1.useState)("");
    const { account } = (0, use_customize_1.default)();
    return ((0, jsx_runtime_1.jsxs)("div", { children: [adding && ((0, jsx_runtime_1.jsx)(antd_1.Button, { size: "small", style: { float: "right" }, onClick: () => {
                    setAdding(false);
                    setError("");
                    setAccountIds([]);
                }, children: "Cancel" })), (0, jsx_runtime_1.jsxs)(antd_1.Button, { disabled: adding, style: { marginTop: "5px" }, size: "small", onClick: () => {
                    setAdding(true);
                    setAccountIds([]);
                    setError("");
                }, children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "plus-circle" }), " Add"] }), adding && ((0, jsx_runtime_1.jsxs)("div", { style: { width: "300px", marginTop: "5px" }, children: [error && (0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: error }), (0, jsx_runtime_1.jsxs)(antd_1.Button, { disabled: accountIds.length == 0, onClick: async () => {
                            setError("");
                            const query = {
                                manager_site_licenses: {
                                    id: license_id,
                                    managers: managers.concat(accountIds),
                                },
                            };
                            try {
                                await (0, post_1.default)("/user-query", { query });
                                setAdding(false);
                                onChange?.();
                            }
                            catch (err) {
                                setError(err.message);
                            }
                        }, style: { marginBottom: "5px", width: "100%" }, type: "primary", children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { name: "check" }), " Add ", accountIds.length, " ", (0, misc_1.plural)(accountIds.length, "selected user")] }), (0, jsx_runtime_1.jsx)(select_users_1.default, { autoFocus: true, onChange: setAccountIds, exclude: managers.concat(account?.account_id ? [account.account_id] : []) })] }))] }));
}
function RemoveManager({ license_id, managers, account_id, onChange, }) {
    const [error, setError] = (0, react_1.useState)("");
    const { account } = (0, use_customize_1.default)();
    return ((0, jsx_runtime_1.jsx)(antd_1.Popconfirm, { zIndex: 20000 /* compare with user search */, title: (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [account?.account_id == account_id ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Remove ", (0, jsx_runtime_1.jsx)("b", { children: "yourself" }), " as a manager of this license?"] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: ["Remove manager", " ", (0, jsx_runtime_1.jsxs)("b", { children: [(0, jsx_runtime_1.jsx)(name_1.default, { account_id: account_id }), "?"] }), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)(name_1.default, { account_id: account_id }), " will no longer see this license listed under licenses they manage."] })), (0, jsx_runtime_1.jsx)("br", {}), " The license will ", (0, jsx_runtime_1.jsx)("i", { children: "not" }), " be automatically removed from any projects."] }), onConfirm: async () => {
            setError("");
            const query = {
                manager_site_licenses: {
                    id: license_id,
                    managers: managers.filter((x) => x != account_id),
                },
            };
            try {
                await (0, post_1.default)("/user-query", { query });
                onChange?.();
            }
            catch (err) {
                setError(err.message);
            }
        }, okText: "Remove", cancelText: "Cancel", children: (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("a", { children: "Remove as Manager..." }), error && ((0, jsx_runtime_1.jsx)(antd_1.Alert, { type: "error", message: "Error Removing Manager", description: error }))] }) }));
}
//# sourceMappingURL=managed.js.map