
	ALTER TABLE vn.routeCommission ADD IF NOT EXISTS countryFk mediumint(8) unsigned DEFAULT NULL NULL;
	ALTER TABLE vn.routeCommission ADD IF NOT EXISTS isKmTruckRate TINYINT(1) DEFAULT NULL NULL;

	ALTER TABLE vn.routeCommission DROP FOREIGN KEY IF EXISTS routeCommission_country_FK;
	ALTER TABLE vn.routeCommission ADD CONSTRAINT routeCommission_country_FK FOREIGN KEY (countryFk)
		REFERENCES vn.country(id) ON DELETE RESTRICT ON UPDATE CASCADE;

	CREATE TABLE IF NOT EXISTS vn.workCenterCommission (
		`workCenterFk` INT(11) NOT NULL,
		`deliveryManAdjustment` DECIMAL(4,2) DEFAULT NULL
			COMMENT 'Número de trabajadores para equilibrar los repartidores de diferentes centros.
				Utilizado en repartidores de grafana',
		`distributionM3Category1` decimal(5,2) DEFAULT NULL,
		`distributionM3Category2` decimal(5,2) DEFAULT NULL,
		`distributionCat4M3` DECIMAL(5,2) DEFAULT NULL
			COMMENT 'Comisión por gestión de la distribución Cat IV',
		`distributionCat5M3` DECIMAL(5,2) DEFAULT NULL
			COMMENT 'Comisión por gestión de la distribución Cat V',
		PRIMARY KEY (`workCenterFk`),
		CONSTRAINT `workCenterCommission_workCenterFk` FOREIGN KEY (`workCenterFk`)
			REFERENCES `workCenter` (`id`) ON UPDATE CASCADE ON DELETE RESTRICT
	);

	UPDATE vn.routeCommission rc
			JOIN (SELECT id, countryFk, isKmTruckRate
					FROM (SELECT r.id, c.countryFk, v.isKmTruckRate
							FROM  vn.route r
								JOIN  vn.routeCommission rc ON rc.routeFk = r.id
								LEFT JOIN  vn.ticket t ON t.routeFk = r.id
								LEFT JOIN  vn.client c ON c.id = t.clientFk
								LEFT JOIN  vn.vehicle v ON v.id = r.vehicleFk
							WHERE r.created >= '2023-12-01'
							GROUP BY r.id, c.countryFk
							ORDER BY r.id, COUNT(*) DESC
							LIMIT 100000000000
					)sub
					GROUP BY id
			)sub ON sub.id =  rc.routeFk
		SET rc.isKmTruckRate = sub.isKmTruckRate,
			rc.countryFk = sub.countryFk;

	ALTER TABLE vn.workerDistributionCategory ADD IF NOT EXISTS countryFk mediumint(8) unsigned DEFAULT NULL NULL;
	ALTER TABLE vn.workerDistributionCategory ADD IF NOT EXISTS isKmTruckRate TINYINT(1) DEFAULT NULL NULL;

	ALTER TABLE vn.workerDistributionCategory DROP FOREIGN KEY IF EXISTS workerDistributionCategory_country_FK;
	ALTER TABLE vn.workerDistributionCategory ADD CONSTRAINT workerDistributionCategory_country_FK FOREIGN KEY (countryFk)
		REFERENCES vn.country(id) ON DELETE RESTRICT ON UPDATE CASCADE;

	ALTER TABLE vn.workerDistributionCategory ADD IF NOT EXISTS commissionSplitWorkers INT UNSIGNED NOT NULL DEFAULT 1
		COMMENT 'Número de enrutadores entr los que se reparte la comsión';
