Snippets

John NotesRestController

Created by John De la cruz
/**
 * Created by johndelacruz on 5/10/23.
 */

public class NotesRestController {

    private final ResponseListener responseListener;
    private final JobMessageRestService jobMessageRestService;
    List<Job_Message__c> jobMessages = new List<Job_Message__c>();

    public class NotesException extends Exception {
    }

    public NotesRestController(ResponseListener responseListener, JobMessageRestService jobMessageRestService) {
        this.responseListener = responseListener;
        this.jobMessageRestService = jobMessageRestService;
    }

    public void getNotes(Map<String, String> params) {
        final String userId = params.get('userId');
        final String jobId = params.get('jobId');

        List<Labor__c> labors = new List<Labor__c>();
        List<NoteViewModel> noteList = new List<NoteViewModel>();
        List<CrewMemberViewModel> crewMemberViewModels = new List<CrewMemberViewModel>();


        try {
            LaborRestService laborRestService = new LaborRestService();


            if (jobId != null) {

            labors = laborRestService.getLaborForJob(jobId, LaborProjections.CREW_MEMBERS_LABOR_FIELDS);

            crewMemberViewModels.addAll(getCrewMemberList(labors,jobId,userId));

            } else {
                throw new NotesException('jobId is null, please provide a valid jobId.');
            }

        } catch (Exception error) {
            responseListener.onResult(new ErrorResponse.Builder(ResponseCode.BAD_REQUEST)
                    .message(error.getMessage())
                    .error(error)
                    .build());
            return;

        }

        try {
            for (Job_Message__c currentNote : jobMessages) {

                NoteViewModel note = new NoteViewModel(currentNote);

                note.setRecipient(
                        currentNote.Recipient__r.Account.ImageUrl_For_Employee_App__c,
                        currentNote.Recipient__r.Account.Name,
                        currentNote.Recipient__c
                );

                note.setCreatedBy(currentNote.CreatedBy.Account.ImageUrl_For_Employee_App__c,
                        currentNote.CreatedBy.Account.Name,
                        currentNote.CreatedById);

                noteList.add(note);

            }


            responseListener.onResult(new DataResponse(ResponseCode.OK,
                    new Map<String, List<Object>>{
                            'notes' => noteList,
                            'contacts' => crewMemberViewModels
                    })
            );

        } catch (Exception error) {
            responseListener.onResult(new ErrorResponse.Builder(ResponseCode.SERVER_ERROR)
                    .message(error.getMessage())
                    .error(error)
                    .build());

        }


    }

    private List<CrewMemberViewModel> getCrewMemberList(List<Labor__c> labors,String jobId, String userId) {
        JobController jobController = new JobController();
        Map<String, CrewMemberViewModel> crewMemberMap = new Map<String, CrewMemberViewModel>();

        if (labors.isEmpty()) {
            throw new NotesException('No labors found with jobId, please provide a valid jobId.');
        }
        String coordinatorId = labors.get(0).Job__r.Crew_Coordinator__c;
        String coordinatorName = labors.get(0).Job__r.Crew_Coordinator_Name__c;


        crewMemberMap.put(coordinatorId,
                new CrewMemberViewModel(
                        coordinatorId,
                        coordinatorName));


        Set<String> combinedProjections = new Set<String>();
        combinedProjections.addAll(JobMessageProjections.NOTES_PROJECTION);
        combinedProjections.addAll(JobMessageProjections.EMPLOYEE_NOTES_PROJECTION);

        Job__c job = jobController.getJob(jobId, new Set<String>{
                'Crew_Coordinator__c'
        });

        if (job != null && job.Crew_Coordinator__c == userId) {
            jobMessages = jobMessageRestService.getNotesForCoordinator(jobId, combinedProjections);

            for (Labor__c currentLabor : labors) {

                if (crewMemberMap.get(currentLabor.Employee_Name__c) == null && currentLabor.Employee_Name__c != 'Pending') {
                    crewMemberMap.put(currentLabor.Employee_Name__c, new CrewMemberViewModel(currentLabor));
                }
            }

        } else {
            jobMessages = jobMessageRestService.getNotesByUserId(jobId, userId, combinedProjections);
        }

        return crewMemberMap.values();
    }

    public void postNotes(Blob body) {


        NoteViewModel noteViewModel = (NoteViewModel) JSON.deserialize(body.toString(), NoteViewModel.class);
        User user;

        try {

            if (noteViewModel.recipientId == null) {
                throw new NotesException('recipientId is null, please provide recipientId.');

            }

            if (noteViewModel.jobId == null) {
                throw new NotesException('jobId is null, please provide a valid jobId.');

            }

            if (noteViewModel.body == null) {
                throw new NotesException('body is null, please provide body.');

            }

            if (noteViewModel.subject == null) {
                throw new NotesException('subject is null, please provide subject.');

            }


        } catch (Exception e) {
            responseListener.onResult(new ErrorResponse.Builder(ResponseCode.BAD_REQUEST)
                    .message(e.getMessage())
                    .error(e)
                    .build());

            return;
        }


        try {
            Account account = [SELECT Id FROM Account WHERE Id = :noteViewModel.recipientId][0];
            Contact contact = [SELECT Id FROM Contact WHERE AccountId = :account.Id][0];
            user = [SELECT Id FROM User WHERE ContactId = :contact.Id][0];
        } catch (Exception e) {
            user = [SELECT Id FROM User WHERE Id = :noteViewModel.recipientId][0];
        }

        try {
            Job_Message__c note = new Job_Message__c();
            note.Job__c = noteViewModel.jobId;
            note.Body__c = noteViewModel.body;
            note.Recipient__c = user.Id;
            note.Subject__c = noteViewModel.subject;
            note.RecordTypeId = Schema.SObjectType.Job_Message__c.getRecordTypeInfosByName().get('Note').getRecordTypeId();
            insert note;

            responseListener.onResult(new DataResponse(ResponseCode.CREATED, 'Successfully created a note!'));

        } catch (Exception e) {
            responseListener.onResult(new ErrorResponse.Builder(ResponseCode.SERVER_ERROR)
                    .message('Something went wrong, Please try again later')
                    .error(e)
                    .build());
        }
    }

}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.