DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`ticket_isTooLittle`(
	vSelf INT
)
	RETURNS BOOL
	READS SQL DATA
BEGIN
/**
 * Check if the ticket is small based on the volume and amount parameters.
 * 
 * @param vSelf Id ticket
 * @return BOOL
 */
	DECLARE vIsTooLittle BOOL;
	
	WITH ticketData AS (
	SELECT addressFk, DATE(shipped) dated
		FROM vn.ticket 
		WHERE id = vSelf
	)
	SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume 
			AND SUM(IFNULL(t.totalWithoutVat, 0)) < vc.minTicketValue) INTO vIsTooLittle
		FROM ticketData td
			JOIN vn.ticket t ON t.addressFk = td.addressFk
			LEFT JOIN vn.saleVolume sv ON sv.ticketFk = t.id
			JOIN vn.volumeConfig vc
		WHERE t.shipped BETWEEN td.dated AND util.dayEnd(td.dated)
			AND ticket_isProblemCalcNeeded(t.id);

	RETURN vIsTooLittle;	
END$$
DELIMITER ;