CentralBackend/repositories/user/company/CompanyUserRepository.js
2025-09-08 16:05:37 +02:00

197 lines
6.5 KiB
JavaScript

const CompanyUser = require('../../../models/CompanyUser');
const User = require('../../../models/User');
const { logger } = require('../../../middleware/logger');
class CompanyUserRepository {
constructor(unitOfWork) {
this.unitOfWork = unitOfWork;
}
async create({ companyEmail, password, companyName, companyPhone, contactPersonName, contactPersonPhone }) {
logger.info('CompanyUserRepository.create:start', { companyEmail, companyName });
try {
console.log('📊 CompanyUserRepository: Creating company user in database...');
const hashedPassword = await User.hashPassword(password);
const conn = this.unitOfWork.connection;
// 1. Insert into users table
const userQuery = `
INSERT INTO users (email, password, user_type, role)
VALUES (?, ?, 'company', 'user')
`;
const [userResult] = await conn.query(userQuery, [companyEmail, hashedPassword]);
const userId = userResult.insertId;
logger.info('CompanyUserRepository.create:user_created', { userId });
console.log('✅ User record created with ID:', userId);
// 2. Insert into company_profiles table
const profileQuery = `
INSERT INTO company_profiles (user_id, company_name, phone, contact_person_name, contact_person_phone)
VALUES (?, ?, ?, ?, ?)
`;
await conn.query(profileQuery, [
userId,
companyName,
companyPhone,
contactPersonName,
contactPersonPhone
]);
logger.info('CompanyUserRepository.create:profile_created', { userId, companyName });
console.log('✅ Company profile created');
logger.info('CompanyUserRepository.create:success', { userId });
return new CompanyUser(
userId,
companyEmail,
hashedPassword,
companyName,
companyPhone,
contactPersonName,
contactPersonPhone,
null, // registrationNumber is now null at registration
new Date()
);
} catch (error) {
logger.error('CompanyUserRepository.create:error', { error: error.message });
throw error;
}
}
async findByEmail(email) {
logger.info('CompanyUserRepository.findByEmail:start', { email });
try {
console.log('🔍 CompanyUserRepository: Querying database for company user...');
const conn = this.unitOfWork.connection;
const query = `
SELECT u.*, cp.company_name, cp.registration_number, cp.phone as company_phone,
cp.contact_person_name
FROM users u
LEFT JOIN company_profiles cp ON u.id = cp.user_id
WHERE u.email = ? AND u.user_type = 'company'
`;
const [rows] = await conn.query(query, [email]);
if (rows.length > 0) {
logger.info('CompanyUserRepository.findByEmail:found', { email, userId: rows[0].id });
const row = rows[0];
return new CompanyUser(
row.id,
row.email,
row.password,
row.company_name,
row.company_phone,
row.contact_person_name,
null,
row.registration_number,
row.created_at,
row.updated_at
);
}
logger.info('CompanyUserRepository.findByEmail:not_found', { email });
return null;
} catch (error) {
logger.error('CompanyUserRepository.findByEmail:error', { email, error: error.message });
throw error;
}
}
async findById(userId) {
logger.info('CompanyUserRepository.findById:start', { userId });
try {
console.log('🔍 CompanyUserRepository: Querying database for company user by ID...');
const conn = this.unitOfWork.connection;
const query = `
SELECT u.*, cp.company_name, cp.registration_number, cp.phone as company_phone,
cp.contact_person_name
FROM users u
LEFT JOIN company_profiles cp ON u.id = cp.user_id
WHERE u.id = ? AND u.user_type = 'company'
`;
const [rows] = await conn.query(query, [userId]);
if (rows.length > 0) {
logger.info('CompanyUserRepository.findById:found', { userId });
const row = rows[0];
return new CompanyUser(
row.id,
row.email,
row.password,
row.company_name,
row.company_phone,
row.contact_person_name,
null,
row.registration_number,
row.created_at,
row.updated_at
);
}
logger.info('CompanyUserRepository.findById:not_found', { userId });
return null;
} catch (error) {
logger.error('CompanyUserRepository.findById:error', { userId, error: error.message });
throw error;
}
}
async updateProfileAndMarkCompleted(userId, profileData) {
logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:start', { userId });
try {
console.log('Updating profile and marking registration as completed for user ID:', userId);
const conn = this.unitOfWork.connection;
const {
address,
zip_code,
city,
country, // Add country here
branch,
numberOfEmployees,
registrationNumber,
businessType,
iban,
accountHolderName
} = profileData;
await conn.query(
`UPDATE company_profiles SET
address = ?, zip_code = ?, city = ?, country = ?, branch = ?, number_of_employees = ?,
registration_number = ?, business_type = ?, account_holder_name = ?
WHERE user_id = ?`,
[
address,
zip_code,
city,
country, // Add country to parameter list
branch,
numberOfEmployees,
registrationNumber,
businessType,
accountHolderName,
userId
]
);
logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:profile_updated', { userId });
// Update IBAN in users table if provided
if (iban) {
await conn.query(
`UPDATE users SET iban = ? WHERE id = ?`,
[iban, userId]
);
logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:iban_updated', { userId });
}
await conn.query(
`UPDATE user_status SET profile_completed = 1, profile_completed_at = NOW() WHERE user_id = ?`,
[userId]
);
logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:profile_completed', { userId });
} catch (error) {
logger.error('CompanyUserRepository.updateProfileAndMarkCompleted:error', { userId, error: error.message });
throw error;
}
}
}
module.exports = CompanyUserRepository;