Created
November 25, 2021 11:32
-
-
Save acrolink/b6de93352a0f8c19edfb8148ff2a7184 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var _ = require('lodash'); | |
var Docxtemplater = require('docxtemplater'); | |
var ImageModule = require('docxtemplater-image-module'); | |
var fs = require('fs'); | |
var util = require('util'); | |
var path = require('path'); | |
var async = require('async'); | |
var Unit = require('../unit/unit.model').Unit; | |
var Product = require('./product.model').Product; | |
var Storage = require('../storage/storage.model'); | |
var ProductLifeCycle = require('./product.model').ProductLifeCycle; | |
var ProductName = require('./product.model').ProductName; | |
var KosherType = require('./product.model').KosherType; | |
var LocationHistory = require('./product.model').LocationHistory; | |
var SubMove = require('./product.model').SubMove; | |
var LineSequence = require('../misc/misc.model').LineSequence; | |
var Customer = require('../misc/misc.model').Customer; | |
var Moment = require('moment-timezone'); | |
var mime = require('mime'); | |
var shell = require('shelljs'); | |
var JSZip = require("jszip"); | |
// var pdf = require('html-pdf'); | |
// Waseem, 9.10.2015: Convert String to ObjectId function | |
String.prototype.toObjectId = function () { | |
var ObjectId = (require('mongoose').Types.ObjectId); | |
return new ObjectId(this.toString()); | |
}; | |
// New: Counter table for sequences and shortcodes. | |
var Counter = require('./product.model').Counter; | |
var Barc = require('barc'), barc = new Barc({ | |
fontsize: 36, | |
border: 'auto' | |
}); | |
var dateFormat = require('dateformat'); | |
// Get list of products | |
exports.index = function (req, res) { | |
Product.find({ | |
type: req.params.type | |
}) | |
.populate('unit', 'quantity') | |
.exec(function (err, products) { | |
if (err) { | |
return handleError(res, err); | |
} | |
// return res.json(200, products); | |
return res.status(200).json(products); | |
}); | |
}; | |
exports.productNames = function (req, res) { | |
ProductName.find({}, function (err, names) { | |
if (err) | |
return handleError(res, err); | |
//return res.json(200, names); | |
return res.status(200).json(names); | |
}); | |
} | |
exports.kosherTypes = function (req, res) { | |
KosherType.find({}, function (err, koshers) { | |
if (err) | |
return handleError(res, err); | |
// return res.json(200, koshers); | |
return res.status(200).json(koshers); | |
}); | |
} | |
// Get a single product | |
exports.show = function (req, res) { | |
Product.findById(req.params.id, function (err, product) { | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!product) { | |
return res.send(404); | |
} | |
return res.json(product); | |
}); | |
}; | |
exports.barcodeItem = function (req, res) { | |
return findAndPopulate(req, res); | |
} | |
exports.barcodeView = function (req, res) { | |
ProductLifeCycle.findOne({ | |
_id: req.params.id | |
}, function (err, plc) { | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!plc) { | |
return res.send(404); | |
} | |
res.writeHead(200, { | |
'Content-Type': 'image/png' | |
}); | |
// Higher resolution for better image. | |
var buf = barc.code2of5(plc._id, 720, 450); | |
return res.end(buf, 'binary'); | |
}); | |
} | |
function generateUniqueId(seed) { | |
// return (seed).toString().substring(3); | |
return (seed).toString().substring(1); | |
} | |
function calcTime(offset) { | |
// create Date object for current location | |
var d = new Date(); | |
// convert to msec | |
// add local time zone offset | |
// get UTC time in msec | |
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); | |
// create new Date object for different city | |
// using supplied offset | |
var nd = new Date(utc + (3600000 * offset)); | |
// return time as a string | |
return nd; | |
} | |
// Creates a new product in the DB. | |
exports.barcode = function (req, res) { | |
console.log("d") | |
Product | |
.findById(req.body.productId) | |
.populate("unit") | |
.exec(function (err, p) { | |
if (err) { | |
return handleError(res, err); | |
} | |
var barcodes = []; | |
var start = new Date().getTime(); | |
var temp_seq = 1; | |
for (var i = 0; i < req.body.quantity; i++) { | |
var item_quantity; | |
// Make it possible to specify less than complete quantity at production hall. | |
if (req.body.currentQuantity) { | |
item_quantity = req.body.currentQuantity; | |
} else { | |
item_quantity = p.unit.quantity; | |
} | |
var storage_object = null; | |
// var actual_quantity_object = null; | |
var production_time_object = req.body.production_time; | |
var production_sequence_object = req.body.production_sequence; | |
if (req.body.BatchLocateAt) { | |
storage_object = {}; | |
storage_object.location = req.body.BatchLocateAt.toObjectId(); | |
storage_object.direction = "RECEIPTED"; | |
storage_object.updateDate = new Date; | |
storage_object._id = 0; | |
// actual_quantity_object = item_quantity; | |
production_time_object = "12:00:00"; | |
production_sequence_object = temp_seq; | |
storage_object.by = 0; | |
} | |
temp_seq += 1; | |
barcodes.push({ | |
_id: generateUniqueId(start + i), | |
product: req.body.productId, | |
created: req.body.createDate, | |
quantity: item_quantity, | |
production_time: production_time_object, | |
production_sequence: production_sequence_object, | |
storage: storage_object, | |
// actual_quantity : actual_quantity_object, | |
real: 5 // 4 set from 23.04.2016 when omar began scanning | |
// 5 on 28.07.17 | |
// real : 2 // set from 07.04.2016 | |
// real : 3 // set from 27.03.2017 | |
}); | |
} | |
var calls = []; | |
var barcodes_count = barcodes.length; | |
barcodes.forEach(function (item, index) { | |
calls.push(function (callback) { | |
ProductLifeCycle.create(item, function (err, plc) { | |
if (err) { | |
return callback(err); | |
} | |
// Improved resolution for Barcode images. | |
var buf = barc.code2of5((plc._id).toString(), 720, 450); | |
var barcodePath = 'docx/plc' + plc._id + '.png'; | |
// Add Page Break except for the last barcode in batch mode. | |
var page_break; | |
if (index == (barcodes_count - 1)) { | |
page_break = ''; | |
} else { | |
page_break = '<w:br w:type="page" />'; | |
} | |
// Add quantity to printed Barcode. | |
var item_quantity_token = plc.quantity; | |
fs.writeFile(barcodePath, buf, function (err) { | |
if (err) | |
return callback(err); | |
callback(null, { | |
title: p.name, | |
barcode: plc._id, | |
p_date: dateFormat(plc.created, 'dd/mm/yyyy'), | |
barcode_image: barcodePath, | |
break_break: page_break, | |
pq: item_quantity_token, | |
seq: plc.production_sequence, | |
time: plc.production_time, | |
product_id: p._id, | |
}) | |
}); | |
}); | |
}); | |
}); | |
async.series(calls, function (err, result) { | |
if (err) | |
return handleError(res, err); | |
var buff = generateFromTempate({ | |
barcodes: result | |
}); | |
// Barcode / name is UNIX time in milliseconds except for the first digit to the left. | |
var filename = 'docx/barcode' + start.toString().substring(1) + '.docx'; | |
// | |
fs.writeFileSync(filename, buff, { | |
encoding: 'base64' | |
}); | |
result.forEach(function (b) { | |
fs.unlink(b.barcode_image, function (err) { | |
if (err) | |
return handleError(res, err); | |
}); | |
}); | |
//return res.json(200, {downloadUrl: filename}); | |
return res.json(200, { | |
//downloadUrl : "/api/products/download/" + start.toString().substring(1), | |
downloadUrl: "/docx/barcode" + start.toString().substring(1) + '.docx', | |
result_barcode_id: start.toString().substring(1), | |
currentSequence: result[0].seq | |
}); | |
}); | |
}); | |
} | |
var generateFromTempate = function (barcodeData) { | |
var content = fs.readFileSync("docx/template/input.docx", "binary"); | |
var opts = {} | |
opts.centered = false; | |
opts.getImage = function (tagValue, tagName) { | |
return fs.readFileSync(tagValue); | |
} | |
opts.getSize = function (img, tagValue, tagName) { | |
return [190, 150]; | |
} | |
var imageModule = new ImageModule(opts); | |
var zip = new JSZip(content); | |
var docx = new Docxtemplater() | |
.attachModule(imageModule) | |
.loadZip(zip) | |
.setData(barcodeData) | |
.render(); | |
var time_now = new Date().toLocaleString(); | |
console.log(time_now); | |
var buffer = docx | |
.getZip() | |
.generate({ | |
type: "nodebuffer" | |
}); | |
return buffer; | |
} | |
exports.download = function (req, res) { | |
var filename = 'barcode' + req.params.id + '.docx'; | |
var file = '/srv/www/eden_warehouse/docx/' + filename; | |
var mimetype = mime.lookup(file); | |
res.setHeader('Content-disposition', 'attachment; filename=' + filename); | |
res.setHeader('Content-type', mimetype); | |
res.setHeader('Transfer-Encoding', 'chunked'); | |
var filestream = fs.createReadStream(file); | |
filestream.pipe(res); | |
} | |
exports.create = function (req, res) { | |
console.log('Barcode creation called..'); | |
// First retieve shortcode value for new product from Counter table. | |
retrieveSeq(req.body.type, function (err, item) { | |
if (err) { | |
console.log(err); | |
} | |
req.body._id = item.seq; | |
Product.create(req.body, function (err, product) { | |
if (err) { | |
return handleError(res, err); | |
} | |
return res.json(201, product); | |
}); | |
}); | |
}; | |
// Updates an existing product in the DB. | |
exports.update = function (req, res) { | |
if (req.body._id) { | |
delete req.body._id; | |
} | |
Product.findById(req.params.id, function (err, product) { | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!product) { | |
return res.send(404); | |
} | |
var updated = _.merge(product, req.body); | |
updated.save(function (err) { | |
if (err) { | |
return handleError(res, err); | |
} | |
return res.json(200, product); | |
}); | |
}); | |
}; | |
exports.recept = function (req, res) { | |
console.log(req.body); | |
ProductLifeCycle.findOne({ | |
_id: req.params.id | |
}) | |
.exec(function (err, plc) { | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!plc) { | |
var result = { | |
product_name: "?", | |
message: "لم يتم ايجاد هذا المنتج", | |
max: 0 | |
} | |
return res.json(404, result); | |
} | |
return handleProductLifeCycleSaving(req, res, plc, 'RECEIPTED'); | |
}); | |
} | |
exports.remove = function (req, res) { | |
// force complete package out.. | |
req.body.quantity = 0; | |
console.log(req.body); | |
var result; | |
ProductLifeCycle.findOne({ | |
_id: req.params.id | |
}) | |
.exec(function (err, plc) { | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!plc) { | |
result = { | |
product_name: "?", | |
message: "لم يتم ايجاد هذا المنتج", | |
max: 192 | |
} | |
return res.json(404, result); | |
} | |
if (!plc.storage) { | |
result = { | |
product_name: "?", | |
message: "لم يتم تسجيل هذا المنتج الى مخزن معين سابقاً", | |
max: 192 | |
} | |
return res.json(400, result); | |
} | |
return handleProductLifeCycleSaving(req, res, plc, 'REMOVED'); | |
}); | |
} | |
// Deletes a product from the DB. | |
exports.destroy = function (req, res) { | |
Product.findById(req.params.id, function (err, product) { | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!product) { | |
return res.send(404); | |
} | |
product.remove(function (err) { | |
if (err) { | |
return handleError(res, err); | |
} | |
return res.send(204); | |
}); | |
}); | |
}; | |
function defaultReportCriteria(req) { | |
var rules = []; | |
var produce_date = {}; | |
var date = {}; | |
if (req.body.adjusted) { | |
rules.push({ | |
"storage.updateDate": { | |
$lte: new Date(req.body.adjusted) | |
} | |
}); | |
} | |
var date_counter = 0; | |
if (req.body.adjustedFrom) { | |
date.$gte = new Date(req.body.adjustedFrom); | |
date_counter++; | |
} | |
if (req.body.adjustedTo) { | |
date.$lt = new Date(req.body.adjustedTo); | |
date_counter++; | |
} | |
if (date_counter > 0) { | |
var or = []; | |
or.push((req.body.direction) ? { | |
"storage.updateDate": date, | |
"storage.direction": req.body.direction | |
} | |
: { | |
"storage.updateDate": date | |
}); | |
/* | |
or.push((req.body.direction) ? { | |
"history.updateDate" : date, | |
"history.direction" : req.body.direction | |
} | |
: { | |
"history.updateDate" : date | |
}); | |
*/ | |
/* | |
or.push((req.body.direction) ? { | |
"submove.updateDate": date, | |
"submove.direction": req.body.direction | |
} | |
: { | |
"submove.updateDate": date | |
}); | |
*/ | |
rules.push({ | |
"$or": or | |
}); | |
} else if (req.body.direction) { | |
rules.push({ | |
"$or": [{ | |
"storage.direction": req.body.direction | |
}, { | |
"history.direction": req.body.direction | |
} | |
] | |
}); | |
} | |
var produce_date_counter = 0; | |
if (req.body.from) { | |
produce_date.$gte = new Date(req.body.from); | |
produce_date_counter++; | |
} | |
if (req.body.to) { | |
produce_date.$lt = new Date(req.body.to); | |
produce_date_counter++; | |
} | |
if (produce_date_counter > 0) { | |
rules.push({ | |
created: produce_date | |
}); | |
} | |
// Waseem, 9.10.2015: Filter by Storage if selected by end user. | |
if ((typeof req.body.storage !== "undefined") && (!!req.body.storage)) { | |
rules.push({ | |
"storage.location" : { | |
$eq : (req.body.storage._id).toObjectId() | |
} | |
/* | |
"$or": [{ | |
"storage.location": { | |
$eq: (req.body.storage._id).toObjectId() | |
} | |
}, { | |
"submove.location": { | |
$eq: (req.body.storage._id).toObjectId() | |
} | |
} | |
] | |
*/ | |
}); | |
} | |
rules.push({ | |
"discard": { | |
$ne: 1 | |
} | |
}); | |
rules.push({ | |
"real": { | |
$in: [5]// Don't forget to restrict later to $eq : 3 only | |
} | |
}); | |
rules.push({ | |
"assumed_out": { | |
$in: [0]// Don't forget to restrict later to $eq : 3 only | |
} | |
}); | |
// Waseem, 19.12.2015: Exclude items that have submoves. | |
/* | |
rules.push({ | |
"submove.0" : { | |
$exists : false | |
} | |
}); | |
*/ | |
return rules; | |
} | |
exports.wrapReport = function (req, res) { | |
var productMap = {}; | |
var storageMap = {}; | |
Product.find({}) | |
.exec(function (err, product) { | |
if (err) | |
return handleError(res, err); | |
_.forEach(product, function (item) { | |
productMap[item._id] = { | |
_id: item._id, | |
name: item.name, | |
pn: item.productName, | |
kn: item.kosher | |
}; | |
}); | |
Storage.find({}) | |
.exec(function (err, storage) { | |
if (err) | |
return handleError(res, err); | |
_.forEach(storage, function (s) { | |
storageMap[s._id] = s.name; | |
}); | |
var rules = defaultReportCriteria(req); | |
var aggr = []; | |
if (rules.length > 0) { | |
aggr.push({ | |
$match: { | |
$and: rules | |
} | |
}); | |
} | |
aggr.push({ | |
$project: { | |
_id: 0, // let's remove bson id's from request's result | |
product: 1, // we need this field | |
storage: '$storage.location', // and let's turn the nested field into usual field (usual renaming), | |
submove: 1, | |
whole_quantity: 1, | |
quantity: 1, | |
counting: { | |
$cond: { | |
if : { | |
$eq: ["$regard_as_whole", 1] | |
}, | |
then: 1, | |
else : 0 | |
} | |
}, | |
submoves: { | |
$cond: { | |
if : { | |
$eq: ["$regard_as_whole", 1] | |
}, | |
then: [0], | |
else : "$submove" | |
} | |
}, | |
elin: { | |
$cond: { | |
if : { | |
$and: [{ | |
$eq: ["$regard_as_whole", 1] | |
}, { | |
$eq: ["$whole_quantity", 0] | |
} | |
] | |
}, | |
then: 1, | |
else : 0 | |
} | |
}, | |
elin_sum: { | |
$cond: { | |
if : { | |
$and: [{ | |
$eq: ["$regard_as_whole", 1] | |
}, { | |
$eq: ["$whole_quantity", 0] | |
}, { | |
$eq: ["$storage.location", ("55928bb76237dbec0787d7f3").toObjectId()] | |
} | |
] | |
}, | |
then: '$quantity', | |
else : 0 | |
} | |
}, | |
originals: { | |
$cond: { | |
if : { | |
$eq: ["$regard_as_whole", 0] | |
}, | |
then: '$quantity', | |
else : 0 | |
} | |
}, | |
not_whole: { | |
$cond: { | |
if : { | |
$eq: ["$whole_quantity", 1] | |
}, | |
then: [0], | |
else : '$quantity' | |
} | |
}, | |
whole_count: { | |
$cond: { | |
if : { | |
$eq: ["$whole_quantity", 1] | |
}, | |
then: 1, | |
else : 0 | |
} | |
} | |
// submoves: { $cond: { if: { $eq: [ "$regard_as_whole", 1 ] }, then: [0], else: {$cond: { if : { $eq: ["$regard_as_whole", 0 ]}, then: "$submove.items", else: [0]} } } } | |
} | |
}); | |
aggr.push( | |
// { $unwind : '$submove' }, | |
{ | |
$group: { | |
_id: { | |
product: '$product', | |
storage: '$storage' | |
}, // grouping key - group by field district | |
total: { | |
$sum: '$counting' | |
}, | |
whole_count: { | |
$sum: '$whole_count' | |
}, | |
elin_sum: { | |
$sum: '$elin_sum' | |
}, | |
originals: { | |
$sum: '$originals' | |
}, | |
elin: { | |
$sum: '$elin' | |
}, // we need some stats for each group (for each district) | |
"items_values": { | |
"$addToSet": "$submoves" | |
}, | |
"not_whole_values": { | |
"$addToSet": "$not_whole" | |
}, | |
} | |
}); | |
ProductLifeCycle.aggregate(aggr, function (err, result) { | |
if (err) | |
return handleError(res, err); | |
var mino = 0; | |
var maxo = 9999999999999; | |
var reportResult = []; | |
try { | |
mino = Date.parse(aggr[0]['$match']['$and'][0]['$or'][0]['storage.updateDate']['$gte']); | |
maxo = Date.parse(aggr[0]['$match']['$and'][0]['$or'][0]['storage.updateDate']['$lt']); | |
} catch (e) { | |
// console.log("YO",e) | |
} | |
//console.log(mino); | |
//console.log(maxo); | |
_.forEach(result, function (f) { | |
console.log(f); | |
var kosher = true, | |
product = true; | |
if (req.body.kosher) { | |
var kn = productMap[f._id.product].kn; | |
kosher = (kn === req.body.kosher._id); | |
} | |
if (req.body.product) { | |
var pn = productMap[f._id.product].pn; | |
product = (pn === req.body.product._id); | |
} | |
if (kosher && product) { | |
f._id.product_id = productMap[f._id.product]._id; | |
f._id.product = productMap[f._id.product].name; | |
f._id.storage = storageMap[f._id.storage]; | |
var sum = 0; | |
f.items_values.forEach(function (i) { | |
i.forEach(function (entry) { | |
// console.log(entry.items); | |
var e = Date.parse(entry.updateDate); | |
// console.log(mino + "\n" + maxo + "\n" + e); | |
if (e > mino && e < maxo) { | |
sum += parseInt(entry.items); | |
// console.log('xexeo: ' + entry['items']); | |
} | |
}); | |
}); | |
/* | |
f.items_values.forEach(function(item) { | |
item.reduce( | |
function(prev,current){ | |
sum += current; | |
}, 0 | |
); | |
}); | |
*/ | |
var not_whole_values_sum = 0; | |
f.not_whole_values.forEach(function (entry) { | |
not_whole_values_sum += parseInt(entry); | |
}); | |
/* | |
f.not_whole_values.forEach(function(i) { | |
i.reduce( | |
function(prev,current){ | |
not_whole_values_sum += current; | |
}, 0 | |
); | |
}); | |
*/ | |
// require('os').EOL | |
//console.log(not_whole_values_sum); | |
var number_of_submoves = Object.keys(f.items_values).length; | |
// f.total = (f.total - f.elin) + " (" + (sum + f.elin_sum) + "/" + (f.originals - sum) + ") " + " {" + (f.whole_count) + "} " + " [" + not_whole_values_sum + "]"; | |
var extra = "<span class='sp'></span>( " + (f.originals - sum) + " / " + "<span class='items-out'>" + (sum + f.elin_sum) + "</span>" + " )"; | |
//var extra = "<span class='sp'></span>( " + (sum + f.elin_sum) + " / " + "<span class='items-out'>" + (f.originals - sum) + "</span>" + " )"; | |
if (extra == "<span class='sp'></span>( 0 / <span class='items-out'>0</span> )") { | |
extra = ""; | |
} | |
// CHECKO !!! 23.04.2018 | |
//f.total = (f.total - f.elin) + extra; | |
reportResult.push(f); | |
} | |
}); | |
return res.json(reportResult); | |
}); | |
}); | |
}); | |
} | |
Array.prototype.sortOn = function (key) { | |
this.sort(function (a, b) { | |
if (a[key] < b[key]) { | |
return -1; | |
} else if (a[key] > b[key]) { | |
return 1; | |
} | |
return 0; | |
}); | |
} | |
function handleProductLifeCycleSaving(req, res, plc, direction) { | |
var result = []; | |
var newLocation_location = 0; | |
var toClient; | |
var contains_previous_submoves = false; | |
var actual_quantity; | |
var items_to_be_inserted; | |
var By = 0; | |
if (req.body.by) { | |
By = req.body.by | |
} | |
if (plc.submove.length > 0) { | |
// console.log("Contains SUBMOVES"); | |
contains_previous_submoves = true; | |
} | |
var sum_of_submoves = 0; | |
if (contains_previous_submoves == true) { | |
plc.submove.forEach(function (entry) { | |
sum_of_submoves = sum_of_submoves + entry.items; | |
}); | |
actual_quantity = plc.quantity - sum_of_submoves; | |
} else { | |
actual_quantity = plc.quantity; | |
} | |
var to_where = ''; | |
switch (req.body.location) { | |
case '55928bb76237dbec0787d7f3': | |
to_where = 'customer'; | |
break; | |
case '55928b9e6237dbec0787d7ee': | |
to_where = 'store'; | |
break; | |
case '55928ba36237dbec0787d7ef': | |
to_where = 'store'; | |
break; | |
// 3 | |
case '55928ba86237dbec0787d7f0': | |
to_where = 'store'; | |
break; | |
case '55928bad6237dbec0787d7f1': | |
to_where = 'store'; | |
break; | |
case '55f53f0938a047e011888c86': | |
to_where = 'production'; | |
break; | |
// update this accordingly | |
case '56669bbef3515c4f4e8c0061': | |
plc.assumed_out = 0; | |
to_where = 'return'; | |
break; | |
default: | |
} | |
if ((to_where == 'customer') && req.body.location != plc.storage.location) { | |
if (req.body.quantity > actual_quantity) { | |
return ReturnCustomError(req, res, 'الكمية المختارة أكبر مما يتواجد في القالب', actual_quantity); | |
} else { | |
if ((req.body.quantity == 0 && (!contains_previous_submoves)) || (req.body.quantity == actual_quantity && (!contains_previous_submoves))) { | |
newLocation_location = req.body.location; | |
toClient = req.body.client; | |
} else if (req.body.quantity == 0 && (contains_previous_submoves == true) && (actual_quantity != 0)) { | |
items_to_be_inserted = (plc.quantity - sum_of_submoves); | |
var newSubMove = new SubMove({ | |
_id: plc.submove.length, | |
location: req.body.location, // newLocation_location | |
client: req.body.client, | |
direction: direction, | |
by: By, | |
items: items_to_be_inserted | |
}); | |
plc.submove.push(newSubMove); | |
newLocation_location = req.body.location; | |
plc.regard_as_whole = 0; | |
} else if (actual_quantity == 0) { | |
return res.json(403, "قالب فارغ"); | |
} else if (req.body.quantity != 0) { | |
var to_be_id; | |
if (!contains_previous_submoves) { | |
to_be_id = 0; | |
} else { | |
to_be_id = plc.submove.length | |
} | |
var newSubMove = new SubMove({ | |
_id: to_be_id, | |
location: req.body.location, // newLocation_location | |
client: req.body.client, | |
direction: direction, | |
by: By, | |
items: req.body.quantity | |
}); | |
plc.submove.push(newSubMove); | |
if (req.body.quantity == actual_quantity) { | |
newLocation_location = req.body.location; | |
plc.regard_as_whole = 0; | |
} else { | |
newLocation_location = plc.storage.location; | |
plc.regard_as_whole = 0; | |
} | |
} | |
} | |
} else if ((to_where == 'customer') && req.body.location == plc.storage.location) { | |
return ReturnCustomError(req, res, "لا يمكن تصدير منتج تم تصديره مسبقاً", 192); | |
} | |
if (to_where == 'store') { | |
if (plc.storage && plc.storage.location == '55928bb76237dbec0787d7f3') { | |
return ReturnCustomError(req, res, 'لا يمكن استيعاب منتج تم تصديره مسبقاً الى زبون', 192); | |
} | |
/* DISABLED for easier use of store workers. | |
02.01.2016 | |
if ((plc.storage && plc.storage.direction === direction) && (plc.storage.location != '55f53f0938a047e011888c86')) { | |
return ReturnCustomError(req, res, 'تم الاستيعاب مسبقاً', 192); | |
} | |
*/ | |
newLocation_location = req.body.location; | |
} | |
if (to_where == 'production') { | |
newLocation_location = req.body.location; | |
} | |
if (to_where == 'return') { | |
// return ReturnCustomError(req, res, 'هذا الزر معطل .. لتسجيل النقل لمخزن آخر عليك تحديد المخزن الهدف ومن ثم قراءة الباركود', 192); | |
if (plc.storage && plc.storage.location == '55928bb76237dbec0787d7f3') { | |
newLocation_location = req.body.location; | |
} else if (plc.storage && plc.storage.location == '56669bbef3515c4f4e8c0061') { | |
return ReturnCustomError(req, res, 'تم تسجيل الإعادة مسبقاً .. عليك ادخال المنتج الى مخزن محدد', 192); | |
} else { | |
return ReturnCustomError(req, res, 'لم يصدر هذا المنتج لزبون مسبقاً', 192); | |
} | |
/* DISABLED in the meanwhile due to easier use by storage workers. | |
02.01.2016 | |
if (plc.storage && plc.storage.location == '55928bb76237dbec0787d7f3') { | |
return ReturnCustomError(req, res, 'لا يمكن نقل منتج تم تصديره مسبقاً', 192); | |
} | |
newLocation_location = req.body.location; | |
*/ | |
} | |
if (!plc.history.length) { | |
plc.history = []; | |
} | |
var newLocation = new LocationHistory({ | |
location: newLocation_location, // newLocation_location | |
client: toClient, | |
by: By, | |
direction: direction | |
}); | |
if (req.body.defects) | |
plc.defects = req.body.defects; | |
if (plc.storage) { | |
plc.history.push(plc.storage); | |
} | |
newLocation._id = plc.history.length; | |
if (req.body.time) { | |
newLocation.updateDate = new Date(req.body.time * 1000); | |
} | |
plc.storage = newLocation; | |
plc.save(function (err) { | |
if (err) { | |
return handleError(res, err); | |
} | |
return findAndPopulate(req, res) | |
}); | |
} | |
function findAndPopulate(req, res) { | |
ProductLifeCycle | |
.findOne({ | |
_id: req.params.id | |
}) | |
//.populate("product") | |
//.populate("product.unit") | |
.exec(function (err, plc) { | |
console.log('Barcode: ' + plc._id.toString()); | |
console.log('Created: ' + plc.created.toString()); | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!plc) { | |
return res.send(404); | |
} | |
Product | |
.findOne({ | |
_id: plc.product | |
}) | |
.populate("unit") | |
.exec(function (err, p) { | |
if (err) { | |
return handleError(res, err); | |
} | |
var result = { | |
product_name: p.name, | |
message: "تم التسجيل بنجاح", | |
max: 192 | |
} | |
if ((req.body.location == '55928bb76237dbec0787d7f3') && plc.assumed_out == 1) { | |
console.log('assumed_out is 1, correct another'); | |
ProductLifeCycle | |
.findOne({ | |
product: plc.product, | |
assumed_out: 0, | |
'storage.location': ("55928b9e6237dbec0787d7ee").toObjectId() | |
}) | |
//.populate("product") | |
//.populate("product.unit") | |
.exec(function (err, plc_to_adjust) { | |
if (plc_to_adjust) { | |
plc_to_adjust.assumed_out = 1; | |
plc_to_adjust.save(function (err) {}); | |
/* | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!plc) { | |
return res.send(404); | |
} | |
*/ | |
console.log(plc_to_adjust); | |
} | |
//return res.json(200, "ok"); | |
}); | |
return res.json(200, result); | |
} else { | |
return res.json(200, result); | |
} | |
}); | |
}); | |
} | |
function ReturnCustomError(req, res, text, quantity) { | |
ProductLifeCycle | |
.findOne({ | |
_id: req.params.id | |
}) | |
//.populate("product") | |
.exec(function (err, plc) { | |
if (err) { | |
return handleError(res, err); | |
} | |
if (!plc) { | |
return res.send(404); | |
} | |
Product | |
.findOne({ | |
_id: plc.product | |
}) | |
.exec(function (err, p) { | |
if (err) { | |
return handleError(res, err); | |
} | |
plc.product = p; | |
var result = { | |
product_name: p.name, | |
message: text, | |
max: quantity | |
} | |
return res.json(403, result); | |
}); | |
}); | |
} | |
function handleError(res, err) { | |
console.log(err); | |
return res.send(500, err); | |
} | |
// Retrieve sequence to be used when adding a new product. | |
function retrieveSeq(type, callback) { | |
Counter.findByIdAndUpdate({ | |
_id: type | |
}, { | |
$inc: { | |
seq: 1 | |
} | |
}, function (err, item) { | |
if (err) { | |
callback(err, null); | |
} else { | |
callback(null, item); | |
} | |
}); | |
}; | |
exports.clients = function (req, res) { | |
var customerMap = {}; | |
var productMap = {}; | |
var storageMap = {}; | |
var date = {}; | |
var date_counter = 0; | |
if (req.body.adjustedFrom) { | |
console.log(req.body.adjustedFrom); | |
date.$gte = new Date(req.body.adjustedFrom); | |
date_counter++; | |
} | |
if (req.body.adjustedTo) { | |
date.$lt = new Date(req.body.adjustedTo); | |
date_counter++; | |
} | |
Customer.find({}) | |
.exec(function (err, customer) { | |
if (err) | |
return handleError(res, err); | |
_.forEach(customer, function (c) { | |
customerMap[c._id] = { | |
name: c.name | |
}; | |
}); | |
Product.find({}) | |
.exec(function (err, product) { | |
if (err) | |
return handleError(res, err); | |
_.forEach(product, function (item) { | |
productMap[item._id] = { | |
name: item.name, | |
pn: item.productName, | |
kn: item.kosher | |
}; | |
}); | |
Storage.find({}) | |
.exec(function (err, storage) { | |
if (err) | |
return handleError(res, err); | |
_.forEach(storage, function (s) { | |
storageMap[s._id] = s.name; | |
}); | |
ProductLifeCycle.aggregate( | |
[{ | |
$match: { | |
$or: [{ | |
$and: [{ | |
"regard_as_whole": 0 | |
}, { | |
"submove.updateDate": date | |
}, { | |
"submove.location": ("55928bb76237dbec0787d7f3").toObjectId() | |
} | |
/*, { | |
"real" : 2 // set from 07.04.2016 | |
}*/ | |
] | |
}, { | |
$and: [{ | |
"regard_as_whole": 1 | |
}, { | |
"storage.updateDate": date | |
}, { | |
"storage.location": ("55928bb76237dbec0787d7f3").toObjectId() | |
} | |
/*, { | |
"real" : 2 // set from 07.04.2016 | |
}*/ | |
] | |
} | |
] | |
} | |
}, { | |
$project: { | |
product: 1, | |
submove: { | |
$cond: { | |
if : { | |
$and: [{ | |
$eq: ["$regard_as_whole", 1] | |
}, { | |
$eq: ["$storage.location", ("55928bb76237dbec0787d7f3").toObjectId()] | |
}, | |
] | |
}, | |
then: { | |
client: "$storage.client", | |
items: "$quantity", | |
updateDate: "$storage.updateDate", | |
by: "$storage.by" | |
}, | |
else : '$submove' | |
} | |
} | |
} | |
}, { | |
"$unwind": "$submove" | |
}, { | |
$match: { | |
"submove.updateDate": date | |
} | |
}, { | |
"$group": { | |
"_id": { | |
"client": "$submove.client", | |
"product": "$product", | |
"by": "$submove.by" | |
}, | |
total: { | |
$sum: "$submove.items" | |
} | |
} | |
}, { | |
"$group": { | |
"_id": "$_id.client", | |
"terms": { | |
$push: { | |
term: "$_id.product", | |
by: "$_id.by", | |
total: "$total" | |
} | |
} | |
} | |
} | |
], function (err, result) { | |
var reportResult = []; | |
var i = 0; | |
_.forEach(result, function (f) { | |
var client_item = {}; | |
var m = []; | |
_.forEach(f, function (e) { | |
_.forEach(e, function (r) { | |
r.term = productMap[r.term].name; | |
m.push({ | |
"product": r.term, | |
"total": r.total, | |
"by": r.by | |
}); | |
}); | |
}); | |
try { | |
f._id = customerMap[f._id].name; | |
} catch (e) { | |
console.log(f._id); | |
if (f._id == null) { | |
f._id = "לא מזוהה"; | |
} | |
} | |
/* | |
client_item.push({ | |
"client" : f._id, | |
"movements" : m | |
}); | |
*/ | |
client_item.client = f._id; | |
client_item.movements = m; | |
reportResult[i] = client_item; | |
i += 1; | |
}); | |
return res.json(reportResult); | |
}) | |
}); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment