const { query, one, limitClause } = require('../lib/db') /** * Create a scan report * @param {Object} report * @param {number} report.user_id * @param {string|null} report.device_id * @param {string|null} report.scanned_at - MySQL datetime string * @param {string} report.regions - JSON string (array) * @param {string} report.overall - JSON string (array) * @param {number} report.recommend_mask * @param {string} report.recommend_plan - JSON string (array) * @param {string} report.raw_pd - JSON string * @param {number} report.calibrated - 0/1 * @returns {Promise} query result (has insertId) */ async function create(report) { return query( `INSERT INTO scan_reports (user_id, device_id, scanned_at, regions, overall, recommend_mask, recommend_plan, raw_pd, calibrated) VALUES (:user_id, :device_id, :scanned_at, :regions, :overall, :recommend_mask, :recommend_plan, :raw_pd, :calibrated)`, report ) } /** * Find a scan report by id * @param {number} id * @returns {Promise} */ async function findById(id) { return one('SELECT * FROM scan_reports WHERE id = :id', { id }) } /** * Find the latest scan report for a user, optionally filtered by device * @param {number} userId * @param {string} [deviceId] * @returns {Promise} */ async function findLatestByUser(userId, deviceId) { if (deviceId) { return one( 'SELECT * FROM scan_reports WHERE user_id = :user_id AND device_id = :device_id ORDER BY created_at DESC, id DESC LIMIT 1', { user_id: userId, device_id: deviceId } ) } return one( 'SELECT * FROM scan_reports WHERE user_id = :user_id ORDER BY created_at DESC, id DESC LIMIT 1', { user_id: userId } ) } /** * List scan reports for a user with pagination * @param {number} userId * @param {Object} opts * @param {number} opts.pageSize * @param {number} opts.offset * @returns {Promise<{records: Array, total: number}>} */ async function listByUser(userId, { pageSize, offset }) { const total = await query( 'SELECT COUNT(*) AS total FROM scan_reports WHERE user_id = :user_id', { user_id: userId } ) const records = await query( 'SELECT * FROM scan_reports WHERE user_id = :user_id ORDER BY created_at DESC, id DESC' + limitClause(pageSize, offset), { user_id: userId } ) return { records, total: total[0].total } } module.exports = { create, findById, findLatestByUser, listByUser }