import { transaction } from 'objection'; import { JobInstance, JobTpl, ProjectStage } from 'iworks-db-model'; import { updateProjectStage } from '../projectStage/projectStageRepository'; import { evenRound, jobPriceCalcStrategies, } from '../helpers/price'; import { IJobInstanceSelector, IJobInstanceAdd } from '../model/jobInstance'; export async function deleteJobInstance(jobInstanceSelector: IJobInstanceSelector) : Promise { const numDeleted = await JobInstance .query() .delete() .where('id', jobInstanceSelector.id); return numDeleted > 0; } export async function addJobInstance(jobInstanceData: IJobInstanceAdd) : Promise { const [jobTpl] = await JobTpl .query() .where('id', jobInstanceData.jobTplId) .eager('jobTplMaterials(onlyDefault).material', { onlyDefault: (builder: any) => { builder.where('default', true); }, }); if (!jobTpl) { throw new Error(`Can't find job template with id ${jobInstanceData.jobTplId}`); } const [projectStage] = await ProjectStage.query().where('id', jobInstanceData.projectStageId); if (!projectStage) { throw new Error(`Can't find project stage with id ${jobInstanceData.projectStageId}`); } const jobInstanceInsertData = { price: evenRound(jobPriceCalcStrategies.has(jobTpl.jobPriceType) ? jobPriceCalcStrategies.get(jobTpl.jobPriceType)(jobInstanceData.vol, jobTpl) : 0.0, 2), jobTplId: jobTpl.id, projectStageId: projectStage.id, vol: jobInstanceData.vol, providerLinked: jobInstanceData.providerLinked || true, jobInstanceMaterials: jobTpl.jobTplMaterials.map((jobTplMaterial: any) => ({ consumption: jobTplMaterial.consumption, price: jobTplMaterial.material.price, materialId: jobTplMaterial.material.id, })), }; const { id } = await JobInstance .query() .insertGraph(jobInstanceInsertData); const jobInstances = await JobInstance .query() .where('project_stage_id', projectStage.id); await updateProjectStage({ jobInstances, id: jobInstanceData.projectStageId }); return { id }; }