UNPKG

@kineticdata/react

Version:
717 lines (705 loc) 25.8 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"]; Object.defineProperty(exports, "__esModule", { value: true }); exports.updateSubmission = exports.submitSubmission = exports.searchSubmissions = exports.saveSubmissionMultipart = exports.importSubmissions = exports.importSubmissionStatus = exports.fetchSubmission = exports.exportSubmissions = exports.deleteSubmission = exports.createSubmission = exports.cloneSubmission = exports.VALID_TIMELINES = exports.VALID_KAPP_CORE_STATES = exports.VALID_DS_CORE_STATES = exports.SubmissionSearch = exports.MODE_IMPORT = exports.MODE_BULK = void 0; var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/toConsumableArray")); var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/objectSpread2")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/createClass")); var _axios = _interopRequireDefault(require("axios")); var _qs = _interopRequireDefault(require("qs")); var _helpers = require("../../helpers"); var _http = require("../http"); var _immutable = require("immutable"); // TODO: datastore is deprecated, remove datastore routes from paths. var VALID_TIMELINES = exports.VALID_TIMELINES = ['closedAt', 'createdAt', 'submittedAt', 'updatedAt']; var VALID_KAPP_CORE_STATES = exports.VALID_KAPP_CORE_STATES = ['Draft', 'Submitted', 'Closed']; var VALID_DS_CORE_STATES = exports.VALID_DS_CORE_STATES = ['Draft', 'Submitted']; var getValidCoreStates = function getValidCoreStates() { var datastore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; return datastore ? VALID_DS_CORE_STATES : VALID_KAPP_CORE_STATES; }; var nullFix = function nullFix(val) { var nullable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; return nullable ? val === '' || val === null ? 'null' : "\"".concat(val, "\"") : val === null ? '""' : "\"".concat(val, "\""); }; var SubmissionSearch = exports.SubmissionSearch = /*#__PURE__*/function () { function SubmissionSearch() { var datastore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; (0, _classCallCheck2["default"])(this, SubmissionSearch); this.searchMeta = { include: [] }; this.query = []; this.queryContext = []; this.queryContext.push(this.query); this.isDatastore = datastore; } /* * Context Management */ (0, _createClass2["default"])(SubmissionSearch, [{ key: "currentContext", value: function currentContext() { return this.queryContext[this.queryContext.length - 1]; } }, { key: "addContext", value: function addContext(context) { this.queryContext.push(context); } }, { key: "endContext", value: function endContext() { return this.queryContext.pop(); } /* * Execution Methods */ }, { key: "build", value: function build() { // Validate our attempt to search: this.validateOuter('Attempted to execute query before ending all groupings.'); // * if core state it set to something other than draft we must have an // beginning and ending date. // * ...? var query = this.compileQueryString(); return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, this.searchMeta), {}, { query: query }); } }, { key: "raw", value: function raw() { return this.query; } /* * Equality Methods */ }, { key: "eq", value: function eq(lvalue, rvalue) { this.currentContext().push({ op: 'eq', lvalue: lvalue, rvalue: rvalue }); return this; } }, { key: "sw", value: function sw(lvalue, rvalue) { this.validateDatastore(true); this.currentContext().push({ op: 'sw', lvalue: lvalue, rvalue: rvalue }); return this; } }, { key: "gt", value: function gt(lvalue, rvalue) { this.validateDatastore(); this.currentContext().push({ op: 'gt', lvalue: lvalue, rvalue: rvalue }); return this; } }, { key: "lt", value: function lt(lvalue, rvalue) { this.validateDatastore(); this.currentContext().push({ op: 'lt', lvalue: lvalue, rvalue: rvalue }); return this; } }, { key: "gteq", value: function gteq(lvalue, rvalue) { this.validateDatastore(); this.currentContext().push({ op: 'gteq', lvalue: lvalue, rvalue: rvalue }); return this; } }, { key: "lteq", value: function lteq(lvalue, rvalue) { this.validateDatastore(); this.currentContext().push({ op: 'lteq', lvalue: lvalue, rvalue: rvalue }); return this; } }, { key: "between", value: function between(lvalue, rvalue1, rvalue2) { this.validateDatastore(); this.currentContext().push({ op: 'between', lvalue: lvalue, rvalue1: rvalue1, rvalue2: rvalue2 }); return this; } }, { key: "in", value: function _in(lvalue, rvalue) { this.currentContext().push({ op: 'in', lvalue: lvalue, rvalue: rvalue }); return this; } /* * Grouping Methods */ }, { key: "or", value: function or() { this.validateDatastore(false); var op = { op: 'or', context: [] }; this.currentContext().push(op); this.addContext(op.context); return this; } }, { key: "and", value: function and() { var op = { op: 'and', context: [] }; this.currentContext().push(op); this.addContext(op.context); return this; } }, { key: "end", value: function end() { this.endContext(); return this; } /* * Sorting Methods */ }, { key: "sortBy", value: function sortBy(timeline) { this.validateDatastore(false); this.validateOuter('Sorting cannot be nested.'); // Check to see that timeline is in valid timelines. if (VALID_TIMELINES.includes(timeline)) { this.searchMeta.timeline = timeline; } return this; } }, { key: "sortDirection", value: function sortDirection(direction) { this.validateOuter('Sorting cannot be nested.'); if (direction !== 'ASC' && direction !== 'DESC') { throw new Error("Invalid sort direction: ".concat(direction)); } this.searchMeta.direction = direction; return this; } }, { key: "type", value: function type(_type) { this.validateDatastore(false); this.validateOuter('Type qualification cannot be nested'); this.searchMeta.type = _type; return this; } }, { key: "coreState", value: function coreState(_coreState) { this.validateOuter('Core State cannot be nested'); var validCoreStates = getValidCoreStates(this.isDatastore); if (!validCoreStates.includes(_coreState)) { throw new Error("Invalid Core State \"".concat(_coreState, "\". Expected: ").concat(validCoreStates.join())); } this.searchMeta.coreState = _coreState; return this; } }, { key: "startDate", value: function startDate(_startDate) { this.validateDatastore(false); this.validateOuter('Start Date cannot be nested.'); if (!(_startDate instanceof Date)) { throw new Error('Start Date must be a Date object.'); } this.searchMeta.start = _startDate.toISOString(); return this; } }, { key: "endDate", value: function endDate(_endDate) { this.validateDatastore(false); this.validateOuter('End Date cannot be nested.'); if (!(_endDate instanceof Date)) { throw new Error('End Date must be a Date object.'); } this.searchMeta.end = _endDate.toISOString(); return this; } }, { key: "limit", value: function limit(_limit) { this.validateOuter('Limit cannot be nested'); this.searchMeta.limit = _limit; return this; } }, { key: "pageToken", value: function pageToken(_pageToken) { this.validateOuter('Page Token cannot be nested'); this.searchMeta.pageToken = _pageToken; return this; } }, { key: "include", value: function include(_include) { this.searchMeta.include.push(_include); return this; } }, { key: "includes", value: function includes(_includes) { this.searchMeta.include = (0, _toConsumableArray2["default"])(new Set([].concat((0, _toConsumableArray2["default"])(this.searchMeta.include), (0, _toConsumableArray2["default"])(_includes)))); // _.uniq(_.concat(this.searchMeta.include, includes)); return this; } }, { key: "index", value: function index(_index) { this.validateDatastore(); this.searchMeta.index = _index ? _index.replace(/:UNIQUE$/, '') : _index; return this; } /* * Privately used utilities. */ }, { key: "validateOuter", value: function validateOuter(message) { if (this.queryContext.length > 1) { throw new Error(message); } } }, { key: "validateDatastore", value: function validateDatastore() { var datastore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; if (datastore === false && this.isDatastore) { throw new Error('This cannot be used with datastore searches.'); } else if (datastore && !this.isDatastore) { throw new Error('This can only be used with datastore searches.'); } } }, { key: "setDatastore", value: function setDatastore(datastore) { this.isDatastore = datastore; } }, { key: "compileQueryString", value: function compileQueryString() { function doCompileQueryString(queryContext, queryString) { var and = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var query = "".concat(queryString); queryContext.forEach(function (op, i) { if (i > 0) { query += and ? ' AND ' : ' OR '; } switch (op.op) { case 'eq': query += "".concat(op.lvalue, " = ").concat(nullFix(op.rvalue)); break; case 'sw': query += "".concat(op.lvalue, " =* ").concat(nullFix(op.rvalue)); break; case 'gt': query += "".concat(op.lvalue, " > ").concat(nullFix(op.rvalue, false)); break; case 'lt': query += "".concat(op.lvalue, " < ").concat(nullFix(op.rvalue, false)); break; case 'gteq': query += "".concat(op.lvalue, " >= ").concat(nullFix(op.rvalue, false)); break; case 'lteq': query += "".concat(op.lvalue, " <= ").concat(nullFix(op.rvalue, false)); break; case 'between': query += "".concat(op.lvalue, " BETWEEN (").concat(nullFix(op.rvalue1, false), ", ").concat(nullFix(op.rvalue2, false), ")"); break; case 'in': query += "".concat(op.lvalue, " IN ("); op.rvalue.forEach(function (rval, rvi) { if (rvi > 0) { query += ', '; } query += "".concat(nullFix(op.rvalue[rvi])); }); query += ')'; break; case 'or': case 'and': query += '( '; query += doCompileQueryString(op.context, '', op.op === 'and'); query += ')'; break; default: throw new Error("Unexpected operator type \"".concat(op.op, "\" encountered. Expected: eq, in, or, and.")); } }); return query; } return doCompileQueryString(this.query, '', true); } }]); return SubmissionSearch; }(); var searchSubmissions = exports.searchSubmissions = function searchSubmissions(options) { var kapp = options.kapp, form = options.form, search = options.search, _options$get = options.get, get = _options$get === void 0 ? false : _options$get; var endpoint = !get ? 'submissions-search' : 'submissions'; // Default kapp to 'datastore' if not provided to support deprecated datastore functionality var kappSlug = kapp || 'datastore'; var path = form ? "".concat(_helpers.bundle.apiLocation(), "/kapps/").concat(kappSlug, "/forms/").concat(form, "/").concat(endpoint) : "".concat(_helpers.bundle.apiLocation(), "/kapps/").concat(kappSlug, "/").concat(endpoint); var meta = (0, _objectSpread2["default"])({}, search); // Format includes. if (search.include.length > 0) { meta.include = search.include.join(); } delete meta.query; if (typeof search.query === 'string' && search.query.length > 0) { meta.q = search.query; } // Fetch the submissions. var promise = !get ? _axios["default"].post(path, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, meta), (0, _http.paramBuilder)(options)), { headers: (0, _http.headerBuilder)(options) }) : _axios["default"].get(path, { paramsSerializer: function paramsSerializer(params) { return _qs["default"].stringify(params); }, params: (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, meta), (0, _http.paramBuilder)(options)), headers: (0, _http.headerBuilder)(options) }); // Remove the response envelop and leave us with the submissions. promise = promise.then(function (response) { return { submissions: response.data.submissions, messages: response.data.messages, nextPageToken: response.data.nextPageToken, count: response.data.count, countPageToken: response.data.countPageToken }; }); // Clean up any errors we receive. Make srue this is the last thing so that it // cleans up all errors. promise = promise["catch"](_http.handleErrors); return promise; }; var fetchSubmission = exports.fetchSubmission = function fetchSubmission(options) { var id = options.id; if (!id) { throw new Error('fetchSubmission failed! The option "id" is required.'); } var path = options.datastore ? "".concat(_helpers.bundle.apiLocation(), "/datastore/submissions/").concat(id) : "".concat(_helpers.bundle.apiLocation(), "/submissions/").concat(id); return _axios["default"].get(path, { params: (0, _http.paramBuilder)(options), headers: (0, _http.headerBuilder)(options) }) // Remove the response envelop and leave us with the submission one. .then(function (response) { return { submission: response.data.submission }; }) // Clean up any errors we receive. Make sure this the last thing so that it // cleans up any errors. ["catch"](_http.handleErrors); }; var createSubmission = exports.createSubmission = function createSubmission(options) { var _options$kappSlug = options.kappSlug, kappSlug = _options$kappSlug === void 0 ? _helpers.bundle.kappSlug() : _options$kappSlug, formSlug = options.formSlug, values = options.values, _options$completed = options.completed, completed = _options$completed === void 0 ? true : _options$completed, coreState = options.coreState, parent = options.parent; if (!formSlug) { throw new Error('createSubmission failed! The option "formSlug" is required.'); } else if (!values) { throw new Error('createSubmission failed! The option "values" is required.'); } var path = kappSlug ? "".concat(_helpers.bundle.apiLocation(), "/kapps/").concat(kappSlug, "/forms/").concat(formSlug, "/submissions") : "".concat(_helpers.bundle.apiLocation(), "/datastore/forms/").concat(formSlug, "/submissions"); var params = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _http.paramBuilder)(options)), {}, { completed: completed, coreState: coreState, parent: parent }); return _axios["default"].post(path, { values: values }, { params: params, headers: (0, _http.headerBuilder)(options) }) // Remove the response envelop and leave us with the submission one. .then(function (response) { return { submission: response.data.submission }; }) // Clean up any errors we receive. Make sure this the last thing so that it // cleans up any errors. ["catch"](_http.handleErrors); }; var cloneSubmission = exports.cloneSubmission = function cloneSubmission(options) { var id = options.id, _options$completed2 = options.completed, completed = _options$completed2 === void 0 ? false : _options$completed2, _options$submission = options.submission, submission = _options$submission === void 0 ? {} : _options$submission, _options$files = options.files, files = _options$files === void 0 ? [] : _options$files; if (!id) { throw new Error('cloneSubmission failed! The option "id" is required.'); } var path = "".concat(_helpers.bundle.apiLocation(), "/submissions/").concat(id, "/clone"); var params = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _http.paramBuilder)(options)), {}, { completed: completed }); var formData = new FormData(); formData.append('submission', JSON.stringify(submission)); files.forEach(function (_ref) { var fieldName = _ref.fieldName, file = _ref.file, filename = _ref.filename; formData.append(fieldName, file, filename); }); return _axios["default"].post(path, formData, { params: params, headers: (0, _http.headerBuilder)(options) }) // Remove the response envelop and leave us with the submission one. .then(function (response) { return { submission: response.data.submission }; }) // Clean up any errors we receive. Make sure this the last thing so that it // cleans up any errors. ["catch"](_http.handleErrors); }; var updateSubmission = exports.updateSubmission = function updateSubmission(options) { var id = options.id, values = options.values; var path = options.datastore ? "".concat(_helpers.bundle.apiLocation(), "/datastore/submissions/").concat(id) : "".concat(_helpers.bundle.apiLocation(), "/submissions/").concat(id); var params = (0, _objectSpread2["default"])({}, (0, _http.paramBuilder)(options)); return _axios["default"].put(path, { values: values }, { params: params, headers: (0, _http.headerBuilder)(options) }) // Remove the response envelop and leave us with the submission one. .then(function (response) { return { submission: response.data.submission }; }) // Clean up any errors we receive. Make sure this the last thing so that it // cleans up any errors. ["catch"](_http.handleErrors); }; var saveSubmissionMultipart = exports.saveSubmissionMultipart = function saveSubmissionMultipart(options) { var kappSlug = options.kappSlug, formSlug = options.formSlug, id = options.id, values = options.values, files = options.files, coreState = options.coreState, parent = options.parent, _options$completed3 = options.completed, completed = _options$completed3 === void 0 ? !id : _options$completed3; // Determine whether we should use the create or update endpoint based on the // options provided (the rest of the HTTP request behaves the same way // regardless). var path; if (!!id) { path = "".concat(_helpers.bundle.apiLocation(), "/submissions-multipart/").concat(id); } else if (!!kappSlug && !!formSlug) { path = "".concat(_helpers.bundle.apiLocation(), "/kapps/").concat(kappSlug, "/forms/").concat(formSlug, "/submissions-multipart"); } else { throw new Error('saveSubmissionMultipart failed! Either the "id" option or the "kappSlug" and "formSlug" options need to be provided.'); } var headers = (0, _http.headerBuilder)(options); var params = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _http.paramBuilder)(options)), {}, { completed: completed, coreState: coreState, parent: parent }); var data = new FormData(); data.append('_submission', JSON.stringify({ values: values })); files.forEach(function (fileValue) { data.append((0, _immutable.get)(fileValue, 'field'), (0, _immutable.get)(fileValue, 'file')); }); return _axios["default"].post(path, data, { params: params, headers: headers }).then(function (response) { return { submission: response.data.submission }; })["catch"](_http.handleErrors); }; var submitSubmission = exports.submitSubmission = function submitSubmission(options) { var id = options.id, values = options.values, page = options.page, staged = options.staged, defer = options.defer; var path = options.datastore ? "".concat(_helpers.bundle.apiLocation(), "/datastore/submissions/").concat(id) : "".concat(_helpers.bundle.apiLocation(), "/submissions/").concat(id); var params = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _http.paramBuilder)(options)), {}, { page: page, staged: staged, defer: defer }); return _axios["default"].post(path, { values: values }, { params: params, headers: (0, _http.headerBuilder)(options) }) // Remove the response envelop and leave us with the submission one. .then(function (response) { return { submission: response.data.submission }; }) // Clean up any errors we receive. Make sure this the last thing so that it // cleans up any errors. ["catch"](_http.handleErrors); }; var deleteSubmission = exports.deleteSubmission = function deleteSubmission(options) { var id = options.id; if (!id) { throw new Error('deleteSubmission failed! The option "id" is required.'); } var path = options.datastore ? "".concat(_helpers.bundle.apiLocation(), "/datastore/submissions/").concat(id) : "".concat(_helpers.bundle.apiLocation(), "/submissions/").concat(id); return _axios["default"]["delete"](path, { params: (0, _http.paramBuilder)(options), headers: (0, _http.headerBuilder)(options) }) // Remove the response envelop and leave us with the submission one. .then(function (response) { return { submission: response.data.submission }; }) // Clean up any errors we receive. Make sure this the last thing so that it // cleans up any errors. ["catch"](_http.handleErrors); }; var exportSubmissions = exports.exportSubmissions = function exportSubmissions(options) { var kappSlug = options.kappSlug, formSlug = options.formSlug, onDownloadProgress = options.onDownloadProgress; if (!kappSlug) { throw new Error('exportSubmissions failed! The option "kappSlug" is required.'); } if (!formSlug) { throw new Error('exportSubmissions failed! The option "formSlug" is required.'); } var path = "".concat(_helpers.bundle.apiLocation(), "/kapps/").concat(kappSlug, "/forms/").concat(formSlug, "/submissions-search?export"); return _axios["default"].post(path, {}, { params: (0, _http.paramBuilder)(options), headers: (0, _http.headerBuilder)(options), onDownloadProgress: onDownloadProgress, responseType: 'blob' }); }; var MODE_IMPORT = exports.MODE_IMPORT = 'import'; var MODE_BULK = exports.MODE_BULK = 'bulk'; var modeToFn = function modeToFn(mode) { return mode === MODE_BULK ? 'post' : 'patch'; }; var importSubmissionStatus = exports.importSubmissionStatus = function importSubmissionStatus(options) { var kappSlug = options.kappSlug, formSlug = options.formSlug, jobId = options.jobId; var path = "".concat(_helpers.bundle.apiLocation(), "/kapps/").concat(kappSlug, "/forms/").concat(formSlug, "/submission-import/").concat(jobId); return _axios["default"].get(path, { params: (0, _http.paramBuilder)(options), headers: (0, _http.headerBuilder)(options) }).then(function (response) { return { backgroundJob: response.data.backgroundJob }; })["catch"](_http.handleErrors); }; var importSubmissions = exports.importSubmissions = function importSubmissions(options) { var kappSlug = options.kappSlug, formSlug = options.formSlug, onUploadProgress = options.onUploadProgress, file = options.file, _options$mode = options.mode, mode = _options$mode === void 0 ? MODE_IMPORT : _options$mode, signal = options.signal; if (!kappSlug) { throw new Error('importSubmissions failed! The option "kappSlug" is required.'); } if (!formSlug) { throw new Error('importSubmissions failed! The option "formSlug" is required.'); } if (!file) { throw new Error('importSubmissions failed! The option "file" is required.'); } var path = "".concat(_helpers.bundle.apiLocation(), "/kapps/").concat(kappSlug, "/forms/").concat(formSlug, "/submissions?import"); return _axios["default"][modeToFn(mode)](path, file, { signal: signal, data: file, params: (0, _http.paramBuilder)(options), headers: (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (0, _http.headerBuilder)(options)), {}, { 'Content-Type': 'application/csv' }), onUploadProgress: onUploadProgress }).then(function (response) { return response.data; })["catch"](function (error) { if (error.response && error.response.data && error.response.data.errors) { return error.response.data; } else { return (0, _http.handleErrors)(error); } }); };