-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
396 lines (349 loc) · 11.4 KB
/
database.js
File metadata and controls
396 lines (349 loc) · 11.4 KB
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
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcrypt');
const DB_FILE = path.join(__dirname, 'pharmacy_data.json');
// Initialize database structure
let db = {
users: [],
medicines: [],
stock: [],
customers: [],
suppliers: [],
sales: [],
invoices: [],
purchases: []
};
// Auto-increment IDs
let autoIncrementIds = {
users: 1,
medicines: 1,
stock: 1,
customers: 1,
suppliers: 1,
sales: 1,
invoices: 1,
purchases: 1
};
// Load database from file
function loadDatabase() {
try {
if (fs.existsSync(DB_FILE)) {
const data = fs.readFileSync(DB_FILE, 'utf8');
const loadedData = JSON.parse(data);
db = loadedData.db || db;
autoIncrementIds = loadedData.autoIncrementIds || autoIncrementIds;
console.log('Database loaded successfully');
} else {
initializeDatabase();
}
} catch (error) {
console.error('Error loading database:', error);
initializeDatabase();
}
}
// Save database to file
function saveDatabase() {
try {
const data = JSON.stringify({ db, autoIncrementIds }, null, 2);
fs.writeFileSync(DB_FILE, data, 'utf8');
} catch (error) {
console.error('Error saving database:', error);
}
}
// Initialize database with default admin user
function initializeDatabase() {
const adminExists = db.users.find(u => u.username === 'admin');
if (!adminExists) {
const hashedPassword = bcrypt.hashSync('admin123', 10);
db.users.push({
id: autoIncrementIds.users++,
username: 'admin',
password: hashedPassword,
role: 'Admin',
email: 'admin@pharmacy.com',
created_at: new Date().toISOString()
});
saveDatabase();
console.log('Default admin user created (username: admin, password: admin123)');
}
}
// Helper functions
function getNextId(table) {
return autoIncrementIds[table]++;
}
function getCurrentTimestamp() {
return new Date().toISOString();
}
// Database operations
const database = {
// Users
findUserByUsername: (username) => {
return db.users.find(u => u.username === username);
},
createUser: (userData) => {
const user = {
id: getNextId('users'),
...userData,
created_at: getCurrentTimestamp()
};
db.users.push(user);
saveDatabase();
return user;
},
// Medicines
getAllMedicines: () => {
return db.medicines.map(medicine => {
const supplier = db.suppliers.find(s => s.id === medicine.supplier_id);
return {
...medicine,
supplier_name: supplier ? supplier.name : null
};
});
},
createMedicine: (medicineData) => {
const medicine = {
id: getNextId('medicines'),
...medicineData,
created_at: getCurrentTimestamp(),
updated_at: getCurrentTimestamp()
};
db.medicines.push(medicine);
// Add stock transaction
db.stock.push({
id: getNextId('stock'),
medicine_id: medicine.id,
quantity: medicineData.quantity,
transaction_type: 'IN',
reference: 'Initial Stock',
created_at: getCurrentTimestamp()
});
saveDatabase();
return medicine;
},
updateMedicine: (id, medicineData) => {
const index = db.medicines.findIndex(m => m.id === id);
if (index !== -1) {
db.medicines[index] = {
...db.medicines[index],
...medicineData,
updated_at: getCurrentTimestamp()
};
saveDatabase();
return db.medicines[index];
}
return null;
},
deleteMedicine: (id) => {
const index = db.medicines.findIndex(m => m.id === id);
if (index !== -1) {
db.medicines.splice(index, 1);
saveDatabase();
return true;
}
return false;
},
// Stock
getAllStock: () => {
return db.stock.map(s => {
const medicine = db.medicines.find(m => m.id === s.medicine_id);
return {
...s,
medicine_name: medicine ? medicine.name : 'Unknown'
};
});
},
receiveStock: (stockData) => {
db.stock.push({
id: getNextId('stock'),
...stockData,
transaction_type: 'IN',
created_at: getCurrentTimestamp()
});
// Update medicine quantity
const medicine = db.medicines.find(m => m.id === stockData.medicine_id);
if (medicine) {
medicine.quantity += stockData.quantity;
}
saveDatabase();
},
getLowStock: () => {
return db.medicines.filter(m => m.quantity < 10);
},
// Customers
getAllCustomers: () => db.customers,
createCustomer: (customerData) => {
const customer = {
id: getNextId('customers'),
...customerData,
created_at: getCurrentTimestamp()
};
db.customers.push(customer);
saveDatabase();
return customer;
},
updateCustomer: (id, customerData) => {
const index = db.customers.findIndex(c => c.id === id);
if (index !== -1) {
db.customers[index] = { ...db.customers[index], ...customerData };
saveDatabase();
return db.customers[index];
}
return null;
},
deleteCustomer: (id) => {
const index = db.customers.findIndex(c => c.id === id);
if (index !== -1) {
db.customers.splice(index, 1);
saveDatabase();
return true;
}
return false;
},
getCustomerHistory: (customerId) => {
return db.sales.filter(s => s.customer_id === customerId).map(sale => {
const saleInvoices = db.invoices.filter(i => i.sale_id === sale.id);
const medicines = saleInvoices.map(inv => {
const med = db.medicines.find(m => m.id === inv.medicine_id);
return med ? med.name : 'Unknown';
}).join(', ');
return { ...sale, medicines };
});
},
// Suppliers
getAllSuppliers: () => db.suppliers,
createSupplier: (supplierData) => {
const supplier = {
id: getNextId('suppliers'),
...supplierData,
created_at: getCurrentTimestamp()
};
db.suppliers.push(supplier);
saveDatabase();
return supplier;
},
updateSupplier: (id, supplierData) => {
const index = db.suppliers.findIndex(s => s.id === id);
if (index !== -1) {
db.suppliers[index] = { ...db.suppliers[index], ...supplierData };
saveDatabase();
return db.suppliers[index];
}
return null;
},
deleteSupplier: (id) => {
const index = db.suppliers.findIndex(s => s.id === id);
if (index !== -1) {
db.suppliers.splice(index, 1);
saveDatabase();
return true;
}
return false;
},
// Sales
getAllSales: () => {
return db.sales.map(sale => {
const customer = db.customers.find(c => c.id === sale.customer_id);
const user = db.users.find(u => u.id === sale.created_by);
return {
...sale,
customer_name: customer ? customer.name : null,
created_by_name: user ? user.username : null
};
});
},
createSale: (saleData) => {
const sale = {
id: getNextId('sales'),
customer_id: saleData.customer_id,
total_amount: saleData.total_amount,
discount: saleData.discount,
final_amount: saleData.final_amount,
payment_method: saleData.payment_method,
created_by: saleData.created_by,
created_at: getCurrentTimestamp()
};
db.sales.push(sale);
// Add invoice items
saleData.items.forEach(item => {
db.invoices.push({
id: getNextId('invoices'),
sale_id: sale.id,
medicine_id: item.medicine_id,
quantity: item.quantity,
unit_price: item.unit_price,
total_price: item.quantity * item.unit_price
});
// Update medicine stock
const medicine = db.medicines.find(m => m.id === item.medicine_id);
if (medicine) {
medicine.quantity -= item.quantity;
}
// Add stock transaction
db.stock.push({
id: getNextId('stock'),
medicine_id: item.medicine_id,
quantity: item.quantity,
transaction_type: 'OUT',
reference: `Sale #${sale.id}`,
created_at: getCurrentTimestamp()
});
});
saveDatabase();
return sale;
},
getSaleById: (id) => {
const sale = db.sales.find(s => s.id === id);
if (!sale) return null;
const customer = db.customers.find(c => c.id === sale.customer_id);
const items = db.invoices.filter(i => i.sale_id === id).map(invoice => {
const medicine = db.medicines.find(m => m.id === invoice.medicine_id);
return {
...invoice,
medicine_name: medicine ? medicine.name : 'Unknown'
};
});
return {
...sale,
customer_name: customer ? customer.name : null,
customer_phone: customer ? customer.phone : null,
items
};
},
// Reports
getDashboardStats: () => {
const totalMedicines = db.medicines.length;
const lowStock = db.medicines.filter(m => m.quantity < 10).length;
const today = new Date().toISOString().split('T')[0];
const expired = db.medicines.filter(m => m.expiry_date < today).length;
const todaySales = db.sales
.filter(s => s.created_at.startsWith(today))
.reduce((sum, s) => sum + s.final_amount, 0);
return {
totalMedicines,
lowStock,
expired,
todaySales
};
},
getSalesReport: (startDate, endDate) => {
if (startDate && endDate) {
return db.sales.filter(s => {
const saleDate = s.created_at.split('T')[0];
return saleDate >= startDate && saleDate <= endDate;
});
}
return db.sales;
},
getExpiryReport: () => {
const today = new Date();
const thirtyDaysLater = new Date();
thirtyDaysLater.setDate(today.getDate() + 30);
return db.medicines.filter(m => {
const expiryDate = new Date(m.expiry_date);
return expiryDate > today && expiryDate <= thirtyDaysLater;
});
}
};
// Load database on startup
loadDatabase();
module.exports = database;