Skip to content

Instantly share code, notes, and snippets.

@chrisoverstreet
Created July 22, 2020 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisoverstreet/a2558862b40d0f5193259f3049e861c5 to your computer and use it in GitHub Desktop.
Save chrisoverstreet/a2558862b40d0f5193259f3049e861c5 to your computer and use it in GitHub Desktop.
export const patchEstimateHandler = async (req, res) => {
const {
body: { canStartToday },
params: { estimateId },
userId
} = req;
const originalEstimate = await getEstimateById(estimateId);
if (!originalEstimate) {
return responseService.createErrorResponse(res, createError.NotFound());
}
const updates = {};
if (typeof canStartToday === 'boolean') {
updates.canStartToday = canStartToday;
}
const trx = await BaseModel.getTransactionObject();
const latestEstimateRevision = await JobEstimateRevision.query().findById(
originalEstimate.latestEstimateRevisionId
);
if (
latestEstimateRevision.revisedById !== userId ||
latestEstimateRevision.status !== REVISION_STATUS.draft
) {
const { providerId } = await getJobByEstimateId(estimateId);
const status = providerId === userId ? REVISION_STATUS.published : REVISION_STATUS.suggested;
const jobEstimateRevision = await JobEstimateRevision.query(trx).insertAndFetch({
changedFromId: latestEstimateRevision.id,
status,
revisedById: userId,
expiration: latestEstimateRevision.expiration,
canStartToday: latestEstimateRevision.canStartToday,
...updates
});
await originalEstimate.$query(trx).patch({
latestEstimateRevisionId: jobEstimateRevision.id
});
} else {
await latestEstimateRevision.$query(trx).patch(updates);
}
let estimate;
try {
estimate = await getEstimate(estimateId);
} catch (e) {
return e.status
? responseService.createErrorResponse(res, e)
: responseService.createErrorResponse(res, createError.BadRequest(e.message));
}
return responseService.createSuccessResponse(res, 200, estimate);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment