Commit 8f457989 by tdgiang

Add SobanleClient getProducts/createSale/changeSaleStatus with 401 retry

parent 0f3325b1
......@@ -37,3 +37,91 @@ exports._resetTokenCacheForTest = function () {
tokenCache.token = null;
tokenCache.expiresAt = 0;
};
function withAuthRetry(makeRequest, callback) {
exports.getToken(function (err, token) {
if (err) {
return callback(err);
}
makeRequest(token, function (err2, body, statusCode) {
if (statusCode === 401) {
tokenCache.token = null;
return exports.getToken(function (loginErr, freshToken) {
if (loginErr) {
return callback(loginErr);
}
makeRequest(freshToken, function (err3, body3) {
if (err3) {
return callback(err3);
}
callback(null, body3);
});
});
}
if (err2) {
return callback(err2);
}
callback(null, body);
});
});
}
function getProducts(callback) {
withAuthRetry(function (token, cb) {
var url = config.sobanle.base_url + "/products?page=1&is_active=true&per_page=1000&";
ApiRequest.getOtherUrlWithHeader(url, {}, { Authorization: "Bearer " + token }, cb);
}, function (err, body) {
if (err) {
return callback(err);
}
if (!body || !Array.isArray(body.data)) {
return callback(new Error("SOBANLE_PRODUCTS_INVALID"));
}
callback(null, body.data);
});
}
exports.getProducts = getProducts;
function createSale(lines, customerData, callback) {
withAuthRetry(function (token, cb) {
var url = config.sobanle.base_url + "/sales";
var payload = {
warehouse_id: config.sobanle.warehouse_id,
biller_id: config.sobanle.biller_id,
account_id: config.sobanle.account_id,
currency_id: config.sobanle.currency_id,
exchange_rate: "1",
reference_no: null,
is_internal_api: true,
sale_status: 2,
list_product: lines.map(function (line) {
return { product_id: String(line.product_id), qty: String(line.qty) };
}),
customer_data: customerData,
payment_receiver: "",
payment_note: "",
sale_note: "Tạo tự động từ payment-gate",
staff_note: "",
};
ApiRequest.postOtherUrlWithHeader(url, payload, { Authorization: "Bearer " + token }, cb);
}, function (err, body) {
if (err) {
return callback(err);
}
if (!body || !body.data || typeof body.data.id === "undefined" || typeof body.data.grand_total === "undefined") {
return callback(new Error("SOBANLE_CREATE_SALE_INVALID"));
}
callback(null, { orderId: body.data.id, orderTotal: body.data.grand_total });
});
}
exports.createSale = createSale;
function changeSaleStatus(orderId, callback) {
withAuthRetry(function (token, cb) {
var url = config.sobanle.base_url + "/sales/change-sale-status/" + orderId;
ApiRequest.patchOtherUrlWithHeader(url, { sale_status: 4 }, { Authorization: "Bearer " + token }, cb);
}, function (err) {
callback(err || null);
});
}
exports.changeSaleStatus = changeSaleStatus;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment