Huzaifa1313 commited on
Commit
cbbb3a0
ยท
verified ยท
1 Parent(s): f0f62c7

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +13 -15
  2. README.md +31 -31
  3. package.json +5 -5
  4. server.js +507 -300
Dockerfile CHANGED
@@ -1,16 +1,14 @@
1
- FROM node:18-slim
2
-
3
- WORKDIR /app
4
-
5
- # Package files ko copy karo root mein
6
- COPY hitech-mongodb/package*.json ./
7
- RUN npm install
8
-
9
- # Saara code copy karo
10
- COPY hitech-mongodb/ .
11
-
12
- ENV PORT=7860
13
-
14
- EXPOSE 7860
15
-
16
  CMD ["npm", "start"]
 
1
+ FROM node:18-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY package*.json ./
6
+ RUN npm install
7
+
8
+ COPY . .
9
+
10
+ ENV PORT=7860
11
+
12
+ EXPOSE 7860
13
+
 
 
14
  CMD ["npm", "start"]
README.md CHANGED
@@ -1,32 +1,32 @@
1
- ---
2
- title: HiTech API
3
- emoji: ๐Ÿš€
4
- colorFrom: blue
5
- colorTo: indigo
6
- sdk: docker
7
- sdk_version: "1.0"
8
- app_port: 7860
9
- pinned: false
10
- ---
11
-
12
- # HiTech MongoDB API
13
-
14
- ## ๐Ÿš€ API Endpoints
15
-
16
- | Endpoint | Method | Description |
17
- |----------|--------|-------------|
18
- | `/api/health` | GET | Check server and database status |
19
- | `/api/products` | GET | Get all products |
20
- | `/api/products` | POST | Create new product |
21
- | `/api/users` | GET | Get all users |
22
- | `/api/dashboard/stats` | GET | Get dashboard statistics |
23
-
24
- ## ๐Ÿ“Š Database
25
-
26
- - MongoDB Atlas connected
27
- - Collections: products, users, orders
28
-
29
- ## ๐Ÿ”— Live API
30
-
31
- - Health check: `/api/health`
32
  - Products: `/api/products`
 
1
+ ---
2
+ title: HiTech API
3
+ emoji: ๐Ÿš€
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ sdk_version: "1.0"
8
+ app_port: 7860
9
+ pinned: false
10
+ ---
11
+
12
+ # HiTech MongoDB API
13
+
14
+ ## ๐Ÿš€ API Endpoints
15
+
16
+ | Endpoint | Method | Description |
17
+ |----------|--------|-------------|
18
+ | `/api/health` | GET | Check server and database status |
19
+ | `/api/products` | GET | Get all products |
20
+ | `/api/products` | POST | Create new product |
21
+ | `/api/users` | GET | Get all users |
22
+ | `/api/dashboard/stats` | GET | Get dashboard statistics |
23
+
24
+ ## ๐Ÿ“Š Database
25
+
26
+ - MongoDB Atlas connected
27
+ - Collections: products, users, orders
28
+
29
+ ## ๐Ÿ”— Live API
30
+
31
+ - Health check: `/api/health`
32
  - Products: `/api/products`
package.json CHANGED
@@ -1,11 +1,11 @@
1
  {
2
- "name": "hitech-technologies",
3
  "version": "1.0.0",
4
- "description": "HiTech Technologies - Full Stack Website",
5
- "main": "hitech-mongodb/server.js",
6
  "scripts": {
7
- "start": "node hitech-mongodb/server.js",
8
- "dev": "nodemon hitech-mongodb/server.js"
9
  },
10
  "dependencies": {
11
  "@seald-io/nedb": "^4.0.4",
 
1
  {
2
+ "name": "hitech-mongodb",
3
  "version": "1.0.0",
4
+ "description": "MongoDB-backed server for HiTech Technologies",
5
+ "main": "server.js",
6
  "scripts": {
7
+ "start": "node server.js",
8
+ "dev": "nodemon server.js"
9
  },
10
  "dependencies": {
11
  "@seald-io/nedb": "^4.0.4",
server.js CHANGED
@@ -1,339 +1,546 @@
1
- require('dotenv').config();
2
- const express = require('express');
3
- const Datastore = require('@seald-io/nedb');
4
- const jwt = require('jsonwebtoken');
5
- const bcrypt = require('bcryptjs');
6
- const multer = require('multer');
7
  const path = require('path');
8
  const fs = require('fs');
 
 
9
  const cors = require('cors');
 
 
 
 
 
 
 
 
 
10
 
11
  const app = express();
12
- const PORT = process.env.PORT || 3000;
13
  const JWT_SECRET = process.env.JWT_SECRET || 'hitech_secret_2025';
14
- const dataDir = path.join(__dirname, 'data');
15
- const uploadsDir = path.join(__dirname, 'uploads');
16
 
17
- // โ”€โ”€โ”€ Middleware โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
18
- app.use(cors());
19
- app.use(express.json({ limit: '20mb' }));
20
- app.use(express.urlencoded({ extended: true }));
21
- app.use(express.static(path.join(__dirname, 'public')));
22
- app.use('/uploads', express.static(uploadsDir));
23
-
24
- if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
25
- if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
26
-
27
- // โ”€โ”€โ”€ Databases โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
28
- const db = {
29
- admins: new Datastore({ filename: path.join(dataDir, 'admins.db'), autoload: true }),
30
- settings: new Datastore({ filename: path.join(dataDir, 'settings.db'), autoload: true }),
31
- services: new Datastore({ filename: path.join(dataDir, 'services.db'), autoload: true }),
32
- products: new Datastore({ filename: path.join(dataDir, 'products.db'), autoload: true }),
33
- posts: new Datastore({ filename: path.join(dataDir, 'posts.db'), autoload: true }),
34
- contacts: new Datastore({ filename: path.join(dataDir, 'contacts.db'), autoload: true }),
35
- };
36
 
37
- // Promisify helpers
38
- const normalizeDoc = (doc) => {
 
 
 
 
 
 
 
 
39
  if (!doc) return doc;
 
40
  return {
41
  ...doc,
42
- id: doc._id,
 
43
  created_at: doc.createdAt,
44
  updated_at: doc.updatedAt,
45
  };
46
- };
47
- const normalizeDocs = (docs) => (Array.isArray(docs) ? docs.map(normalizeDoc) : docs);
48
- const dbFind = (col, q={}, sort={}) => new Promise((res,rej) => { let c = col.find(q); if (Object.keys(sort).length) c = c.sort(sort); c.exec((e,d) => e ? rej(e) : res(normalizeDocs(d))); });
49
- const dbFindOne = (col, q) => new Promise((res,rej) => col.findOne(q, (e,d) => e ? rej(e) : res(normalizeDoc(d))));
50
- const dbInsert = (col, d) => new Promise((res,rej) => col.insert(d, (e,r) => e ? rej(e) : res(normalizeDoc(r))));
51
- const dbUpdate = (col, q, u, o={}) => new Promise((res,rej) => col.update(q, u, o, (e,n) => e ? rej(e) : res(n)));
52
- const dbRemove = (col, q, o={}) => new Promise((res,rej) => col.remove(q, o, (e,n) => e ? rej(e) : res(n)));
53
- const dbCount = (col, q={}) => new Promise((res,rej) => col.count(q, (e,n) => e ? rej(e) : res(n)));
54
-
55
- // โ”€โ”€โ”€ Seed admin โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
56
- (async () => {
57
- const admin = await dbFindOne(db.admins, { username: 'Huzaifa' });
58
- if (!admin) {
59
- await dbInsert(db.admins, { username: 'Huzaifa', password_hash: bcrypt.hashSync('12345', 10), createdAt: new Date() });
60
- console.log('โœ… Admin created: Huzaifa / 12345');
61
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- // Seed settings
64
- const defaults = {
65
- company_name: 'HiTech Technologies',
66
- tagline: "Pakistan's Leading Software Company",
67
- hero_title: 'Smart *Software* Solutions That *Scale* With You',
68
- hero_subtitle: 'From custom AI automation to enterprise-grade software systems โ€” we build technology that transforms your business operations and delivers real results.',
69
- about_text: 'HiTech Technologies was founded with a clear mission: to make world-class software development accessible to businesses of every size in Pakistan and beyond. We specialize in custom software, AI automation, data science, mobile apps, web platforms, and enterprise management systems.',
70
- address: 'G-11, Islamabad, Pakistan',
71
- phone: '03345555362',
72
- email: 'info@hitechtech.pk',
73
- whatsapp: '03345555362',
74
- facebook: 'https://facebook.com/hitechtech',
75
- linkedin: 'https://linkedin.com/company/hitechtech',
76
- twitter: 'https://twitter.com/hitechtech',
77
- working_hours: 'Mon โ€“ Sat: 9:00 AM โ€“ 6:00 PM',
78
- footer_text: 'Pakistan\'s trusted software development company. We build custom software, AI automation, and enterprise solutions for businesses of all sizes.'
79
  };
80
- for (const [key, value] of Object.entries(defaults)) {
81
- const ex = await dbFindOne(db.settings, { key });
82
- if (!ex) await dbInsert(db.settings, { key, value });
83
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- // Seed services
86
- const svcCount = await dbCount(db.services);
87
- if (svcCount === 0) {
88
- const svcs = [
89
- { name: 'AI Automation', description: 'Harness artificial intelligence to automate workflows, reduce manual tasks, and optimize operations. We build ML pipelines, chatbots, and intelligent systems that adapt to your business.', icon: 'fa-brain', features: 'Workflow Automation,ML Pipelines,Chatbot Development,Document AI,Predictive Analytics', status: 'active', sort_order: 1 },
90
- { name: 'Data Science Services', description: 'Transform raw data into actionable insights. Custom dashboards, predictive models, and analytics pipelines that empower smarter, data-driven decisions across your organization.', icon: 'fa-chart-bar', features: 'Data Analytics,Custom Dashboards,Predictive Models,Business Intelligence,Data Engineering', status: 'active', sort_order: 2 },
91
- { name: 'POS Software', description: 'Feature-rich Point-of-Sale systems for retail, restaurants, pharmacies, and all business types. Inventory control, fast billing, multi-branch support, and real-time reporting in one system.', icon: 'fa-cash-register', features: 'Inventory Control,Multi-Branch,Barcode Support,Sales Reports,Customer Loyalty', status: 'active', sort_order: 3 },
92
- { name: 'App Development', description: 'Beautiful, high-performance mobile applications for iOS and Android. We develop native and cross-platform apps using Flutter and React Native with exceptional user experiences.', icon: 'fa-mobile-alt', features: 'iOS & Android,Flutter / React Native,UI/UX Design,API Integration,Push Notifications', status: 'active', sort_order: 4 },
93
- { name: 'Web Development', description: 'Responsive, fast, and scalable web applications built with modern frameworks. From corporate websites to complex enterprise portals โ€” we deliver exceptional digital experiences.', icon: 'fa-globe', features: 'React / Vue / Next.js,E-Commerce,Web Portals,REST APIs,SEO Optimized', status: 'active', sort_order: 5 },
94
- { name: 'Custom Software', description: 'Bespoke software built from scratch to match your unique business processes. ERP systems, CRM solutions, billing platforms, and specialized industry tools tailored to your workflow.', icon: 'fa-code', features: 'ERP Systems,CRM Solutions,Billing Systems,HR & Payroll,API Development', status: 'active', sort_order: 6 }
95
- ];
96
- for (const s of svcs) await dbInsert(db.services, { ...s, banner_url: null, createdAt: new Date() });
 
 
 
 
 
 
 
 
 
 
 
 
97
  }
98
 
99
- // Seed products
100
- const prodCount = await dbCount(db.products);
101
- if (prodCount === 0) {
102
- const prods = [
103
- { name: 'School Management System', category: 'Education', description: 'A complete academic management platform for schools, colleges, and educational institutes. Manage everything from admissions to results in one centralized system with parent portal and SMS alerts.', features: 'Student Enrollment & Records,Attendance Tracking (Manual & Biometric),Fee Collection & Receipts,Grade Book & Result Management,Parent Portal & SMS Notifications,Teacher & Staff Management,Library Management,Timetable & Scheduling', banner_color: '#0D2B7A', banner_url: null, status: 'active' },
104
- { name: 'Patient Token System', category: 'Healthcare', description: 'Eliminate waiting room chaos with a smart patient queuing system for clinics, hospitals, and labs. Display tokens on screen, notify patients via SMS, and manage priorities with ease.', features: 'Auto Token Generation,Digital Display Screen,Priority Queue (Emergency),SMS & WhatsApp Notifications,Multiple Counter Support,Doctor-Wise Queuing,Daily Reports & Analytics,Multi-Branch Support', banner_color: '#C91F1F', banner_url: null, status: 'active' },
105
- { name: 'Gym Management System', category: 'Fitness', description: 'A powerful gym and fitness center management platform. Handle memberships, payments, staff, workout plans, and member check-in all in one comprehensive system.', features: 'Member Registration & Profiles,Subscription & Membership Plans,Automated Billing & Renewals,Biometric / Card Check-in,Staff & Trainer Management,Workout Plan Assignment,Expiry Alerts & Notifications,Revenue Reports & Analytics', banner_color: '#071B52', banner_url: null, status: 'active' }
106
- ];
107
- for (const p of prods) await dbInsert(db.products, { ...p, createdAt: new Date() });
108
  }
109
 
110
- console.log('โœ… Database ready');
111
- })();
112
-
113
- // โ”€โ”€โ”€ Auth Middleware โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
114
- const auth = async (req, res, next) => {
115
- const token = req.headers.authorization?.split(' ')[1];
116
- if (!token) return res.status(401).json({ error: 'Unauthorized' });
117
- try { req.user = jwt.verify(token, JWT_SECRET); next(); }
118
- catch { res.status(401).json({ error: 'Invalid token' }); }
119
- };
120
-
121
- // โ”€โ”€โ”€ Multer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
122
- const storage = multer.diskStorage({
123
- destination: (req, file, cb) => cb(null, uploadsDir),
124
- filename: (req, file, cb) => cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${path.extname(file.originalname)}`)
125
- });
126
- const upload = multer({ storage, limits: { fileSize: 10 * 1024 * 1024 }, fileFilter: (req, file, cb) => { if (/image/.test(file.mimetype)) cb(null, true); else cb(new Error('Images only')); } });
127
 
128
- // โ”€โ”€โ”€ AUTH โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
129
- app.post('/api/auth/login', async (req, res) => {
130
- try {
131
- const { username, password } = req.body;
132
- if (!username || !password) return res.status(400).json({ error: 'Username and password required' });
133
- const user = await dbFindOne(db.admins, { username });
134
- if (!user || !bcrypt.compareSync(password, user.password_hash)) return res.status(401).json({ error: 'Invalid credentials' });
135
- const token = jwt.sign({ id: user._id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
136
- res.json({ token, username: user.username });
137
- } catch (e) { res.status(500).json({ error: e.message }); }
138
- });
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
- app.post('/api/auth/change-password', auth, async (req, res) => {
141
- try {
142
- const { currentPassword, newPassword } = req.body;
143
- const user = await dbFindOne(db.admins, { _id: req.user.id });
144
- if (!user || !bcrypt.compareSync(currentPassword, user.password_hash)) return res.status(401).json({ error: 'Current password incorrect' });
145
- await dbUpdate(db.admins, { _id: req.user.id }, { $set: { password_hash: bcrypt.hashSync(newPassword, 10) } });
146
- res.json({ success: true });
147
- } catch (e) { res.status(500).json({ error: e.message }); }
148
- });
149
 
150
- // โ”€โ”€โ”€ SETTINGS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
151
- app.get('/api/settings', async (req, res) => {
152
- try {
153
- const rows = await dbFind(db.settings);
154
- const settings = {};
155
- rows.forEach(r => settings[r.key] = r.value);
156
- res.json(settings);
157
- } catch (e) { res.status(500).json({ error: e.message }); }
158
- });
159
 
160
- app.put('/api/settings', auth, async (req, res) => {
161
  try {
162
- for (const [key, value] of Object.entries(req.body)) {
163
- const ex = await dbFindOne(db.settings, { key });
164
- if (ex) await dbUpdate(db.settings, { key }, { $set: { value: value || '' } });
165
- else await dbInsert(db.settings, { key, value: value || '' });
 
 
 
 
 
 
166
  }
167
- res.json({ success: true });
168
- } catch (e) { res.status(500).json({ error: e.message }); }
169
- });
170
-
171
- // โ”€โ”€โ”€ SERVICES โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
172
- app.get('/api/services', async (req, res) => {
173
- try {
174
- const query = req.query.all ? {} : { status: 'active' };
175
- const svcs = await dbFind(db.services, query, { sort_order: 1 });
176
- res.json(svcs);
177
- } catch (e) { res.status(500).json({ error: e.message }); }
178
- });
179
-
180
- app.post('/api/services', auth, upload.single('banner'), async (req, res) => {
181
- try {
182
- const { name, description, icon, features, status, sort_order } = req.body;
183
- if (!name) return res.status(400).json({ error: 'Name required' });
184
- const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
185
- const doc = await dbInsert(db.services, { name, description: description||'', icon: icon||'fa-cog', banner_url, features: features||'', status: status||'active', sort_order: parseInt(sort_order)||0, createdAt: new Date() });
186
- res.json(doc);
187
- } catch (e) { res.status(500).json({ error: e.message }); }
188
- });
189
-
190
- app.put('/api/services/:id', auth, upload.single('banner'), async (req, res) => {
191
- try {
192
- const { name, description, icon, features, status, sort_order } = req.body;
193
- const existing = await dbFindOne(db.services, { _id: req.params.id });
194
- if (!existing) return res.status(404).json({ error: 'Not found' });
195
- const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url;
196
- if (req.file && existing.banner_url) { const fp = path.join(__dirname, existing.banner_url.replace(/^\//, '')); if (fs.existsSync(fp)) fs.unlinkSync(fp); }
197
- await dbUpdate(db.services, { _id: req.params.id }, { $set: { name: name||existing.name, description: description??existing.description, icon: icon||existing.icon, banner_url, features: features??existing.features, status: status||existing.status, sort_order: parseInt(sort_order)??existing.sort_order, updatedAt: new Date() } });
198
- res.json({ success: true, banner_url });
199
- } catch (e) { res.status(500).json({ error: e.message }); }
200
- });
201
-
202
- app.delete('/api/services/:id', auth, async (req, res) => {
203
- try {
204
- const s = await dbFindOne(db.services, { _id: req.params.id });
205
- if (!s) return res.status(404).json({ error: 'Not found' });
206
- if (s.banner_url) { const fp = path.join(__dirname, s.banner_url.replace(/^\//, '')); if (fs.existsSync(fp)) fs.unlinkSync(fp); }
207
- await dbRemove(db.services, { _id: req.params.id });
208
- res.json({ success: true });
209
- } catch (e) { res.status(500).json({ error: e.message }); }
210
- });
211
-
212
- // โ”€โ”€โ”€ PRODUCTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
213
- app.get('/api/products', async (req, res) => {
214
- try {
215
- const query = req.query.all ? {} : { status: 'active' };
216
- res.json(await dbFind(db.products, query, { createdAt: 1 }));
217
- } catch (e) { res.status(500).json({ error: e.message }); }
218
- });
219
-
220
- app.post('/api/products', auth, upload.single('banner'), async (req, res) => {
221
- try {
222
- const { name, category, description, features, banner_color, status } = req.body;
223
- if (!name) return res.status(400).json({ error: 'Name required' });
224
- const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
225
- const doc = await dbInsert(db.products, { name, category: category||'', description: description||'', features: features||'', banner_url, banner_color: banner_color||'#0D2B7A', status: status||'active', createdAt: new Date() });
226
- res.json(doc);
227
- } catch (e) { res.status(500).json({ error: e.message }); }
228
- });
229
-
230
- app.put('/api/products/:id', auth, upload.single('banner'), async (req, res) => {
231
- try {
232
- const { name, category, description, features, banner_color, status } = req.body;
233
- const ex = await dbFindOne(db.products, { _id: req.params.id });
234
- if (!ex) return res.status(404).json({ error: 'Not found' });
235
- const banner_url = req.file ? `/uploads/${req.file.filename}` : ex.banner_url;
236
- if (req.file && ex.banner_url) { const fp = path.join(__dirname, ex.banner_url.replace(/^\//, '')); if (fs.existsSync(fp)) fs.unlinkSync(fp); }
237
- await dbUpdate(db.products, { _id: req.params.id }, { $set: { name: name||ex.name, category: category??ex.category, description: description??ex.description, features: features??ex.features, banner_url, banner_color: banner_color||ex.banner_color, status: status||ex.status, updatedAt: new Date() } });
238
- res.json({ success: true, banner_url });
239
- } catch (e) { res.status(500).json({ error: e.message }); }
240
- });
241
-
242
- app.delete('/api/products/:id', auth, async (req, res) => {
243
- try {
244
- const p = await dbFindOne(db.products, { _id: req.params.id });
245
- if (!p) return res.status(404).json({ error: 'Not found' });
246
- if (p.banner_url) { const fp = path.join(__dirname, p.banner_url.replace(/^\//, '')); if (fs.existsSync(fp)) fs.unlinkSync(fp); }
247
- await dbRemove(db.products, { _id: req.params.id });
248
- res.json({ success: true });
249
- } catch (e) { res.status(500).json({ error: e.message }); }
250
- });
251
-
252
- // โ”€โ”€โ”€ POSTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
253
- app.get('/api/posts', async (req, res) => {
254
- try {
255
- const query = req.query.all ? {} : { status: 'published' };
256
- res.json(await dbFind(db.posts, query, { createdAt: -1 }));
257
- } catch (e) { res.status(500).json({ error: e.message }); }
258
- });
259
-
260
- app.post('/api/posts', auth, upload.single('banner'), async (req, res) => {
261
- try {
262
- const { title, content, excerpt, status } = req.body;
263
- if (!title) return res.status(400).json({ error: 'Title required' });
264
- const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
265
- const doc = await dbInsert(db.posts, { title, content: content||'', excerpt: excerpt||'', banner_url, status: status||'published', createdAt: new Date() });
266
- res.json(doc);
267
- } catch (e) { res.status(500).json({ error: e.message }); }
268
- });
269
-
270
- app.put('/api/posts/:id', auth, upload.single('banner'), async (req, res) => {
271
- try {
272
- const { title, content, excerpt, status } = req.body;
273
- const ex = await dbFindOne(db.posts, { _id: req.params.id });
274
- if (!ex) return res.status(404).json({ error: 'Not found' });
275
- const banner_url = req.file ? `/uploads/${req.file.filename}` : ex.banner_url;
276
- if (req.file && ex.banner_url) { const fp = path.join(__dirname, ex.banner_url.replace(/^\//, '')); if (fs.existsSync(fp)) fs.unlinkSync(fp); }
277
- await dbUpdate(db.posts, { _id: req.params.id }, { $set: { title: title||ex.title, content: content??ex.content, excerpt: excerpt??ex.excerpt, banner_url, status: status||ex.status, updatedAt: new Date() } });
278
- res.json({ success: true });
279
- } catch (e) { res.status(500).json({ error: e.message }); }
280
- });
281
 
282
- app.delete('/api/posts/:id', auth, async (req, res) => {
283
- try {
284
- const p = await dbFindOne(db.posts, { _id: req.params.id });
285
- if (!p) return res.status(404).json({ error: 'Not found' });
286
- if (p.banner_url) { const fp = path.join(__dirname, p.banner_url.replace(/^\//, '')); if (fs.existsSync(fp)) fs.unlinkSync(fp); }
287
- await dbRemove(db.posts, { _id: req.params.id });
288
- res.json({ success: true });
289
- } catch (e) { res.status(500).json({ error: e.message }); }
290
- });
291
 
292
- // โ”€โ”€โ”€ CONTACTS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
293
- app.post('/api/contact', async (req, res) => {
 
294
  try {
295
- const { name, email, phone, service_interest, budget, message } = req.body;
296
- if (!name || !message) return res.status(400).json({ error: 'Name and message required' });
297
- await dbInsert(db.contacts, { name, email: email||'', phone: phone||'', service_interest: service_interest||'', budget: budget||'', message, is_read: false, createdAt: new Date() });
298
- res.json({ success: true, message: 'Your message has been received! We will contact you within 24 hours.' });
299
- } catch (e) { res.status(500).json({ error: e.message }); }
300
  });
301
 
302
- app.get('/api/contacts', auth, async (req, res) => {
303
- try { res.json(await dbFind(db.contacts, {}, { createdAt: -1 })); }
304
- catch (e) { res.status(500).json({ error: e.message }); }
305
  });
306
 
307
- app.put('/api/contacts/:id/read', auth, async (req, res) => {
308
- try { await dbUpdate(db.contacts, { _id: req.params.id }, { $set: { is_read: true } }); res.json({ success: true }); }
309
- catch (e) { res.status(500).json({ error: e.message }); }
 
 
 
 
310
  });
311
 
312
- app.delete('/api/contacts/:id', auth, async (req, res) => {
313
- try { await dbRemove(db.contacts, { _id: req.params.id }); res.json({ success: true }); }
314
- catch (e) { res.status(500).json({ error: e.message }); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  });
316
 
317
- // โ”€โ”€โ”€ STATS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
318
- app.get('/api/admin/stats', auth, async (req, res) => {
319
- try {
320
- res.json({
321
- services: await dbCount(db.services, { status: 'active' }),
322
- products: await dbCount(db.products, { status: 'active' }),
323
- posts: await dbCount(db.posts, { status: 'published' }),
324
- contacts: await dbCount(db.contacts),
325
- unread: await dbCount(db.contacts, { is_read: false })
326
  });
327
- } catch (e) { res.status(500).json({ error: e.message }); }
328
- });
329
-
330
- // โ”€โ”€โ”€ Fallback โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
331
- app.get('/admin', (req, res) => res.sendFile(path.join(__dirname, 'public', 'admin.html')));
332
- app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html')));
333
-
334
- // โ”€โ”€โ”€ Start โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
335
- app.listen(PORT, () => {
336
- console.log(`\n๐Ÿš€ HiTech Technologies โ€” http://localhost:${PORT}`);
337
- console.log(`๐Ÿ”‘ Admin Panel โ€” http://localhost:${PORT}/admin`);
338
- console.log(` Username: Huzaifa | Password: 12345\n`);
339
- });
 
 
 
 
 
 
 
1
  const path = require('path');
2
  const fs = require('fs');
3
+ const dns = require('dns');
4
+ const express = require('express');
5
  const cors = require('cors');
6
+ const dotenv = require('dotenv');
7
+ const bcrypt = require('bcryptjs');
8
+ const jwt = require('jsonwebtoken');
9
+ const multer = require('multer');
10
+ const Datastore = require('@seald-io/nedb');
11
+ const { MongoClient, ObjectId } = require('mongodb');
12
+
13
+ dotenv.config({ path: path.join(__dirname, '.env') });
14
+ dotenv.config({ path: path.join(__dirname, '..', '.env') });
15
 
16
  const app = express();
17
+ const PORT = Number(process.env.PORT || 3001);
18
  const JWT_SECRET = process.env.JWT_SECRET || 'hitech_secret_2025';
19
+ const MONGODB_URI = process.env.MONGODB_URI;
20
+ const MONGODB_DB = process.env.MONGODB_DB || 'hitech_technologies';
21
 
22
+ const ROOT_DIR = path.join(__dirname, '..');
23
+ const PUBLIC_DIR = path.join(ROOT_DIR, 'public');
24
+ const UPLOADS_DIR = path.join(ROOT_DIR, 'uploads');
25
+ const LEGACY_DATA_DIR = path.join(ROOT_DIR, 'data');
26
+
27
+ let mongoClient;
28
+ let mongoDb;
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
31
+ const collection = (name) => mongoDb.collection(name);
32
+ const toObjectId = (value) => (ObjectId.isValid(value) ? new ObjectId(value) : null);
33
+
34
+ function ensureDirs() {
35
+ if (!fs.existsSync(UPLOADS_DIR)) fs.mkdirSync(UPLOADS_DIR, { recursive: true });
36
+ if (!fs.existsSync(LEGACY_DATA_DIR)) fs.mkdirSync(LEGACY_DATA_DIR, { recursive: true });
37
+ }
38
+
39
+ function normalizeDoc(doc) {
40
  if (!doc) return doc;
41
+ const id = String(doc._id);
42
  return {
43
  ...doc,
44
+ _id: id,
45
+ id,
46
  created_at: doc.createdAt,
47
  updated_at: doc.updatedAt,
48
  };
49
+ }
50
+
51
+ const normalizeDocs = (docs) => (Array.isArray(docs) ? docs.map(normalizeDoc) : []);
52
+
53
+ async function findDocs(name, query = {}, sort = {}) {
54
+ let cursor = collection(name).find(query);
55
+ if (Object.keys(sort).length) cursor = cursor.sort(sort);
56
+ return normalizeDocs(await cursor.toArray());
57
+ }
58
+
59
+ async function findOneDoc(name, query = {}) {
60
+ return normalizeDoc(await collection(name).findOne(query));
61
+ }
62
+
63
+ async function insertDoc(name, doc) {
64
+ const result = await collection(name).insertOne(doc);
65
+ return normalizeDoc({ ...doc, _id: result.insertedId });
66
+ }
67
+
68
+ async function updateDoc(name, query, set, options = {}) {
69
+ return collection(name).updateOne(query, { $set: set }, options);
70
+ }
71
+
72
+ async function upsertDoc(name, query, set) {
73
+ return collection(name).updateOne(query, { $set: set }, { upsert: true });
74
+ }
75
+
76
+ async function removeDoc(name, query) {
77
+ return collection(name).deleteOne(query);
78
+ }
79
+
80
+ async function countDocs(name, query = {}) {
81
+ return collection(name).countDocuments(query);
82
+ }
83
+
84
+ function deleteStoredFile(urlPath) {
85
+ if (!urlPath || typeof urlPath !== 'string') return;
86
+ const safeRelative = urlPath.replace(/^\//, '');
87
+ const fullPath = path.join(ROOT_DIR, safeRelative);
88
+ if (!fullPath.startsWith(UPLOADS_DIR)) return;
89
+ if (fs.existsSync(fullPath)) fs.unlinkSync(fullPath);
90
+ }
91
+
92
+ function legacyFile(name) {
93
+ return path.join(LEGACY_DATA_DIR, `${name}.db`);
94
+ }
95
+
96
+ function loadLegacyDocs(filePath) {
97
+ return new Promise((resolve, reject) => {
98
+ if (!fs.existsSync(filePath)) return resolve([]);
99
+ const store = new Datastore({ filename: filePath, autoload: true });
100
+ store.find({}).exec((err, docs) => {
101
+ if (err) return reject(err);
102
+ resolve(docs || []);
103
+ });
104
+ });
105
+ }
106
 
107
+ function legacyDocToMongo(doc) {
108
+ if (!doc) return doc;
109
+ const { _id, ...rest } = doc;
110
+ return {
111
+ ...rest,
112
+ legacyId: _id ? String(_id) : undefined,
113
+ createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(),
114
+ updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : undefined,
 
 
 
 
 
 
 
 
115
  };
116
+ }
117
+
118
+ function stripUndefined(doc) {
119
+ return Object.fromEntries(Object.entries(doc).filter(([, value]) => value !== undefined));
120
+ }
121
+
122
+ const DEFAULT_SETTINGS = {
123
+ company_name: 'HiTech Technologies',
124
+ tagline: "Pakistan's Leading Software Company",
125
+ hero_title: 'Smart *Software* Solutions That *Scale* With You',
126
+ hero_subtitle: 'From custom AI automation to enterprise-grade software systems - we build technology that transforms your business operations and delivers real results.',
127
+ about_text: 'HiTech Technologies was founded with a clear mission: to make world-class software development accessible to businesses of every size in Pakistan and beyond. We specialize in custom software, AI automation, data science, mobile apps, web platforms, and enterprise management systems.',
128
+ address: 'G-11, Islamabad, Pakistan',
129
+ phone: '03345555362',
130
+ email: 'info@hitechtech.pk',
131
+ whatsapp: '03345555362',
132
+ facebook: 'https://facebook.com/hitechtech',
133
+ linkedin: 'https://linkedin.com/company/hitechtech',
134
+ twitter: 'https://twitter.com/hitechtech',
135
+ working_hours: 'Mon - Sat: 9:00 AM - 6:00 PM',
136
+ footer_text: "Pakistan's trusted software development company. We build custom software, AI automation, and enterprise solutions for businesses of all sizes.",
137
+ };
138
 
139
+ const DEFAULT_SERVICES = [
140
+ { name: 'AI Automation', description: 'Harness artificial intelligence to automate workflows, reduce manual tasks, and optimize operations. We build ML pipelines, chatbots, and intelligent systems that adapt to your business.', icon: 'fa-brain', features: 'Workflow Automation,ML Pipelines,Chatbot Development,Document AI,Predictive Analytics', status: 'active', sort_order: 1 },
141
+ { name: 'Data Science Services', description: 'Transform raw data into actionable insights. Custom dashboards, predictive models, and analytics pipelines that empower smarter, data-driven decisions across your organization.', icon: 'fa-chart-bar', features: 'Data Analytics,Custom Dashboards,Predictive Models,Business Intelligence,Data Engineering', status: 'active', sort_order: 2 },
142
+ { name: 'POS Software', description: 'Feature-rich Point-of-Sale systems for retail, restaurants, pharmacies, and all business types. Inventory control, fast billing, multi-branch support, and real-time reporting in one system.', icon: 'fa-cash-register', features: 'Inventory Control,Multi-Branch,Barcode Support,Sales Reports,Customer Loyalty', status: 'active', sort_order: 3 },
143
+ { name: 'App Development', description: 'Beautiful, high-performance mobile applications for iOS and Android. We develop native and cross-platform apps using Flutter and React Native with exceptional user experiences.', icon: 'fa-mobile-alt', features: 'iOS & Android,Flutter / React Native,UI/UX Design,API Integration,Push Notifications', status: 'active', sort_order: 4 },
144
+ { name: 'Web Development', description: 'Responsive, fast, and scalable web applications built with modern frameworks. From corporate websites to complex enterprise portals - we deliver exceptional digital experiences.', icon: 'fa-globe', features: 'React / Vue / Next.js,E-Commerce,Web Portals,REST APIs,SEO Optimized', status: 'active', sort_order: 5 },
145
+ { name: 'Custom Software', description: 'Bespoke software built from scratch to match your unique business processes. ERP systems, CRM solutions, billing platforms, and specialized industry tools tailored to your workflow.', icon: 'fa-code', features: 'ERP Systems,CRM Solutions,Billing Systems,HR & Payroll,API Development', status: 'active', sort_order: 6 },
146
+ ];
147
+
148
+ const DEFAULT_PRODUCTS = [
149
+ { name: 'School Management System', category: 'Education', description: 'A complete academic management platform for schools, colleges, and educational institutes. Manage everything from admissions to results in one centralized system with parent portal and SMS alerts.', features: 'Student Enrollment & Records,Attendance Tracking (Manual & Biometric),Fee Collection & Receipts,Grade Book & Result Management,Parent Portal & SMS Notifications,Teacher & Staff Management,Library Management,Timetable & Scheduling', banner_color: '#0D2B7A', status: 'active' },
150
+ { name: 'Patient Token System', category: 'Healthcare', description: 'Eliminate waiting room chaos with a smart patient queuing system for clinics, hospitals, and labs. Display tokens on screen, notify patients via SMS, and manage priorities with ease.', features: 'Auto Token Generation,Digital Display Screen,Priority Queue (Emergency),SMS & WhatsApp Notifications,Multiple Counter Support,Doctor-Wise Queuing,Daily Reports & Analytics,Multi-Branch Support', banner_color: '#C91F1F', status: 'active' },
151
+ { name: 'Gym Management System', category: 'Fitness', description: 'A powerful gym and fitness center management platform. Handle memberships, payments, staff, workout plans, and member check-in all in one comprehensive system.', features: 'Member Registration & Profiles,Subscription & Membership Plans,Automated Billing & Renewals,Biometric / Card Check-in,Staff & Trainer Management,Workout Plan Assignment,Expiry Alerts & Notifications,Revenue Reports & Analytics', banner_color: '#071B52', status: 'active' },
152
+ ];
153
+
154
+ async function seedDefaults() {
155
+ const adminCount = await countDocs('admins');
156
+ if (adminCount === 0) {
157
+ await insertDoc('admins', {
158
+ username: 'Huzaifa',
159
+ password_hash: bcrypt.hashSync('12345', 10),
160
+ createdAt: new Date(),
161
+ });
162
+ console.log('Seeded default admin: Huzaifa / 12345');
163
  }
164
 
165
+ const settingsCount = await countDocs('settings');
166
+ if (settingsCount === 0) {
167
+ const docs = Object.entries(DEFAULT_SETTINGS).map(([key, value]) => ({ key, value }));
168
+ await collection('settings').insertMany(docs);
 
 
 
 
 
169
  }
170
 
171
+ const servicesCount = await countDocs('services');
172
+ if (servicesCount === 0) {
173
+ const docs = DEFAULT_SERVICES.map((doc) => ({ ...doc, banner_url: null, createdAt: new Date() }));
174
+ await collection('services').insertMany(docs);
175
+ }
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
+ const productsCount = await countDocs('products');
178
+ if (productsCount === 0) {
179
+ const docs = DEFAULT_PRODUCTS.map((doc) => ({ ...doc, banner_url: null, createdAt: new Date() }));
180
+ await collection('products').insertMany(docs);
181
+ }
182
+ }
183
+
184
+ async function migrateLegacyCollection(collectionName, filePath, mapper = legacyDocToMongo) {
185
+ const currentCount = await countDocs(collectionName);
186
+ if (currentCount > 0) return;
187
+ const docs = await loadLegacyDocs(filePath);
188
+ if (!docs.length) return;
189
+ const mapped = docs.map(mapper).map(stripUndefined);
190
+ if (!mapped.length) return;
191
+ await collection(collectionName).insertMany(mapped);
192
+ console.log(`Migrated ${mapped.length} docs into ${collectionName}`);
193
+ }
194
+
195
+ async function bootstrapDatabase() {
196
+ ensureDirs();
197
+ if (!MONGODB_URI) {
198
+ throw new Error('MONGODB_URI is missing. Put it in hitech-mongodb/.env');
199
+ }
200
 
201
+ const connectOptions = {
202
+ serverSelectionTimeoutMS: 10000,
203
+ };
 
 
 
 
 
 
204
 
205
+ const tryConnect = async () => {
206
+ mongoClient = new MongoClient(MONGODB_URI, connectOptions);
207
+ await mongoClient.connect();
208
+ mongoDb = mongoClient.db(MONGODB_DB);
209
+ };
 
 
 
 
210
 
 
211
  try {
212
+ await tryConnect();
213
+ } catch (error) {
214
+ const isSrvUri = MONGODB_URI.startsWith('mongodb+srv://');
215
+ const isSrvLookupError = String(error?.message || '').includes('querySrv') || String(error?.code || '').includes('ECONNREFUSED');
216
+ if (isSrvUri && isSrvLookupError) {
217
+ dns.setServers(['1.1.1.1', '8.8.8.8']);
218
+ await tryConnect();
219
+ console.log('MongoDB connected after switching DNS resolvers to 1.1.1.1 / 8.8.8.8');
220
+ } else {
221
+ throw error;
222
  }
223
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
+ await migrateLegacyCollection('admins', legacyFile('admins'));
226
+ await migrateLegacyCollection('settings', legacyFile('settings'));
227
+ await migrateLegacyCollection('services', legacyFile('services'));
228
+ await migrateLegacyCollection('products', legacyFile('products'));
229
+ await migrateLegacyCollection('posts', legacyFile('posts'));
230
+ await migrateLegacyCollection('contacts', legacyFile('contacts'));
231
+ await seedDefaults();
232
+ }
 
233
 
234
+ const auth = asyncHandler(async (req, res, next) => {
235
+ const token = req.headers.authorization?.split(' ')[1];
236
+ if (!token) return res.status(401).json({ error: 'Unauthorized' });
237
  try {
238
+ req.user = jwt.verify(token, JWT_SECRET);
239
+ next();
240
+ } catch {
241
+ res.status(401).json({ error: 'Invalid token' });
242
+ }
243
  });
244
 
245
+ const storage = multer.diskStorage({
246
+ destination: (req, file, cb) => cb(null, UPLOADS_DIR),
247
+ filename: (req, file, cb) => cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${path.extname(file.originalname)}`),
248
  });
249
 
250
+ const upload = multer({
251
+ storage,
252
+ limits: { fileSize: 10 * 1024 * 1024 },
253
+ fileFilter: (req, file, cb) => {
254
+ if (/image/.test(file.mimetype)) cb(null, true);
255
+ else cb(new Error('Images only'));
256
+ },
257
  });
258
 
259
+ app.use(cors());
260
+ app.use(express.json({ limit: '20mb' }));
261
+ app.use(express.urlencoded({ extended: true }));
262
+ app.use(express.static(PUBLIC_DIR));
263
+ app.use('/uploads', express.static(UPLOADS_DIR));
264
+
265
+ app.post('/api/auth/login', asyncHandler(async (req, res) => {
266
+ const { username, password } = req.body;
267
+ if (!username || !password) return res.status(400).json({ error: 'Username and password required' });
268
+ const user = await findOneDoc('admins', { username });
269
+ if (!user || !bcrypt.compareSync(password, user.password_hash)) {
270
+ return res.status(401).json({ error: 'Invalid credentials' });
271
+ }
272
+ const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
273
+ res.json({ token, username: user.username });
274
+ }));
275
+
276
+ app.post('/api/auth/change-password', auth, asyncHandler(async (req, res) => {
277
+ const { currentPassword, newPassword } = req.body;
278
+ const user = await findOneDoc('admins', { _id: toObjectId(req.user.id) });
279
+ if (!user || !bcrypt.compareSync(currentPassword, user.password_hash)) {
280
+ return res.status(401).json({ error: 'Current password incorrect' });
281
+ }
282
+ await updateDoc('admins', { _id: toObjectId(req.user.id) }, { password_hash: bcrypt.hashSync(newPassword, 10) });
283
+ res.json({ success: true });
284
+ }));
285
+
286
+ app.get('/api/settings', asyncHandler(async (req, res) => {
287
+ const rows = await findDocs('settings');
288
+ const settings = {};
289
+ rows.forEach((row) => {
290
+ settings[row.key] = row.value;
291
+ });
292
+ res.json(settings);
293
+ }));
294
+
295
+ app.put('/api/settings', auth, asyncHandler(async (req, res) => {
296
+ for (const [key, value] of Object.entries(req.body)) {
297
+ await upsertDoc('settings', { key }, { key, value: value || '' });
298
+ }
299
+ res.json({ success: true });
300
+ }));
301
+
302
+ app.get('/api/services', asyncHandler(async (req, res) => {
303
+ const query = req.query.all ? {} : { status: 'active' };
304
+ const docs = await findDocs('services', query, { sort_order: 1, createdAt: 1 });
305
+ res.json(docs);
306
+ }));
307
+
308
+ app.post('/api/services', auth, upload.single('banner'), asyncHandler(async (req, res) => {
309
+ const { name, description, icon, features, status, sort_order } = req.body;
310
+ if (!name) return res.status(400).json({ error: 'Name required' });
311
+ const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
312
+ const doc = await insertDoc('services', {
313
+ name,
314
+ description: description || '',
315
+ icon: icon || 'fa-cog',
316
+ banner_url,
317
+ features: features || '',
318
+ status: status || 'active',
319
+ sort_order: Number.isFinite(Number(sort_order)) ? Number(sort_order) : 0,
320
+ createdAt: new Date(),
321
+ });
322
+ res.json(doc);
323
+ }));
324
+
325
+ app.put('/api/services/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => {
326
+ const existingId = toObjectId(req.params.id);
327
+ if (!existingId) return res.status(404).json({ error: 'Not found' });
328
+ const existing = await findOneDoc('services', { _id: existingId });
329
+ if (!existing) return res.status(404).json({ error: 'Not found' });
330
+
331
+ const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url;
332
+ if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url);
333
+
334
+ await updateDoc('services', { _id: existingId }, {
335
+ name: req.body.name || existing.name,
336
+ description: req.body.description ?? existing.description,
337
+ icon: req.body.icon || existing.icon,
338
+ banner_url,
339
+ features: req.body.features ?? existing.features,
340
+ status: req.body.status || existing.status,
341
+ sort_order: Number.isFinite(Number(req.body.sort_order)) ? Number(req.body.sort_order) : existing.sort_order,
342
+ updatedAt: new Date(),
343
+ });
344
+
345
+ res.json({ success: true, banner_url });
346
+ }));
347
+
348
+ app.delete('/api/services/:id', auth, asyncHandler(async (req, res) => {
349
+ const id = toObjectId(req.params.id);
350
+ if (!id) return res.status(404).json({ error: 'Not found' });
351
+ const service = await findOneDoc('services', { _id: id });
352
+ if (!service) return res.status(404).json({ error: 'Not found' });
353
+ if (service.banner_url) deleteStoredFile(service.banner_url);
354
+ await removeDoc('services', { _id: id });
355
+ res.json({ success: true });
356
+ }));
357
+
358
+ app.get('/api/products', asyncHandler(async (req, res) => {
359
+ const query = req.query.all ? {} : { status: 'active' };
360
+ const docs = await findDocs('products', query, { createdAt: 1 });
361
+ res.json(docs);
362
+ }));
363
+
364
+ app.post('/api/products', auth, upload.single('banner'), asyncHandler(async (req, res) => {
365
+ const { name, category, description, features, banner_color, status } = req.body;
366
+ if (!name) return res.status(400).json({ error: 'Name required' });
367
+ const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
368
+ const doc = await insertDoc('products', {
369
+ name,
370
+ category: category || '',
371
+ description: description || '',
372
+ features: features || '',
373
+ banner_url,
374
+ banner_color: banner_color || '#0D2B7A',
375
+ status: status || 'active',
376
+ createdAt: new Date(),
377
+ });
378
+ res.json(doc);
379
+ }));
380
+
381
+ app.put('/api/products/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => {
382
+ const id = toObjectId(req.params.id);
383
+ if (!id) return res.status(404).json({ error: 'Not found' });
384
+ const existing = await findOneDoc('products', { _id: id });
385
+ if (!existing) return res.status(404).json({ error: 'Not found' });
386
+
387
+ const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url;
388
+ if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url);
389
+
390
+ await updateDoc('products', { _id: id }, {
391
+ name: req.body.name || existing.name,
392
+ category: req.body.category ?? existing.category,
393
+ description: req.body.description ?? existing.description,
394
+ features: req.body.features ?? existing.features,
395
+ banner_url,
396
+ banner_color: req.body.banner_color || existing.banner_color,
397
+ status: req.body.status || existing.status,
398
+ updatedAt: new Date(),
399
+ });
400
+
401
+ res.json({ success: true, banner_url });
402
+ }));
403
+
404
+ app.delete('/api/products/:id', auth, asyncHandler(async (req, res) => {
405
+ const id = toObjectId(req.params.id);
406
+ if (!id) return res.status(404).json({ error: 'Not found' });
407
+ const product = await findOneDoc('products', { _id: id });
408
+ if (!product) return res.status(404).json({ error: 'Not found' });
409
+ if (product.banner_url) deleteStoredFile(product.banner_url);
410
+ await removeDoc('products', { _id: id });
411
+ res.json({ success: true });
412
+ }));
413
+
414
+ app.get('/api/posts', asyncHandler(async (req, res) => {
415
+ const query = req.query.all ? {} : { status: 'published' };
416
+ const docs = await findDocs('posts', query, { createdAt: -1 });
417
+ res.json(docs);
418
+ }));
419
+
420
+ app.post('/api/posts', auth, upload.single('banner'), asyncHandler(async (req, res) => {
421
+ const { title, content, excerpt, status } = req.body;
422
+ if (!title) return res.status(400).json({ error: 'Title required' });
423
+ const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
424
+ const doc = await insertDoc('posts', {
425
+ title,
426
+ content: content || '',
427
+ excerpt: excerpt || '',
428
+ banner_url,
429
+ status: status || 'published',
430
+ createdAt: new Date(),
431
+ });
432
+ res.json(doc);
433
+ }));
434
+
435
+ app.put('/api/posts/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => {
436
+ const id = toObjectId(req.params.id);
437
+ if (!id) return res.status(404).json({ error: 'Not found' });
438
+ const existing = await findOneDoc('posts', { _id: id });
439
+ if (!existing) return res.status(404).json({ error: 'Not found' });
440
+
441
+ const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url;
442
+ if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url);
443
+
444
+ await updateDoc('posts', { _id: id }, {
445
+ title: req.body.title || existing.title,
446
+ content: req.body.content ?? existing.content,
447
+ excerpt: req.body.excerpt ?? existing.excerpt,
448
+ banner_url,
449
+ status: req.body.status || existing.status,
450
+ updatedAt: new Date(),
451
+ });
452
+
453
+ res.json({ success: true });
454
+ }));
455
+
456
+ app.delete('/api/posts/:id', auth, asyncHandler(async (req, res) => {
457
+ const id = toObjectId(req.params.id);
458
+ if (!id) return res.status(404).json({ error: 'Not found' });
459
+ const post = await findOneDoc('posts', { _id: id });
460
+ if (!post) return res.status(404).json({ error: 'Not found' });
461
+ if (post.banner_url) deleteStoredFile(post.banner_url);
462
+ await removeDoc('posts', { _id: id });
463
+ res.json({ success: true });
464
+ }));
465
+
466
+ app.post('/api/contact', asyncHandler(async (req, res) => {
467
+ const { name, email, phone, service_interest, budget, message } = req.body;
468
+ if (!name || !message) return res.status(400).json({ error: 'Name and message required' });
469
+ await insertDoc('contacts', {
470
+ name,
471
+ email: email || '',
472
+ phone: phone || '',
473
+ service_interest: service_interest || '',
474
+ budget: budget || '',
475
+ message,
476
+ is_read: false,
477
+ createdAt: new Date(),
478
+ });
479
+ res.json({ success: true, message: 'Your message has been received! We will contact you within 24 hours.' });
480
+ }));
481
+
482
+ app.get('/api/contacts', auth, asyncHandler(async (req, res) => {
483
+ const docs = await findDocs('contacts', {}, { createdAt: -1 });
484
+ res.json(docs);
485
+ }));
486
+
487
+ app.put('/api/contacts/:id/read', auth, asyncHandler(async (req, res) => {
488
+ const id = toObjectId(req.params.id);
489
+ if (!id) return res.status(404).json({ error: 'Not found' });
490
+ await updateDoc('contacts', { _id: id }, { is_read: true, updatedAt: new Date() });
491
+ res.json({ success: true });
492
+ }));
493
+
494
+ app.delete('/api/contacts/:id', auth, asyncHandler(async (req, res) => {
495
+ const id = toObjectId(req.params.id);
496
+ if (!id) return res.status(404).json({ error: 'Not found' });
497
+ await removeDoc('contacts', { _id: id });
498
+ res.json({ success: true });
499
+ }));
500
+
501
+ app.get('/api/admin/stats', auth, asyncHandler(async (req, res) => {
502
+ const [services, products, posts, contacts, unread] = await Promise.all([
503
+ countDocs('services', { status: 'active' }),
504
+ countDocs('products', { status: 'active' }),
505
+ countDocs('posts', { status: 'published' }),
506
+ countDocs('contacts'),
507
+ countDocs('contacts', { is_read: false }),
508
+ ]);
509
+
510
+ res.json({ services, products, posts, contacts, unread });
511
+ }));
512
+
513
+ app.get('/api/health', asyncHandler(async (req, res) => {
514
+ const adminCount = await countDocs('admins');
515
+ res.json({
516
+ status: 'OK',
517
+ message: 'Server is running!',
518
+ mongodb: 'Connected',
519
+ db: MONGODB_DB,
520
+ admins: adminCount,
521
+ });
522
+ }));
523
+
524
+ app.get('/admin', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'admin.html')));
525
+ app.get('*', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'index.html')));
526
+
527
+ app.use((err, req, res, next) => {
528
+ console.error(err);
529
+ if (err && err.message === 'Images only') {
530
+ return res.status(400).json({ error: 'Images only' });
531
+ }
532
+ res.status(500).json({ error: err?.message || 'Server error' });
533
  });
534
 
535
+ bootstrapDatabase()
536
+ .then(() => {
537
+ app.listen(PORT, () => {
538
+ console.log(`\n๐Ÿš€ HiTech Technologies (MongoDB) - http://localhost:${PORT}`);
539
+ console.log(`๐Ÿ”‘ Admin Panel - http://localhost:${PORT}/admin`);
540
+ console.log(`๐Ÿ“ฆ MongoDB DB - ${MONGODB_DB}`);
 
 
 
541
  });
542
+ })
543
+ .catch((error) => {
544
+ console.error('Failed to bootstrap application:', error);
545
+ process.exit(1);
546
+ });