Subversion Repositories SmartDukaan

Rev

Rev 37282 | Rev 37564 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 37282 Rev 37458
Line 23... Line 23...
23
    );
23
    );
24
}
24
}
25
 
25
 
26
let IdempotencyKey = uuidv4();
26
let IdempotencyKey = uuidv4();
27
 
27
 
-
 
28
// bootbox is served from a CDN; if that request is blocked the reporter itself
-
 
29
// throws and the failure is swallowed. Always fall back to the native dialog.
-
 
30
function showAlert(message) {
-
 
31
    if (typeof bootbox !== 'undefined' && bootbox && typeof bootbox.alert === 'function') {
-
 
32
        bootbox.alert(message);
-
 
33
    } else {
-
 
34
        alert(message);
-
 
35
    }
-
 
36
}
-
 
37
 
28
function badRequestAlert(response) {
38
function badRequestAlert(response) {
29
    //console.log(response.responseText);
39
    //console.log(response.responseText);
30
    try {
40
    try {
31
        var errorObject = JSON.parse(response.responseText);
41
        var errorObject = JSON.parse(response.responseText);
32
        errorObject = errorObject.response;
42
        errorObject = errorObject.response;
33
        bootbox.alert('Bad Request\n' + 'rejectedType : '
43
        showAlert('Bad Request\n' + 'rejectedType : '
34
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
44
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
35
            + errorObject.rejectedValue + '\n' + 'message : '
45
            + errorObject.rejectedValue + '\n' + 'message : '
36
            + errorObject.message);
46
            + errorObject.message);
37
    } catch (e) {
47
    } catch (e) {
38
        console.log("response.responseText", response.responseText);
48
        console.log("response.responseText", response.responseText);
39
        bootbox.alert("Error occurred! Please contact your manager");
49
        showAlert("Error occurred! Please contact your manager");
40
    }
50
    }
41
}
51
}
42
 
52
 
43
function internalServerErrorAlert(response) {
53
function internalServerErrorAlert(response) {
44
    // console.log(response.responseText);
54
    // console.log(response.responseText);
45
    try {
55
    try {
46
        var errorObject = JSON.parse(response.responseText);
56
        var errorObject = JSON.parse(response.responseText);
47
        errorObject = errorObject.response;
57
        errorObject = errorObject.response;
48
        bootbox.alert('Internal Server Error\n' + 'rejectedType : '
58
        showAlert('Internal Server Error\n' + 'rejectedType : '
49
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
59
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
50
            + errorObject.rejectedValue + '\n' + 'message : '
60
            + errorObject.rejectedValue + '\n' + 'message : '
51
            + errorObject.message);
61
            + errorObject.message);
52
    } catch (e) {
62
    } catch (e) {
53
        console.log("response.responseText", response.responseText);
63
        console.log("response.responseText", response.responseText);
54
        bootbox.alert("Error occurred! Please contact your manager");
64
        showAlert("Error occurred! Please contact your manager");
55
    }
65
    }
56
}
66
}
57
 
67
 
58
$(document).ajaxError(function (event, jqxhr, settings, thrownError) {
68
$(document).ajaxError(function (event, jqxhr, settings, thrownError) {
59
    if (typeof loaderDialogObj != "undefined") {
69
    if (typeof loaderDialogObj != "undefined") {
60
        loaderDialogObj.modal('hide');
70
        loaderDialogObj.modal('hide');
61
        // $('div.modal-backdrop.fade').remove();
71
        // $('div.modal-backdrop.fade').remove();
62
    }
72
    }
-
 
73
    // Callers that surface their own actionable message opt out here, otherwise the
-
 
74
    // operator gets a useful message and a generic "rejectedType : undefined" one.
-
 
75
    if (settings && settings.suppressGlobalError) {
-
 
76
        return;
-
 
77
    }
63
    if (jqxhr.status == 400) {
78
    if (jqxhr.status == 400) {
64
        // $('#error-prompt-model').modal();
79
        // $('#error-prompt-model').modal();
65
        badRequestAlert(jqxhr);
80
        badRequestAlert(jqxhr);
66
    } else {
81
    } else {
67
        internalServerErrorAlert(jqxhr);
82
        internalServerErrorAlert(jqxhr);
Line 212... Line 227...
212
            response = ajaxResponse;
227
            response = ajaxResponse;
213
        });
228
        });
214
    return response;
229
    return response;
215
}
230
}
216
 
231
 
217
function doAjaxUploadRequestHandler(urlString, httpType, file, callback_function) {
232
function doAjaxUploadRequestHandler(urlString, httpType, file, callback_function, error_callback) {
218
    var formData = new FormData();
233
    var formData = new FormData();
219
    formData.append("file", file);
234
    formData.append("file", file);
220
    $.ajax({
235
    $.ajax({
221
        url: urlString,
236
        url: urlString,
222
        type: httpType,
237
        type: httpType,
Line 225... Line 240...
225
        async: true,
240
        async: true,
226
        cache: false,
241
        cache: false,
227
        contentType: false,
242
        contentType: false,
228
        enctype: 'multipart/form-data',
243
        enctype: 'multipart/form-data',
229
        processData: false,
244
        processData: false,
-
 
245
        suppressGlobalError: typeof error_callback === 'function',
230
        success: function (response) {
246
        success: function (response) {
231
            // console.log("response"+JSON.stringify(data));
247
            // console.log("response"+JSON.stringify(data));
232
            callback_function(response);
248
            callback_function(response);
-
 
249
        },
-
 
250
        error: function (xhr) {
-
 
251
            var msg = uploadErrorMessage(xhr);
-
 
252
            console.error(httpType + ' ' + urlString + ' failed: ' + xhr.status + ' - ' + msg);
-
 
253
            if (typeof error_callback === 'function') {
-
 
254
                error_callback(xhr, msg);
-
 
255
            }
233
        }
256
        }
234
    });
257
    });
235
}
258
}
236
 
259
 
-
 
260
/**
-
 
261
 * /document-upload answers a rejection with {response:{document_id, message, result}},
-
 
262
 * while the duplicate-request guard answers with plain text. Pull out whichever of the
-
 
263
 * two is actually there so the operator sees the real reason.
-
 
264
 */
-
 
265
function uploadErrorMessage(xhr) {
-
 
266
    try {
-
 
267
        var body = JSON.parse(xhr.responseText);
-
 
268
        if (body && body.response && body.response.message) {
-
 
269
            return body.response.message;
-
 
270
        }
-
 
271
    } catch (e) {
-
 
272
        // plain-text body (e.g. "Duplicate request.") - fall through
-
 
273
    }
-
 
274
    return xhr.responseText || xhr.statusText || 'Unknown error';
-
 
275
}
-
 
276
 
-
 
277
// Mirrors Utils.MIME_TYPE / max.allowed.upload.size on the server. Rejecting here
-
 
278
// gives the operator a message naming the file instead of a bare 400.
-
 
279
var UPLOAD_MAX_BYTES = 5000000;
-
 
280
var UPLOAD_ALLOWED_MIME = {
-
 
281
    'image/png': true,
-
 
282
    'image/jpeg': true,
-
 
283
    'image/pjpeg': true,
-
 
284
    'application/pdf': true,
-
 
285
    'application/msword': true,
-
 
286
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': true,
-
 
287
    'application/vnd.ms-excel': true,
-
 
288
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': true
-
 
289
};
-
 
290
var UPLOAD_ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx', 'xls', 'xlsx'];
-
 
291
 
-
 
292
function uploadFileRejectionReason(file) {
-
 
293
    var name = file.name || 'the selected file';
-
 
294
    if (file.size === 0) {
-
 
295
        return '"' + name + '" is empty (0 bytes). Please pick the file again.';
-
 
296
    }
-
 
297
    if (file.size > UPLOAD_MAX_BYTES) {
-
 
298
        return '"' + name + '" is ' + (file.size / 1048576).toFixed(1)
-
 
299
            + ' MB. The limit is 5 MB - please compress it or take a smaller screenshot.';
-
 
300
    }
-
 
301
    if (UPLOAD_ALLOWED_MIME[file.type]) {
-
 
302
        return null;
-
 
303
    }
-
 
304
    // A Blob built in the browser has no name; judge it on its type alone.
-
 
305
    if (!file.name) {
-
 
306
        return 'This file type (' + (file.type || 'unknown') + ') is not supported.';
-
 
307
    }
-
 
308
    var dot = file.name.lastIndexOf('.');
-
 
309
    var ext = dot > -1 ? file.name.substring(dot + 1).toLowerCase() : '';
-
 
310
    if (UPLOAD_ALLOWED_EXTENSIONS.indexOf(ext) > -1) {
-
 
311
        // Browser reported a generic/blank type for a file we do accept; let the
-
 
312
        // server take the final call on it.
-
 
313
        return null;
-
 
314
    }
-
 
315
    return '"' + name + '" is a .' + (ext || 'unknown') + ' file, which is not supported.'
-
 
316
        + ' Please upload it as JPG, PNG or PDF'
-
 
317
        + (ext === 'heic' || ext === 'heif' ? ' (iPhone photos save as .HEIC - share it to yourself as JPEG first).'
-
 
318
            : ext === 'webp' ? ' (images saved from WhatsApp/web are often .webp - re-save it as JPG).'
-
 
319
            : '.');
-
 
320
}
-
 
321
 
-
 
322
/**
-
 
323
 * Uploads a file and hands back its document id.
-
 
324
 *
-
 
325
 * error_callback is optional but callers that write the id into a hidden field MUST
-
 
326
 * pass one: without it a rejected upload used to leave the hidden field empty while
-
 
327
 * the file input still displayed the filename, so the form looked filled and the
-
 
328
 * submit validator reported the field as missing.
-
 
329
 */
-
 
330
function uploadDocument(file, callback, error_callback) {
-
 
331
    function fail(message) {
-
 
332
        if (typeof error_callback === 'function') {
-
 
333
            error_callback(message);
-
 
334
        } else {
-
 
335
            showAlert(message);
-
 
336
        }
-
 
337
    }
-
 
338
 
-
 
339
    if (!file) {
-
 
340
        fail('No file was selected. Please choose the file again.');
-
 
341
        return;
-
 
342
    }
-
 
343
    var rejection = uploadFileRejectionReason(file);
-
 
344
    if (rejection) {
-
 
345
        fail(rejection);
-
 
346
        return;
-
 
347
    }
-
 
348
 
-
 
349
    var url = context + '/document-upload';
-
 
350
    doAjaxUploadRequestHandler(url, 'POST', file, function (response) {
-
 
351
        var documentId = response && response.response ? response.response.document_id : 0;
-
 
352
        if (!documentId || documentId <= 0) {
-
 
353
            fail('The server did not return a document id for "' + (file.name || 'the file')
-
 
354
                + '". Please try again.');
-
 
355
            return;
-
 
356
        }
-
 
357
        callback(documentId);
-
 
358
    }, function (xhr, serverMessage) {
-
 
359
        fail('Could not upload "' + (file.name || 'the file') + '": ' + serverMessage);
-
 
360
    });
-
 
361
}
-
 
362
 
237
function doAjaxUploadRequestJsonHandler(urlString, httpType, file, json, callback_function) {
363
function doAjaxUploadRequestJsonHandler(urlString, httpType, file, json, callback_function) {
238
    var formData = new FormData();
364
    var formData = new FormData();
239
    formData.append("file", file);
365
    formData.append("file", file);
240
    formData.append('json', new Blob([json]));
366
    formData.append('json', new Blob([json]));
241
    $.ajax({
367
    $.ajax({
Line 250... Line 376...
250
            callback_function(response);
376
            callback_function(response);
251
        }
377
        }
252
    });
378
    });
253
}
379
}
254
 
380
 
255
function uploadDocument(file, callback) {
-
 
256
    var url = context + '/document-upload';
-
 
257
    doAjaxUploadRequestHandler(url, 'POST', file, function (response) {
-
 
258
        var documentId = response.response.document_id;
-
 
259
        //console.log("documentId : " + documentId);
-
 
260
        callback(documentId);
-
 
261
    });
-
 
262
}
-
 
263
 
-
 
264
function doAjaxGetDownload(urlString, fileName) {
381
function doAjaxGetDownload(urlString, fileName) {
265
    // console.log("fileName : " + fileName);
382
    // console.log("fileName : " + fileName);
266
    doAjaxDownload(urlString, "GET", null, fileName);
383
    doAjaxDownload(urlString, "GET", null, fileName);
267
}
384
}
268
 
385