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

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

module.exports = require("cookies");

/***/ }),

/***/ 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");

/***/ }),

/***/ 124095:
/***/ ((__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__(677793);
/* harmony import */ var lib_api_is_post__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(447618);
/*
Create a support ticket.
*/ 


async function handle(req, res) {
    if (!(0,lib_api_is_post__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z)(req, res)) return;
    const { options  } = req.body;
    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 __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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getNameByEmail = void 0;
var pool_1 = __importDefault(__webpack_require__(541808));
function getName(account_id) {
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    pool = (0, pool_1.default)("long");
                    return [4 /*yield*/, pool.query("SELECT first_name, last_name FROM accounts WHERE account_id=$1", [account_id])];
                case 1:
                    rows = (_a.sent()).rows;
                    return [2 /*return*/, rowsToName(rows)];
            }
        });
    });
}
exports["default"] = getName;
function getNameByEmail(email_address) {
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    pool = (0, pool_1.default)("long");
                    return [4 /*yield*/, pool.query("SELECT first_name, last_name FROM accounts WHERE email_address=$1", [email_address])];
                case 1:
                    rows = (_a.sent()).rows;
                    return [2 /*return*/, rowsToName(rows)];
            }
        });
    });
}
exports.getNameByEmail = getNameByEmail;
function rowsToName(rows) {
    var _a, _b;
    if (rows.length == 0 || (!rows[0].first_name && !rows[0].last_name))
        return;
    return [(_a = rows[0].first_name) !== null && _a !== void 0 ? _a : "", (_b = rows[0].last_name) !== null && _b !== void 0 ? _b : ""].join(" ");
}
//# sourceMappingURL=get-name.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 __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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var logger_1 = __webpack_require__(227554);
var site_url_1 = __importDefault(__webpack_require__(661348));
var get_name_1 = __importStar(__webpack_require__(320966));
var zendesk_client_1 = __importDefault(__webpack_require__(214641));
var util_1 = __webpack_require__(662895);
var log = (0, logger_1.getLogger)("support:create-ticket");
function createTicket(options) {
    return __awaiter(this, void 0, void 0, function () {
        var client, account_id, email, files, type, subject, url, info, user, userResult, body, files_1, files_1_1, file, _a, _b, e_1_1, ticket, ticketResult;
        var e_1, _c;
        return __generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    log.debug("createTicket", options);
                    return [4 /*yield*/, (0, zendesk_client_1.default)()];
                case 1:
                    client = _d.sent();
                    account_id = options.account_id, email = options.email, files = options.files, type = options.type, subject = options.subject, url = options.url, info = options.info;
                    return [4 /*yield*/, getUser(email, account_id)];
                case 2:
                    user = _d.sent();
                    return [4 /*yield*/, client.users.createOrUpdate(user)];
                case 3:
                    userResult = _d.sent();
                    body = options.body;
                    if (url) {
                        body += "\n\n\nURL:\n".concat(url, "\n");
                    }
                    if (!(files && files.length > 0)) return [3 /*break*/, 11];
                    body += "\n\n\nRELEVANT FILES:\n\n";
                    _d.label = 4;
                case 4:
                    _d.trys.push([4, 9, 10, 11]);
                    files_1 = __values(files), files_1_1 = files_1.next();
                    _d.label = 5;
                case 5:
                    if (!!files_1_1.done) return [3 /*break*/, 8];
                    file = files_1_1.value;
                    _a = body;
                    _b = "\n\n- ".concat;
                    return [4 /*yield*/, toURL(file)];
                case 6:
                    body = _a + _b.apply("\n\n- ", [_d.sent(), "\n"]);
                    _d.label = 7;
                case 7:
                    files_1_1 = files_1.next();
                    return [3 /*break*/, 5];
                case 8: return [3 /*break*/, 11];
                case 9:
                    e_1_1 = _d.sent();
                    e_1 = { error: e_1_1 };
                    return [3 /*break*/, 11];
                case 10:
                    try {
                        if (files_1_1 && !files_1_1.done && (_c = files_1.return)) _c.call(files_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                    return [7 /*endfinally*/];
                case 11:
                    if (info) {
                        body += "\n\n\nBROWSER INFO:\n\n";
                        body += "\n\n- userAgent=\"".concat(info.userAgent, "\"");
                        body += "\n\n- browser=\"".concat(info.browser, "\"");
                    }
                    body += "\n\n\nUSER:\n\n";
                    body += "\n\n- account_id=\"".concat(account_id, "\"");
                    body += "\n\n- email=\"".concat(email, "\"");
                    ticket = {
                        ticket: {
                            comment: { body: body },
                            external_id: account_id,
                            subject: subject,
                            type: type,
                            // @ts-ignore: @types/node-zendesk is wrong:
                            requester_id: userResult.id,
                        },
                    };
                    log.debug("ticket ", ticket);
                    return [4 /*yield*/, client.tickets.create(ticket)];
                case 12:
                    ticketResult = _d.sent();
                    log.debug("got ", { ticketResult: ticketResult });
                    // @ts-ignore:  @types/node-zendesk is wrong about fields in ticketResult.
                    return [2 /*return*/, (0, util_1.urlToUserURL)(ticketResult.url)];
            }
        });
    });
}
exports["default"] = createTicket;
function toURL(_a) {
    var project_id = _a.project_id, path = _a.path;
    return __awaiter(this, void 0, void 0, function () {
        var s;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, (0, site_url_1.default)()];
                case 1:
                    s = (_b.sent()) + "/" + encodeURI("projects/".concat(project_id));
                    if (!path)
                        return [2 /*return*/, s];
                    return [2 /*return*/, s + encodeURI("/files/".concat(path))];
            }
        });
    });
}
function getUser(email, account_id) {
    return __awaiter(this, void 0, void 0, function () {
        var name;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    name = undefined;
                    if (!account_id) return [3 /*break*/, 2];
                    return [4 /*yield*/, (0, get_name_1.default)(account_id)];
                case 1:
                    name = _a.sent();
                    _a.label = 2;
                case 2:
                    if (!!name) return [3 /*break*/, 4];
                    return [4 /*yield*/, (0, get_name_1.getNameByEmail)(email)];
                case 3:
                    name = _a.sent();
                    _a.label = 4;
                case 4:
                    // name: must be at least one character, even " " is causing errors
                    // https://developer.zendesk.com/rest_api/docs/core/users
                    if (!(name === null || name === void 0 ? void 0 : name.trim())) {
                        name = email;
                    }
                    return [2 /*return*/, {
                            user: { name: name, email: email, external_id: account_id !== null && account_id !== void 0 ? 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, [549,1970,2921,2185,2014,6652,1050,6942,1034,3965,1808,9738,8312,540,7793,8416,4181,7554,5016,6177,1348,2061], () => (__webpack_exec__(124095)));
module.exports = __webpack_exports__;

})();