Changeset 79fff4f for server.js


Ignore:
Timestamp:
02/22/26 22:32:07 (7 months ago)
Author:
Klimentina Efremova <klimentina08642@…>
Branches:
finki-main, main
Children:
6fea37e, 81bc7da
Parents:
4dff800
Message:

Improved employee logging in and changing password

File:
1 edited

Legend:

Unmodified
Added
Removed
  • server.js

    r4dff800 r79fff4f  
    1010
    1111const port = process.env.PORT || 3000;
     12
    1213const sessions = new Map();
    1314const verificationCodes = new Map();
    … …  
    3132        }
    3233    };
     34
    3335    emailTransporter = nodemailer.createTransport(emailConfig);
     36
    3437    emailTransporter.verify(function(error, success) {
    3538        if (error) {
    … …  
    5255                const codeMatch = mailOptions.html.match(/\b\d{6}\b/);
    5356                const code = codeMatch ? codeMatch[0] : 'unknown';
     57
    5458                console.log('');
    5559                console.log('🎯 ===== VERIFICATION CODE =====');
    … …  
    6064                console.log('================================');
    6165                console.log('');
     66
    6267                resolve({ messageId: 'dev-' + Date.now() });
    6368            });
    … …  
    932937                    }
    933938                    rolesInserted++;
     939
    934940                    if (rolesInserted === roles.length) {
    935941                        console.log('✅ Roles inserted');
    936 
    937942                        // Create admin user with ID 000000
    938943                        createAdminUser();
    … …  
    11511156                // Check if store owner or employee
    11521157                const personalId = userId.replace('personal_', '');
     1158
    11531159                database.database.get(
    11541160                    'SELECT boss_id FROM boss WHERE boss_id = ?',
    … …  
    12011207            body += chunk.toString();
    12021208        });
    1203 
    12041209        req.on('end', () => {
    12051210            const { username, email, password, userType, firstName, lastName } = JSON.parse(body);
    … …  
    12661271                            console.log('✅ Verification email sent to:', email);
    12671272                            database.logAudit(null, 'REGISTER_ATTEMPT', 'user', null, `Registration attempt for ${email} as ${userType}`, ipAddress);
    1268 
    12691273                            res.writeHead(200, { 'Content-Type': 'application/json' });
    12701274                            res.end(JSON.stringify({
    … …  
    12941298            body += chunk.toString();
    12951299        });
    1296 
    12971300        req.on('end', () => {
    12981301            const formData = JSON.parse(body);
    … …  
    13251328
    13261329            const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
     1330
    13271331            if (!emailRegex.test(formData.ownerEmail)) {
    13281332                res.writeHead(400, { 'Content-Type': 'application/json' });
    … …  
    14061410                                // Next store number is max + 1, starting from 1 if no stores exist
    14071411                                let nextStoreNumber = 1;
     1412
    14081413                                if (result && result.max_store_num) {
    14091414                                    // Extract numeric part from store_id (format: XXX)
    … …  
    14611466                                        console.log('✅ Store registration email sent to:', formData.ownerEmail);
    14621467                                        database.logAudit(null, 'STORE_REGISTER_ATTEMPT', 'store', null, `Store registration attempt: ${formData.storeName}`, ipAddress);
    1463 
    14641468                                        res.writeHead(200, { 'Content-Type': 'application/json' });
    14651469                                        res.end(JSON.stringify({
    … …  
    14941498            body += chunk.toString();
    14951499        });
    1496 
    14971500        req.on('end', () => {
    14981501            const { firstName, lastName, email, password, address, city, postcode, country, isDefaultAddress } = JSON.parse(body);
    … …  
    15591562                        console.log('✅ Verification email sent to:', email);
    15601563                        database.logAudit(null, 'CLIENT_REGISTER_ATTEMPT', 'client', null, `Client registration attempt for ${email}`, ipAddress);
    1561 
    15621564                        res.writeHead(200, { 'Content-Type': 'application/json' });
    15631565                        res.end(JSON.stringify({
    … …  
    15861588            body += chunk.toString();
    15871589        });
    1588 
    15891590        req.on('end', () => {
    15901591            const { email } = JSON.parse(body);
    … …  
    17211722            body += chunk.toString();
    17221723        });
    1723 
    17241724        req.on('end', () => {
    17251725            const { email, code } = JSON.parse(body);
    … …  
    17931793                                        database.database.run('ROLLBACK');
    17941794                                        console.error('Error inserting personal:', err);
     1795
    17951796                                        if (err.code === '23505') {
    17961797                                            res.writeHead(400, { 'Content-Type': 'application/json' });
    … …  
    18411842                                                            }
    18421843
    1843                                                             database.database.run('COMMIT', (commitErr) => {
    1844                                                                 if (commitErr) {
    1845                                                                     console.error('Error committing transaction:', commitErr);
    1846                                                                     database.database.run('ROLLBACK');
    1847                                                                     res.writeHead(500, { 'Content-Type': 'application/json' });
    1848                                                                     res.end(JSON.stringify({ success: false, message: 'Error completing registration' }));
    1849                                                                     return;
     1844                                                            // Also create entry in users table for login with force_password_change = 1
     1845                                                            database.database.run(
     1846                                                                'INSERT INTO users (id, username, email, password, user_type, force_password_change) VALUES (?, ?, ?, ?, ?, ?)',
     1847                                                                [
     1848                                                                    tempStoreData.personalId,
     1849                                                                    `${tempStoreData.ownerFirstName} ${tempStoreData.ownerLastName}`,
     1850                                                                    tempStoreData.ownerEmail,
     1851                                                                    bcrypt.hashSync(tempStoreData.password, 10),
     1852                                                                    'store_owner',
     1853                                                                    1
     1854                                                                ],
     1855                                                                (err) => {
     1856                                                                    if (err) {
     1857                                                                        console.error('Error creating user entry for store owner:', err);
     1858                                                                    }
     1859
     1860                                                                    database.database.run('COMMIT', (commitErr) => {
     1861                                                                        if (commitErr) {
     1862                                                                            console.error('Error committing transaction:', commitErr);
     1863                                                                            database.database.run('ROLLBACK');
     1864                                                                            res.writeHead(500, { 'Content-Type': 'application/json' });
     1865                                                                            res.end(JSON.stringify({ success: false, message: 'Error completing registration' }));
     1866                                                                            return;
     1867                                                                        }
     1868
     1869                                                                        tempStoreRegistrations.delete(code);
     1870                                                                        verificationCodes.delete(email);
     1871
     1872                                                                        console.log(`✅ Store registration completed successfully:`);
     1873                                                                        console.log(`   Store ID: ${tempStoreData.storeId}`);
     1874                                                                        console.log(`   Store Name: ${tempStoreData.storeName}`);
     1875                                                                        console.log(`   Personal ID: ${tempStoreData.personalId}`);
     1876                                                                        console.log(`   Owner: ${tempStoreData.ownerFirstName} ${tempStoreData.ownerLastName}`);
     1877
     1878                                                                        database.logAudit(tempStoreData.personalId, 'STORE_REGISTER_SUCCESS', 'store', tempStoreData.storeId, `Store registered: ${tempStoreData.storeName}`, ipAddress);
     1879
     1880                                                                        res.writeHead(200, { 'Content-Type': 'application/json' });
     1881                                                                        res.end(JSON.stringify({
     1882                                                                            success: true,
     1883                                                                            message: 'Store registration successful! You can now login.',
     1884                                                                            storeId: tempStoreData.storeId,
     1885                                                                            storeIdPadded: tempStoreData.storeIdPadded,
     1886                                                                            storeName: tempStoreData.storeName,
     1887                                                                            personalId: tempStoreData.personalId,
     1888                                                                            userType: 'store_owner',
     1889                                                                            redirectTo: 'login.html'
     1890                                                                        }));
     1891                                                                    });
    18501892                                                                }
    1851 
    1852                                                                 tempStoreRegistrations.delete(code);
    1853                                                                 verificationCodes.delete(email);
    1854 
    1855                                                                 console.log(`✅ Store registration completed successfully:`);
    1856                                                                 console.log(`   Store ID: ${tempStoreData.storeId}`);
    1857                                                                 console.log(`   Store Name: ${tempStoreData.storeName}`);
    1858                                                                 console.log(`   Personal ID: ${tempStoreData.personalId}`);
    1859                                                                 console.log(`   Owner: ${tempStoreData.ownerFirstName} ${tempStoreData.ownerLastName}`);
    1860 
    1861                                                                 database.logAudit(tempStoreData.personalId, 'STORE_REGISTER_SUCCESS', 'store', tempStoreData.storeId, `Store registered: ${tempStoreData.storeName}`, ipAddress);
    1862 
    1863                                                                 res.writeHead(200, { 'Content-Type': 'application/json' });
    1864                                                                 res.end(JSON.stringify({
    1865                                                                     success: true,
    1866                                                                     message: 'Store registration successful! You can now login.',
    1867                                                                     storeId: tempStoreData.storeId,
    1868                                                                     storeIdPadded: tempStoreData.storeIdPadded,
    1869                                                                     storeName: tempStoreData.storeName,
    1870                                                                     personalId: tempStoreData.personalId,
    1871                                                                     userType: 'store_owner',
    1872                                                                     redirectTo: 'login.html'
    1873                                                                 }));
    1874                                                             });
     1893                                                            );
    18751894                                                        }
    18761895                                                    );
    … …  
    19521971            } else {
    19531972                const userId = 'user_' + Date.now().toString().slice(-8);
     1973
    19541974                database.createUser(userId, tempUserData.username, tempUserData.email, tempUserData.password, tempUserData.userType, (err, userId) => {
    19551975                    if (err) {
    … …  
    19822002            body += chunk.toString();
    19832003        });
    1984 
    19852004        req.on('end', () => {
    19862005            const { email, password } = JSON.parse(body);
    … …  
    20032022
    20042023                        const twoFACode = generateVerificationCode();
    2005 
    20062024                        verificationCodes.set(adminUser.email, {
    20072025                            code: twoFACode,
    … …  
    20482066                    }
    20492067                });
     2068
    20502069                return;
    20512070            }
    … …  
    20942113                            'Set-Cookie': `sessionId=${sessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
    20952114                        });
     2115
    20962116                        res.end(JSON.stringify({
    20972117                            success: true,
    … …  
    21552175
    21562176                                                const twoFACode = generateVerificationCode();
    2157 
    21582177                                                verificationCodes.set(personal.email, {
    21592178                                                    code: twoFACode,
    … …  
    22162235
    22172236                                                        const twoFACode = generateVerificationCode();
    2218 
    22192237                                                        verificationCodes.set(personal.email, {
    22202238                                                            code: twoFACode,
    … …  
    22782296
    22792297                                                                const twoFACode = generateVerificationCode();
    2280 
    22812298                                                                verificationCodes.set(userByUsername.email, {
    22822299                                                                    code: twoFACode,
    … …  
    23292346
    23302347                                                        const twoFACode = generateVerificationCode();
    2331 
    23322348                                                        verificationCodes.set(user.email, {
    23332349                                                            code: twoFACode,
    … …  
    23962412            body += chunk.toString();
    23972413        });
    2398 
    23992414        req.on('end', () => {
    24002415            const { email } = JSON.parse(body);
    … …  
    24192434
    24202435                            const newTwoFACode = generateVerificationCode();
    2421 
    24222436                            verificationCodes.set(userByUsername.email, {
    24232437                                code: newTwoFACode,
    … …  
    24562470
    24572471                    const newTwoFACode = generateVerificationCode();
    2458 
    24592472                    verificationCodes.set(user.email, {
    24602473                        code: newTwoFACode,
    … …  
    24972510            body += chunk.toString();
    24982511        });
    2499 
    25002512        req.on('end', () => {
    25012513            const { email, code } = JSON.parse(body);
    … …  
    25322544                verificationCodes.delete(email);
    25332545
     2546                // Determine redirect based on user type
     2547                let redirectTo = 'change-password.html?forced=true';
     2548                if (verificationData.userType === 'store_owner') {
     2549                    redirectTo = 'change-password.html?forced=true&redirect=store-owner.html';
     2550                } else if (verificationData.userType === 'store_employee') {
     2551                    redirectTo = 'change-password.html?forced=true&redirect=store-employee.html';
     2552                } else if (verificationData.userType === 'admin') {
     2553                    redirectTo = 'change-password.html?forced=true&redirect=admin.html';
     2554                } else if (verificationData.userType === 'client') {
     2555                    redirectTo = 'change-password.html?forced=true&redirect=client-dashboard.html';
     2556                }
     2557
    25342558                res.writeHead(200, {
    25352559                    'Content-Type': 'application/json',
    25362560                    'Set-Cookie': `sessionId=${tempSessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
    25372561                });
     2562
    25382563                res.end(JSON.stringify({
    25392564                    success: true,
    … …  
    25412566                    requiresPasswordChange: true,
    25422567                    userType: verificationData.userType,
    2543                     redirectTo: 'change-password.html?forced=true'
     2568                    redirectTo: redirectTo
    25442569                }));
    25452570
    … …  
    25902615                'Set-Cookie': `sessionId=${sessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
    25912616            });
     2617
    25922618            res.end(JSON.stringify({
    25932619                success: true,
    … …  
    26162642            'Set-Cookie': 'sessionId=; HttpOnly; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Strict'
    26172643        });
     2644
    26182645        res.end(JSON.stringify({ success: true, message: 'Successfully logged out' }));
    26192646    }
    … …  
    27362763                });
    27372764            }
    2738 
    27392765            else if (userIdStr.startsWith('personal_')) {
    27402766                const personalId = userIdStr.replace('personal_', '');
    … …  
    28852911                body += chunk.toString();
    28862912            });
    2887 
    28882913            req.on('end', () => {
    28892914                const categoryData = JSON.parse(body);
    … …  
    29682993                body += chunk.toString();
    29692994            });
    2970 
    29712995            req.on('end', () => {
    29722996                const orderData = JSON.parse(body);
    … …  
    30663090                body += chunk.toString();
    30673091            });
    3068 
    30693092            req.on('end', () => {
    30703093                const reviewData = JSON.parse(body);
    … …  
    30733096                if (userIdStr.startsWith('client_')) {
    30743097                    const clientId = parseInt(userIdStr.replace('client_', ''));
    3075 
    30763098                    reviewData.client_id = clientId;
    30773099
    … …  
    31003122                body += chunk.toString();
    31013123            });
    3102 
    31033124            req.on('end', () => {
    31043125                const requestData = JSON.parse(body);
    … …  
    31703191                body += chunk.toString();
    31713192            });
    3172 
    31733193            req.on('end', () => {
    31743194                const refundData = JSON.parse(body);
    … …  
    32403260                body += chunk.toString();
    32413261            });
    3242 
    32433262            req.on('end', () => {
    32443263                const productData = JSON.parse(body);
    … …  
    33333352                body += chunk.toString();
    33343353            });
    3335 
    33363354            req.on('end', () => {
    33373355                const productData = JSON.parse(body);
    … …  
    34273445    }
    34283446
     3447    // Updated /api/force-change-password endpoint with redirect handling
    34293448    else if (pathname === '/api/force-change-password' && req.method === 'POST') {
    34303449        const cookies = parseCookies(req);
    … …  
    34393458
    34403459        let body = '';
    3441 
    34423460        req.on('data', chunk => {
    34433461            body += chunk.toString();
    34443462        });
    3445 
    34463463        req.on('end', () => {
    34473464            try {
    3448                 const { newPassword, confirmPassword } = JSON.parse(body);
     3465                const { newPassword, confirmPassword, redirectTo } = JSON.parse(body);
    34493466
    34503467                if (!newPassword || !confirmPassword) {
    … …  
    35083525                                // Create new permanent session
    35093526                                const newSessionId = generateSessionId();
    3510                                 sessions.set(newSessionId, String(userId));
    3511 
    3512                                 // Determine redirect based on user type
    3513                                 let redirectTo = 'dashboard.html';
    3514 
    3515                                 if (user.username === 'admin' || user.user_type === 'admin') {
    3516                                     redirectTo = 'admin.html';
    3517                                 } else if (user.user_type === 'store_owner') {
    3518                                     redirectTo = 'store-owner.html';
    3519                                 } else if (user.user_type === 'store_employee') {
    3520                                     redirectTo = 'store-employee.html';
    3521                                 } else if (user.user_type === 'client') {
    3522                                     redirectTo = 'client-dashboard.html';
     3527
     3528                                // Determine how to store the user ID based on user type
     3529                                let sessionUserId = String(userId);
     3530
     3531                                if (user.user_type === 'store_owner' || user.user_type === 'store_employee') {
     3532                                    sessionUserId = `personal_${userId}`;
    35233533                                }
    35243534
    3525                                 console.log(`Password changed successfully for user ${userId}, redirecting to ${redirectTo}`);
     3535                                sessions.set(newSessionId, sessionUserId);
     3536
     3537                                // Determine redirect based on user type or provided redirectTo
     3538                                let finalRedirect = redirectTo || 'dashboard.html';
     3539
     3540                                if (!redirectTo) {
     3541                                    if (user.username === 'admin' || user.user_type === 'admin') {
     3542                                        finalRedirect = 'admin.html';
     3543                                    } else if (user.user_type === 'store_owner') {
     3544                                        finalRedirect = 'store-owner.html';
     3545                                    } else if (user.user_type === 'store_employee') {
     3546                                        finalRedirect = 'store-employee.html';
     3547                                    } else if (user.user_type === 'client') {
     3548                                        finalRedirect = 'client-dashboard.html';
     3549                                    }
     3550                                }
     3551
     3552                                console.log(`Password changed successfully for user ${userId}, redirecting to ${finalRedirect}`);
    35263553
    35273554                                database.logAudit(userId, 'FORCED_PASSWORD_CHANGE', 'auth', userId.toString(),
    … …  
    35313558                                res.writeHead(200, {
    35323559                                    'Content-Type': 'application/json',
    3533                                     'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
     3560                                    'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=86400; SameSite=Strict` // Extended to 24 hours
    35343561                                });
     3562
    35353563                                res.end(JSON.stringify({
    35363564                                    success: true,
    35373565                                    message: 'Password changed successfully.',
    3538                                     redirectTo: redirectTo,
     3566                                    redirectTo: finalRedirect,
    35393567                                    userType: user.user_type || 'user'
    35403568                                }));
    … …  
    35843612                                            (err, boss) => {
    35853613                                                let userType = 'store_employee';
    3586                                                 let redirectTo = 'store-employee.html';
     3614                                                let finalRedirect = redirectTo || 'store-employee.html';
    35873615
    35883616                                                if (boss) {
    35893617                                                    userType = 'store_owner';
    3590                                                     redirectTo = 'store-owner.html';
     3618                                                    finalRedirect = redirectTo || 'store-owner.html';
    35913619                                                }
    35923620
    … …  
    35943622                                                tempAdminSessions.delete(sessionId);
    35953623
    3596                                                 // Create new permanent session
     3624                                                // Create new permanent session with personal_ prefix
    35973625                                                const newSessionId = generateSessionId();
    35983626                                                sessions.set(newSessionId, `personal_${userId}`);
    35993627
    3600                                                 console.log(`Password changed successfully for ${userType} ${userId}, redirecting to ${redirectTo}`);
     3628                                                console.log(`Password changed successfully for ${userType} ${userId}, redirecting to ${finalRedirect}`);
    36013629
    36023630                                                database.logAudit(userId, 'FORCED_PASSWORD_CHANGE', 'auth', userId.toString(),
    36033631                                                    `${userType} forced password change completed`, ipAddress);
    36043632
    3605                                                 // Set the cookie with proper options
     3633                                                // Set the cookie with proper options - extended to 24 hours
    36063634                                                res.writeHead(200, {
    36073635                                                    'Content-Type': 'application/json',
    3608                                                     'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
     3636                                                    'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=86400; SameSite=Strict`
    36093637                                                });
     3638
    36103639                                                res.end(JSON.stringify({
    36113640                                                    success: true,
    36123641                                                    message: 'Password changed successfully.',
    3613                                                     redirectTo: redirectTo,
     3642                                                    redirectTo: finalRedirect,
    36143643                                                    userType: userType
    36153644                                                }));
    … …  
    36683697                        body += chunk.toString();
    36693698                    });
    3670 
    36713699                    req.on('end', () => {
    36723700                        const { firstName, lastName, ssn, email, password, storeId, dateOfHire } = JSON.parse(body);
    … …  
    37753803                                                    database.database.run('ROLLBACK');
    37763804                                                    console.error('Error inserting personal:', err);
     3805
    37773806                                                    if (err.code === '23505') {
    37783807                                                        res.writeHead(400, { 'Content-Type': 'application/json' });
    3779                                                         res.end(JSON.stringify({ success: false, message: 'This personal ID is already taken. Please try again.' }));
     3808                                                        res.end(JSON.stringify({
     3809                                                            success: false,
     3810                                                            message: 'This personal ID is already taken. Please try again.'
     3811                                                        }));
    37803812                                                    } else {
    37813813                                                        res.writeHead(400, { 'Content-Type': 'application/json' });
    … …  
    38173849                                                                        }
    38183850
    3819                                                                         database.database.run('COMMIT', (err) => {
    3820                                                                             if (err) {
    3821                                                                                 database.database.run('ROLLBACK');
    3822                                                                                 console.error('Error committing transaction:', err);
    3823                                                                                 res.writeHead(500, { 'Content-Type': 'application/json' });
    3824                                                                                 res.end(JSON.stringify({ success: false, message: 'Error completing registration' }));
    3825                                                                                 return;
     3851                                                                        // Also create entry in users table for login with force_password_change = 1
     3852                                                                        database.database.run(
     3853                                                                            'INSERT INTO users (id, username, email, password, user_type, force_password_change) VALUES (?, ?, ?, ?, ?, ?)',
     3854                                                                            [
     3855                                                                                newPersonalId,
     3856                                                                                `${firstName} ${lastName}`,
     3857                                                                                email,
     3858                                                                                bcrypt.hashSync(password, 10),
     3859                                                                                'store_employee',
     3860                                                                                1
     3861                                                                            ],
     3862                                                                            (err) => {
     3863                                                                                if (err) {
     3864                                                                                    console.error('Error creating user entry for employee:', err);
     3865                                                                                }
     3866
     3867                                                                                database.database.run('COMMIT', (err) => {
     3868                                                                                    if (err) {
     3869                                                                                        database.database.run('ROLLBACK');
     3870                                                                                        console.error('Error committing transaction:', err);
     3871                                                                                        res.writeHead(500, { 'Content-Type': 'application/json' });
     3872                                                                                        res.end(JSON.stringify({ success: false, message: 'Error completing registration' }));
     3873                                                                                        return;
     3874                                                                                    }
     3875
     3876                                                                                    database.logAudit(personalId, 'EMPLOYEE_REGISTERED', 'employee', newPersonalId, `Employee registered: ${firstName} ${lastName}`, ipAddress);
     3877
     3878                                                                                    res.writeHead(200, { 'Content-Type': 'application/json' });
     3879                                                                                    res.end(JSON.stringify({
     3880                                                                                        success: true,
     3881                                                                                        message: 'Employee registered successfully!',
     3882                                                                                        employeeId: newPersonalId,
     3883                                                                                        name: `${firstName} ${lastName}`
     3884                                                                                    }));
     3885                                                                                });
    38263886                                                                            }
    3827 
    3828                                                                             database.logAudit(personalId, 'EMPLOYEE_REGISTERED', 'employee', newPersonalId, `Employee registered: ${firstName} ${lastName}`, ipAddress);
    3829 
    3830                                                                             res.writeHead(200, { 'Content-Type': 'application/json' });
    3831                                                                             res.end(JSON.stringify({
    3832                                                                                 success: true,
    3833                                                                                 message: 'Employee registered successfully!',
    3834                                                                                 employeeId: newPersonalId,
    3835                                                                                 name: `${firstName} ${lastName}`
    3836                                                                             }));
    3837                                                                         });
     3887                                                                        );
    38383888                                                                    }
    38393889                                                                );
    … …  
    38873937                        body += chunk.toString();
    38883938                    });
    3889 
    38903939                    req.on('end', () => {
    38913940                        const { employeeId, storeId } = JSON.parse(body);
    … …  
    39754024                                                                                    }
    39764025
    3977                                                                                     database.database.run('COMMIT', (commitErr) => {
    3978                                                                                         if (commitErr) {
    3979                                                                                             database.database.run('ROLLBACK');
    3980                                                                                             console.error('Error committing transaction:', commitErr);
    3981                                                                                             res.writeHead(500, { 'Content-Type': 'application/json' });
    3982                                                                                             res.end(JSON.stringify({ success: false, message: 'Error completing deletion' }));
    3983                                                                                             return;
     4026                                                                                    // Also delete from users table
     4027                                                                                    database.database.run(
     4028                                                                                        'DELETE FROM users WHERE id = ?',
     4029                                                                                        [employeeId],
     4030                                                                                        (err) => {
     4031                                                                                            if (err) {
     4032                                                                                                console.error('Error deleting from users:', err);
     4033                                                                                            }
     4034
     4035                                                                                            database.database.run('COMMIT', (commitErr) => {
     4036                                                                                                if (commitErr) {
     4037                                                                                                    database.database.run('ROLLBACK');
     4038                                                                                                    console.error('Error committing transaction:', commitErr);
     4039                                                                                                    res.writeHead(500, { 'Content-Type': 'application/json' });
     4040                                                                                                    res.end(JSON.stringify({ success: false, message: 'Error completing deletion' }));
     4041                                                                                                    return;
     4042                                                                                                }
     4043
     4044                                                                                                database.logAudit(personalId, 'EMPLOYEE_DELETED', 'employee', employeeId, `Employee deleted from store ${storeId}`, ipAddress);
     4045
     4046                                                                                                res.writeHead(200, { 'Content-Type': 'application/json' });
     4047                                                                                                res.end(JSON.stringify({
     4048                                                                                                    success: true,
     4049                                                                                                    message: 'Employee deleted successfully'
     4050                                                                                                }));
     4051                                                                                            });
    39844052                                                                                        }
    3985 
    3986                                                                                         database.logAudit(personalId, 'EMPLOYEE_DELETED', 'employee', employeeId, `Employee deleted from store ${storeId}`, ipAddress);
    3987 
    3988                                                                                         res.writeHead(200, { 'Content-Type': 'application/json' });
    3989                                                                                         res.end(JSON.stringify({
    3990                                                                                             success: true,
    3991                                                                                             message: 'Employee deleted successfully'
    3992                                                                                         }));
    3993                                                                                     });
     4053                                                                                    );
    39944054                                                                                }
    39954055                                                                            );
    … …  
    40464106                        body += chunk.toString();
    40474107                    });
    4048 
    40494108                    req.on('end', () => {
    40504109                        const { employeeId, storeId, status } = JSON.parse(body);
    … …  
    41534212                        body += chunk.toString();
    41544213                    });
    4155 
    41564214                    req.on('end', () => {
    41574215                        const { employeeId, storeId, firstName, lastName, email } = JSON.parse(body);
    … …  
    42234281                                                    res.end(JSON.stringify({ success: false, message: 'Error updating employee information' }));
    42244282                                                    return;
     4283                                                }
     4284
     4285                                                // Also update in users table if email was changed
     4286                                                if (email) {
     4287                                                    database.database.run(
     4288                                                        'UPDATE users SET email = ? WHERE id = ?',
     4289                                                        [email, employeeId],
     4290                                                        (err) => {
     4291                                                            if (err) {
     4292                                                                console.error('Error updating user email:', err);
     4293                                                            }
     4294                                                        }
     4295                                                    );
     4296                                                }
     4297
     4298                                                if (firstName || lastName) {
     4299                                                    database.database.get(
     4300                                                        'SELECT first_name, last_name FROM personal WHERE id = ?',
     4301                                                        [employeeId],
     4302                                                        (err, personal) => {
     4303                                                            if (!err && personal) {
     4304                                                                const newUsername = `${personal.first_name} ${personal.last_name}`;
     4305                                                                database.database.run(
     4306                                                                    'UPDATE users SET username = ? WHERE id = ?',
     4307                                                                    [newUsername, employeeId],
     4308                                                                    (err) => {
     4309                                                                        if (err) {
     4310                                                                            console.error('Error updating user username:', err);
     4311                                                                        }
     4312                                                                    }
     4313                                                                );
     4314                                                            }
     4315                                                        }
     4316                                                    );
    42254317                                                }
    42264318
    … …  
    45824674                body += chunk.toString();
    45834675            });
    4584 
    45854676            req.on('end', () => {
    45864677                const { productCode, storeId } = JSON.parse(body);
    … …  
    46524743                body += chunk.toString();
    46534744            });
    4654 
    46554745            req.on('end', () => {
    46564746                const { storeId, period, startDate, endDate, type } = JSON.parse(body);
Note: See TracChangeset for help on using the changeset viewer.