DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`invoiceOut_getWeight`(vInvoiceRef VARCHAR(15)
)
	RETURNS decimal(10,2)
	NOT DETERMINISTIC
	READS SQL DATA
BEGIN
/**
 * Calcula el peso de una factura emitida
 *
 * @param vInvoiceRef referencia de la factura
 * @return vTotalWeight peso de la factura
 */
	DECLARE vTotalWeight DECIMAL(10,2);

	SELECT SUM(CAST(IFNULL(i.stems, 1)
				* s.quantity
				* IF(ic.grams, ic.grams, IFNULL(i.weightByPiece, 0)) / 1000 AS DECIMAL(10,2)))
			INTO vTotalWeight
		FROM ticket t
			JOIN sale s ON s.ticketFk = t.id
			JOIN item i ON i.id = s.itemFk
			JOIN itemCost ic ON ic.itemFk = i.id
				AND ic.warehouseFk = t.warehouseFk
		WHERE t.refFk = vInvoiceRef
			AND i.intrastatFk;

	RETURN vTotalWeight;
END$$
DELIMITER ;
