-
Notifications
You must be signed in to change notification settings - Fork 1
/
orders.js
482 lines (402 loc) · 15.6 KB
/
orders.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// we use that function to don't dopilcate orders in cart screen
function removeDuplicates( arr, prop ) {
var obj = {};
for ( var i = 0, len = arr.length; i < len; i++ ){
if(!obj[arr[i][prop]]) obj[arr[i][prop]] = arr[i];
}
var newArr = [];
for ( var key in obj ) newArr.push(obj[key]);
return newArr;
}
var count = (ids,id)=>{
var num = 0;
for(let i in ids){
if(ids[i] == id){
num++
}
if(i == ids.length-1){
return num;
}
}
}
//search for id inside library logic function
var search = (ids,id) =>{
var result = false;
if(ids.length != 0 ){
for(let g in ids){
if(ids[g].key == id){
result = true;
}
if(i == ids.length-1){
return result;
}
}
}
else{
return result;
}
}
app.get('/api/make-special-order',function(req,res){
var user_id = req.param("user_id");
var cost = req.param("cost");
var note = req.param("note");
var restaurant = req.param("restaurant");
var info = restaurant+' - '+req.param("info");
var address = req.param("address");
con.query('INSERT INTO orders(store_id,user_id,cost,info,location,delivery_cost,time_ordered,note) VALUES(-1,?,?,?,?,0, NOW(),?)', [user_id,cost,info,address,note],
function(err,orders) {
if(!err){
res.json({response:1})
}
else {
res.json({response:err})
}
});
})
app.get('/api/special_orders_status',function(req,res){
sql.qry("select * from meta_data where name = 'special_orders_status'",function(status,err){
res.json({status:status[0].value});
})
})
app.get('/api/image',function(req,res){
sql.qry("select * from meta_data where name = 'background'",function(status,err){
res.json({background:status[0].value});
})
})
app.get('/api/make-order',function(req,res){
var store_id = req.param("store_id");
var user_id = req.param("user_id");
var cost = req.param("cost");
var note = req.param("note");
var info = req.param("info");
var ids = req.param("ids");
var discounted = req.param('discounted')
var pure_ids = ids;
var ids = ids.split(",");
var address = req.param("address");
var address_hint = req.param("address_hint");
var full_location = (!address_hint) ? (address) : (address + " - " + address_hint);
var stored_ids = [];
con.query('SELECT delivery_cost FROM stores WHERE id=? LIMIT 1', [store_id], function(err,storeDeliveryCost) {
if(!err) {
var dCost = storeDeliveryCost[0].delivery_cost;
var meals = [];
for(let i in ids){
if(ids[i] != null || ids[i] != 'null'){
if(search(meals,ids[i]) == false){
con.query('SELECT id AS `key`, name, img AS image, cost AS price, info AS `desc` '+
'FROM products WHERE id=? LIMIT 1', [ids[i]], function(err,data) {
if(!err) {
var data = data[0];
console.log(data)
if(data != null){
meals.push({
key:data.key,
name: data.name,
desc:data.desc,
count:count(ids,ids[i])
})
stored_ids.push(ids[i]);
}
}
else {
res.json({ response:"here", err });
}
if(i == ids.length-1){
//you data coud be here ----------------->
meals = removeDuplicates(meals,'key');
for(let k in meals){
if(info){
var info = info + '-'+' عدد'+meals[k].count+''+ ' '+meals[k].name;
}
else{
var info = '-'+' عدد'+meals[k].count+''+ ' '+meals[k].name;
}
if(k == meals.length-1){
//here it goes to play ---------->
con.query('INSERT INTO orders(store_id,user_id,cost,info,location,delivery_cost,time_ordered,note,ids,cost_dicounted) VALUES(?,?,?,?,?,?,NOW(),?,?,?)',
[store_id,user_id,cost,info,full_location,dCost,note,pure_ids,discounted],
function(err,orders) {
if(err) return res.json({response: err});
//add products ---->
//end add products
con.query('SELECT token FROM expo_push_tokens WHERE store_id=? LIMIT 100',
[store_id], function(err,tokens) {
for(let i in tokens){
push(tokens[i].token,'هناك طلب جديد على متجرك، تفحص صفحة طلبات المتجر')
}
// if(tokens.length)
// {
// var pushTokensArr = [];
// tokens.forEach(function(tok) {
// pushTokensArr.push(tok.token);
// });
// SendPushNotifications(pushTokensArr);
// }
});
res.json({ response: 1 });
});
//end of game
}
}
}
});
}
else{
if(i == ids.length-1){
//you data coud be here ----------------->
meals = removeDuplicates(meals,'key');
for(let k in meals){
if(info){
var info = info + '-'+' عدد'+meals[k].count+' وجبه'+ ' '+meals[k].name;
}
else{
var info = '-'+' عدد'+meals[k].count+' وجبه'+ ' '+meals[k].name;
}
if(k == meals.length-1){
//here it goes to play ---------->
con.query('INSERT INTO orders(store_id,user_id,cost,info,location,delivery_cost,time_ordered) VALUES(?,?,?,?,?,?, NOW())',
[store_id,user_id,cost,info,full_location,dCost],
function(err,orders) {
if(err) return res.json({response: err});
//add products ---->
//end add products
con.query('SELECT token FROM expo_push_tokens WHERE store_id=? LIMIT 100',
[store_id], function(err,tokens) {
if(tokens.length)
{
var pushTokensArr = [];
tokens.forEach(function(tok) {
pushTokensArr.push(tok.token);
});
SendPushNotifications(pushTokensArr);
}
});
res.json({ response: 1 });
});
//end of game
}
}
}
}
}
}
}
else res.json({ response:0, err });
})
app.get('/api/order-time',function(req,res){
var order_id = req.param("id");
var dateFormat = require('dateformat');
var now = new Date();
var timediff = require('timediff');
var time_now = dateFormat(now, "isoDateTime");
con.query('SELECT store_id,time_accepted '+
'FROM orders WHERE id=? LIMIT 1', [order_id], function(err,order) {
var time_passed = timediff(order[0]['time_accepted'], time_now, 'YDHms');
con.query('SELECT delivery_time '+
'FROM stores WHERE id=? LIMIT 1', [order[0]['store_id']], function(err,restaurant) {
deliver_time =
time_left = Number(restaurant[0]['delivery_time']) - Number(time_passed.minutes);
res.json({time:time_left});
});
});
})
});
//show current orders api
app.get('/api/show-orders-current',function(req,res){
var user_id = req.param("user_id");
var dateFormat = require('dateformat');
var now = new Date();
var timediff = require('timediff');
var time_now = dateFormat(now, "isoDateTime");
con.query('SELECT id AS `key`, info AS title, cost AS price,time_accepted, status,store_id '+
'FROM orders WHERE user_id=? and status < 2 ', [user_id], function(err,data) {
if(!err) {
if(data.length == 0) return res.json({ response: 0 });
else
{
con.query('SELECT delivery_time AS `deliveryTime` '+
'FROM stores WHERE id=? ', [data[0].store_id], function(err,deliveryTime) {
var new_data = [];
for(let i in data){
var timediff = require('timediff');
if(data[i].status == 1){
console.log(data[i])
var time_now = dateFormat(now, "isoDateTime");
var time_accepted = dateFormat(data[i].time_accepted,"isoDateTime");
var time_passed = timediff(time_accepted, time_now, 'YDHms');
console.log('time now :'+time_now +'time accepted : '+time_accepted);
if(data[0].store_id == -1){
time_left = Number(60) - Number(time_passed.minutes);
}
else{
time_left = Number(deliveryTime[0].deliveryTime) - Number(time_passed.minutes);
}
new_data.push({
key:data[i].key,
title:data[i].title,
price:data[i].price,
status:data[i].status,
store_id:data[i].store_id,
time:time_left
})
}
else{
new_data.push({
key:data[i].key,
title:data[i].title,
price:data[i].price,
status:data[i].status,
store_id:data[i].store_id,
})
}
if(i == data.length-1){
if(data[0].store_id == -1){
res.json({
deliveryTime: 60,
response: new_data
});
}else {
res.json({
deliveryTime: deliveryTime[0].deliveryTime,
response: new_data
});
}
}
}
});
}
}
else {
res.json({ response:0, err });
}
});
});
app.get('/api/show-orders-past',function(req,res){
var user_id = req.param("user_id");
con.query('SELECT id AS `key`, info AS title, cost AS price, status,store_id '+
'FROM orders WHERE user_id=? and status = 2 ', [user_id], function(err,data) {
if(!err) {
if(data.length == 0) return res.json({ response: 0 });
else
{
res.json({
response: data
});
}
}
else {
res.json({ response:0, err });
}
});
});
app.get('/api/order-price',function(req,res){
var ids = req.param("ids");
var price = 0;
var store_id = 0;
if(ids == 'null' || ids == 'null,'){
res.json({response:0})
}
else{
var ids = ids.split(",");
for(let i in ids){
if(ids[i] != null || ids[i] != 'null'){
con.query('SELECT cost,store_id '+
'FROM products WHERE id=? LIMIT 1', [ids[i]], function(err,data) {
if(!err) {
var data = data[0];
if(data != null){
var store_id = data.store_id;
}
if(data != null){
console.log(store_id)
price = price + data.cost
}
}
else {
res.json({ response:0, err });
}
if(i == ids.length-1){
con.query('SELECT delivery_cost,delivery_time '+
'FROM stores WHERE id=? LIMIT 1', [store_id], function(err,deliver_price) {
console.log(deliver_price);
// 1- before : delevery price 2 - after : price with delivery
res.json({
before:deliver_price[0].delivery_cost,
after:price+deliver_price[0].delivery_cost,
store_id,
deliveryTime:deliver_price[0].delivery_time
});
});
}
})
}
}
}
});
function push(registrationToken,body){
// See documentation on defining a message payload.
var message = {
notification: {
title:'Talbatk',
body,
icon: "default",
sound:"default",
vibrate:"true"
},
};
var options = {
priority:"high",
}
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().sendToDevice(registrationToken,message,options)
.then((response) => {
// Response is a message ID string.
res.json( response);
})
.catch((error) => {
res.send('Error sending message:', error);
});
}
function SendPushNotifications(pushTokens)
{
// Create a new Expo SDK client
let expo = new Expo();
// Create the messages that you want to send to clents
let messages = [];
for (let pushToken of pushTokens) {
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`);
continue;
}
// Construct a message (see https://docs.expo.io/versions/latest/guides/push-notifications.html)
messages.push({
to: pushToken,
sound: 'default',
body: 'هناك طلب جديد على متجرك، تفحص صفحة طلبات المتجر',
data: { },
})
}
// The Expo push notification service accepts batches of notifications so
// that you don't need to send 1000 requests to send 1000 notifications. We
// recommend you batch your notifications to reduce the number of requests
// and to compress them (notifications with similar content will get
// compressed).
let chunks = expo.chunkPushNotifications(messages);
(async () => {
// Send the chunks to the Expo push notification service. There are
// different strategies you could use. A simple one is to send one chunk at a
// time, which nicely spreads the load out over time:
for (let chunk of chunks) {
try {
let receipts = await expo.sendPushNotificationsAsync(chunk);
console.log(receipts);
} catch (error) {
console.error(error);
}
}
})();
}