"use strict";
(() => {
var exports = {};
exports.id = 6622;
exports.ids = [6622];
exports.modules = {

/***/ 439491:
/***/ ((module) => {

module.exports = require("assert");

/***/ }),

/***/ 714300:
/***/ ((module) => {

module.exports = require("buffer");

/***/ }),

/***/ 706113:
/***/ ((module) => {

module.exports = require("crypto");

/***/ }),

/***/ 809523:
/***/ ((module) => {

module.exports = require("dns");

/***/ }),

/***/ 582361:
/***/ ((module) => {

module.exports = require("events");

/***/ }),

/***/ 657147:
/***/ ((module) => {

module.exports = require("fs");

/***/ }),

/***/ 113685:
/***/ ((module) => {

module.exports = require("http");

/***/ }),

/***/ 795687:
/***/ ((module) => {

module.exports = require("https");

/***/ }),

/***/ 241808:
/***/ ((module) => {

module.exports = require("net");

/***/ }),

/***/ 822037:
/***/ ((module) => {

module.exports = require("os");

/***/ }),

/***/ 371017:
/***/ ((module) => {

module.exports = require("path");

/***/ }),

/***/ 677282:
/***/ ((module) => {

module.exports = require("process");

/***/ }),

/***/ 285477:
/***/ ((module) => {

module.exports = require("punycode");

/***/ }),

/***/ 863477:
/***/ ((module) => {

module.exports = require("querystring");

/***/ }),

/***/ 12781:
/***/ ((module) => {

module.exports = require("stream");

/***/ }),

/***/ 371576:
/***/ ((module) => {

module.exports = require("string_decoder");

/***/ }),

/***/ 924404:
/***/ ((module) => {

module.exports = require("tls");

/***/ }),

/***/ 76224:
/***/ ((module) => {

module.exports = require("tty");

/***/ }),

/***/ 257310:
/***/ ((module) => {

module.exports = require("url");

/***/ }),

/***/ 473837:
/***/ ((module) => {

module.exports = require("util");

/***/ }),

/***/ 959796:
/***/ ((module) => {

module.exports = require("zlib");

/***/ }),

/***/ 26438:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getParams)
/* harmony export */ });
function getParams(req) {
    if (req?.method == "POST") {
        return new Proxy({}, {
            get (_, key) {
                return req.body?.[key];
            }
        });
    /*
    // Disabled, since this could lead to a sneaky click on a link attack.
    // Should only be enabled for dev purposes.
    } else if (req?.method == "GET") {
    return new Proxy(
      {},
      {
        get(_, key) {
          if (typeof key != "string") {
            return undefined;
          }
          return req.query?.[key];
        },
      }
    );
*/ } else {
        // only support params for POST requests.
        return {};
    }
}


/***/ }),

/***/ 810298:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handle)
/* harmony export */ });
/* harmony import */ var _cocalc_server_support_create_ticket__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5445);
/* harmony import */ var _cocalc_server_support_create_ticket__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_support_create_ticket__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lib_account_get_account__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(559459);
/* harmony import */ var lib_api_get_params__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(26438);
/*
Create a support ticket.
*/ 


async function handle(req, res) {
    const { options  } = (0,lib_api_get_params__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z)(req);
    let url;
    try {
        const account_id = await (0,lib_account_get_account__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z)(req);
        url = await _cocalc_server_support_create_ticket__WEBPACK_IMPORTED_MODULE_0___default()({
            ...options,
            account_id
        });
    } catch (err) {
        res.json({
            error: `${err.message}`
        });
        return;
    }
    res.json({
        url
    });
}


/***/ }),

/***/ 320966:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


// If no such account or no name set, returns "Unknown User".
// Answers are cached for a while.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getNameByEmail = void 0;
const pool_1 = __importDefault(__webpack_require__(541808));
async function getName(account_id) {
    const pool = (0, pool_1.default)("long");
    const { rows } = await pool.query("SELECT first_name, last_name FROM accounts WHERE account_id=$1", [account_id]);
    return rowsToName(rows);
}
exports["default"] = getName;
async function getNameByEmail(email_address) {
    const pool = (0, pool_1.default)("long");
    const { rows } = await pool.query("SELECT first_name, last_name FROM accounts WHERE email_address=$1", [email_address]);
    return rowsToName(rows);
}
exports.getNameByEmail = getNameByEmail;
function rowsToName(rows) {
    if (rows.length == 0 || (!rows[0].first_name && !rows[0].last_name))
        return;
    return [rows[0].first_name ?? "", rows[0].last_name ?? ""].join(" ");
}
//# sourceMappingURL=get-name.js.map

/***/ }),

/***/ 661348:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const server_settings_1 = __webpack_require__(526177);
const base_path_1 = __importDefault(__webpack_require__(8312));
// Returns url of this site in terms of the base path (determined
// by an env variable when server starts) and the "Domain name"
// setting of site settings.  This URL does NOT end in a /
async function siteURL(dns) {
    if (!dns) {
        dns = (await (0, server_settings_1.getServerSettings)()).dns?.toLowerCase();
    }
    if (!dns) {
        dns = "localhost";
    }
    if (!dns.startsWith("http")) {
        dns = "https://" + dns;
    }
    return `${dns}${base_path_1.default == "/" ? "" : base_path_1.default}`;
}
exports["default"] = siteURL;
//# sourceMappingURL=site-url.js.map

/***/ }),

/***/ 5445:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {


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 }));
const logger_1 = __webpack_require__(227554);
const site_url_1 = __importDefault(__webpack_require__(661348));
const get_name_1 = __importStar(__webpack_require__(320966));
const zendesk_client_1 = __importDefault(__webpack_require__(214641));
const util_1 = __webpack_require__(662895);
const log = (0, logger_1.getLogger)("support:create-ticket");
async function createTicket(options) {
    log.debug("createTicket", options);
    const client = await (0, zendesk_client_1.default)();
    const { account_id, email, files, type, subject, url, info } = options;
    const user = await getUser(email, account_id);
    // create corresponding zendesk user, or get current user if already created.
    const userResult = await client.users.createOrUpdate(user);
    let { body } = options;
    if (url) {
        body += `\n\n\nURL:\n${url}\n`;
    }
    if (files && files.length > 0) {
        body += "\n\n\nRELEVANT FILES:\n\n";
        for (const file of files) {
            body += `\n\n- ${await toURL(file)}\n`;
        }
    }
    if (info) {
        body += "\n\n\nBROWSER INFO:\n\n";
        body += `\n\n- userAgent="${info.userAgent}"`;
        body += `\n\n- browser="${info.browser}"`;
    }
    body += "\n\n\nUSER:\n\n";
    body += `\n\n- account_id="${account_id}"`;
    body += `\n\n- email="${email}"`;
    // It's very helpful to look https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node-zendesk/index.d.ts
    // and
    // https://github.com/blakmatrix/node-zendesk/tree/master/examples
    // https://developer.zendesk.com/api-reference/
    const ticket = {
        ticket: {
            comment: { body },
            external_id: account_id,
            subject,
            type: type,
            // @ts-ignore: @types/node-zendesk is wrong:
            requester_id: userResult.id,
        },
    };
    log.debug("ticket ", ticket);
    const ticketResult = await client.tickets.create(ticket);
    log.debug("got ", { ticketResult });
    // @ts-ignore:  @types/node-zendesk is wrong about fields in ticketResult.
    return (0, util_1.urlToUserURL)(ticketResult.url);
}
exports["default"] = createTicket;
async function toURL({ project_id, path, }) {
    let s = (await (0, site_url_1.default)()) + "/" + encodeURI(`projects/${project_id}`);
    if (!path)
        return s;
    return s + encodeURI(`/files/${path}`);
}
async function getUser(email, account_id) {
    let name = undefined;
    if (account_id) {
        name = await (0, get_name_1.default)(account_id);
    }
    if (!name) {
        name = await (0, get_name_1.getNameByEmail)(email);
    }
    // name: must be at least one character, even " " is causing errors
    // https://developer.zendesk.com/rest_api/docs/core/users
    if (!name?.trim()) {
        name = email;
    }
    return {
        user: { name, email, external_id: account_id ?? null },
    };
}
//# sourceMappingURL=create-ticket.js.map

/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [8180,2921,9557,5245,6652,6942,5517,6099,4069,1808,4006,8312,5710,9459,4181,4557,7896,6177,5486], () => (__webpack_exec__(810298)));
module.exports = __webpack_exports__;

})();