|
1 | 1 | import Patient from '../models/patient.js'; |
2 | | -import User from '../models/User.js'; |
3 | | -import bcrypt from 'bcrypt'; |
4 | | -import * as emailService from '../services/email.service.js'; |
| 2 | +import { createPatientPortalAccount } from '../services/patientPortal.service.js'; |
5 | 3 |
|
6 | 4 | const createPatient = async (req, res, next) => { |
7 | 5 | try { |
8 | 6 | const { name, email, phno, paymentMode } = req.body; |
| 7 | + |
9 | 8 | console.log(`Creating patient: ${name}, Email: ${email}, PaymentMode: ${paymentMode}`); |
10 | 9 |
|
11 | | - // Create the patient record |
12 | 10 | const patient = new Patient(req.body); |
13 | 11 | await patient.save(); |
14 | 12 |
|
15 | | - // If online payment, create a patient portal account |
16 | | - if (paymentMode === 'online') { |
17 | | - console.log(`Online payment mode detected for ${email}. Processing portal creation...`); |
18 | | - const existingUser = await User.findOne({ email }); |
19 | | - if (!existingUser) { |
20 | | - // Use phone number as default password |
21 | | - const password = phno; // Plain text for the email |
22 | | - const hashedPassword = await bcrypt.hash(password, 10); |
23 | | - |
24 | | - await User.create({ |
25 | | - name, |
26 | | - email, |
27 | | - password: hashedPassword, |
28 | | - role: 'patient', |
29 | | - status: 'Active', |
30 | | - phno |
31 | | - }); |
32 | | - console.log(`Patient portal User record created for: ${email}`); |
33 | | - |
34 | | - // Send credentials email |
35 | | - try { |
36 | | - await emailService.sendPortalCredentials(email, name, password); |
37 | | - console.log(`Portal credentials email sent to: ${email}`); |
38 | | - } catch (mailErr) { |
39 | | - console.error(`Failed to send portal credentials email: ${mailErr.message}`); |
40 | | - } |
41 | | - } else { |
42 | | - console.log(`User account already exists for: ${email}. Skipping portal creation.`); |
43 | | - } |
44 | | - } else { |
45 | | - console.log(`Payment mode is '${paymentMode}'. Skipping portal creation.`); |
| 13 | + if (paymentMode === "online" && email) { |
| 14 | + await createPatientPortalAccount(email); |
46 | 15 | } |
47 | 16 |
|
48 | | - res.status(201).json(patient); |
| 17 | + res.status(201).json({ |
| 18 | + success: true, |
| 19 | + patient |
| 20 | + }); |
| 21 | + |
49 | 22 | } catch (err) { |
50 | 23 | console.error(`Error in createPatient: ${err.message}`); |
51 | 24 | next(err); |
|
0 commit comments