account.controller.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import _ from "lodash";
  2. import AccountSerializer from "./account.serializer.js";
  3. import AccountService from "./account.service.js";
  4. import AccountValidator from "./account.validator.js";
  5. class Controller {
  6. async byId(req, res) {
  7. const account = await AccountService.byId(req.params.id);
  8. if (account) res.json(AccountSerializer.show(account));
  9. else res.status(404).end();
  10. }
  11. async update(req, res) {
  12. const accountData = _.pick(req.body, [
  13. "companyName",
  14. "companyVat",
  15. "companyBillingAddress",
  16. "companySdi",
  17. "companyPhone",
  18. "companyEmail",
  19. "companyPec",
  20. "companyCountry",
  21. "planType", // Added planType to allowed fields
  22. ]);
  23. const accountErrors = await AccountValidator.onUpdate(accountData);
  24. if (accountErrors) {
  25. return res.status(422).json({
  26. success: false,
  27. errors: accountErrors.details,
  28. });
  29. }
  30. const result = await AccountService.update(req.params.id, accountData);
  31. if (result) {
  32. return res.json(AccountSerializer.show(result));
  33. } else {
  34. return res.status(422).json({
  35. success: false,
  36. message: "Failed to update account.",
  37. });
  38. }
  39. }
  40. // New controller method to set trial period
  41. async setTrialPeriod(req, res) {
  42. try {
  43. const { id: accountId } = req.params;
  44. const { trialDays } = req.body;
  45. console.log(`Received request to set trial period for account ${accountId} to ${trialDays} days`);
  46. // Validate input
  47. if (!trialDays || isNaN(parseInt(trialDays)) || parseInt(trialDays) < 0) {
  48. console.log('Validation failed: Invalid trial days value');
  49. return res.status(422).json({
  50. success: false,
  51. message: "Trial days must be a valid positive number"
  52. });
  53. }
  54. const trialDaysInt = parseInt(trialDays);
  55. console.log(`Parsed trial days: ${trialDaysInt}`);
  56. // Call service method to update the trial period
  57. const result = await AccountService.setTrialPeriod(accountId, trialDaysInt);
  58. if (result) {
  59. console.log('Trial period set successfully');
  60. return res.json(AccountSerializer.show(result));
  61. } else {
  62. console.log('Failed to update trial period');
  63. return res.status(422).json({
  64. success: false,
  65. message: "Failed to update trial period."
  66. });
  67. }
  68. } catch (error) {
  69. console.error('Error in setTrialPeriod controller:', error);
  70. return res.status(500).json({
  71. success: false,
  72. message: "Server error while updating trial period",
  73. error: error.message
  74. });
  75. }
  76. }
  77. }
  78. export default new Controller();