// @ts-check
/**
* @import {ExpressRequestAuthorized, ExpressResponse} from '../../types.js'
*/
import {query,UUID2hex} from '@commtool/sql-query'
import _ from 'lodash'
import { isObjectAdmin } from '../../utils/authChecks.js'
import { addUpdateList } from '../../server.ws.js'
import { errorLoggerUpdate } from '../../utils/requestLogger.js'
function mergeCustomizer(objValue, srcValue) {
// do not merge arrays
if (_.isArray(objValue)) {
return srcValue;
}
}
/**
* Updates an existing job in the database
*
* @async
* @function updateJob
* @param {Object} req - Express request object
* @param {Object} req.params - Request parameters
* @param {string} req.params.UID - Unique identifier of the job to update
* @param {Object} req.body - Data to update the job with
* @param {Object} res - Express response object
* @returns {Promise<void>} - Sends JSON response with operation success status
* @throws {Error} - Logs error through errorLoggerUpdate if operation fails
*
* @description
* Updates a job after validating user permissions.
* The function performs these steps:
* 1. Converts the job UID parameter to hexadecimal format
* 2. Checks if the user has admin permissions for the job
* 3. Validates the job UID exists
* 4. Retrieves the existing job data from the database
* 5. Merges the existing job data with the provided updated data
* 6. Updates the job record in the database
* 7. Adds the job to an update list for processing
*/
export const updateJob =async (req,res)=>
{
try {
// this can be used for mutating data of a job
const UIDjob=UUID2hex(req.params.UID)
if(!isObjectAdmin(req,req.params.UID))
{
res.json({success:false,message:'user not authorized for this job'})
return
}
// const asOf=timestamp ? `FOR SYSTEM_TIME AS OF FROM_UNIXTIME(${timestamp})` : ''
if(!UIDjob)
{
res.status(300).json({success: false, message:'UID can not be null or undefined'})
return
}
const jobs = await query(`SELECT ObjectBase.Data,ObjectBase.UIDBelongsTo FROM ObjectBase
WHERE ObjectBase.UID=? AND ObjectBase.Type ='job'`,
[UIDjob],
{
log:false,
cast:['json']
})
if(jobs.length===0)
{
res.json({success:false,message:'job with this UID not found'})
return
}
const job=jobs[0]
const jobData=job.Data
const origData=_.cloneDeep(jobData)
const Data=_.mergeWith(_.cloneDeep(jobData),req.body, mergeCustomizer)
// Only update if data actually changed
if (!_.isEqual(origData, Data)) {
query(`UPDATE ObjectBase SET Data=? WHERE UID=?`,[JSON.stringify(Data),UIDjob])
addUpdateList(job.UIDBelongsTo)
}
res.json({success:true})
}
catch(e)
{
errorLoggerUpdate(e)
}
}