Untitled

mail@pastecode.io avatar
unknown
javascript
7 months ago
2.4 kB
3
Indexable
Never
exports.createInspection = (req, res) => {
	const number_plate = req.params.number_plate;
	let queryString = utils.generateQueryString(req.query);
	connection.query(
		`SELECT *
			FROM inspections i
			INNER JOIN cars c ON c.car_id = i.car_id WHERE i.car_id = (SELECT car_id FROM cars WHERE number_plate = ?)`,
		[number_plate],
		(err, result, fields) => {
			if (err) {
				return res.status(500).json({
					status: "Failed",
					message: err,
				});
			} else if (result.length > 0) {
				const inspection_date = new Date();
				const expired_date = new Date(inspection_date);
				expired_date.setMonth(expired_date.getMonth() + 6);
				connection.query(
					`UPDATE inspections
						SET inspection_date = ? , expired_date = ?
						WHERE car_id = (SELECT car_id FROM cars WHERE number_plate = ?)`,
					[inspection_date, expired_date, number_plate],
					(updateErr, updateResult, updateFields) => {
						if (updateErr) {
							return res.status(500).json({
								status: "Failed",
								error: updateErr,
							});
						}

						return res.status(200).json({
							status: "Success",
							message: "Inspection updated successfully",
							data: updateResult,
						});
					}
				);
			} else {
				const inspection_date = new Date();
				const expired_date = new Date(inspection_date);
				expired_date.setMonth(expired_date.getMonth() + 6);
				connection.query(
					`INSERT INTO inspections (inspection_id, inspection_number, inspection_date, car_id, user_id, centre_id, specify, first_time, expired_date)
					VALUES ((SELECT COUNT(*) + 1 FROM inspections),
						CONCAT(YEAR(CURDATE()), '-', LPAD(MAX(CAST(SUBSTRING(inspection_number, 6) AS UNSIGNED)) + 1, 6, '0')),
						?, (SELECT car_id FROM cars WHERE number_plate = ?),
						?,?,?,?,?,?)`,
					[
						inspection_date,
						number_plate,
						"1",
						"1",
						"carry_people$lte:9-personal+manufacture$lte:7~36~24",
						"0",
						expired_date,
					],
					(insertErr, insertResult, insertFields) => {
						if (insertErr) {
							return res.status(500).json({
								status: "Failed",
								message: insertErr,
							});
						} else {
							return res.status(201).json({
								status: "Success",
								message: `Create inspection successfully`,
								data: insertResult,
							});
						}
					}
				);
			}
		}
	);
};
Leave a Comment