DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`sale_afterInsert` AFTER INSERT ON `sale` FOR EACH ROW BEGIN IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN CALL util.throw('Cannot insert a service item into a ticket'); END IF; CALL stock.log_add('sale', NEW.id, NULL); CALL ticket_requestRecalc(NEW.ticketFk); IF NEW.quantity > 0 THEN UPDATE vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk JOIN vn.item i ON i.id = NEW.itemFk AND (c.itemPackingTypeFk = i.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) SET c.saleTotalCount = c.saleTotalCount + 1; INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) SELECT r.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.route r ON r.id = t.routeFk WHERE r.isOk = FALSE AND s.id = NEW.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; END IF; END$$ DELIMITER ;