
-- --------------------------------------------------------
-- Arrebol Consuntancy
-- version 1.0.1
-- http://www.arrebolconsultancy.com
-- --------------------------------------------------------

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
-- SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

USE `car_driver_tepic`;
-- --------------------------------------------------------
--
-- Estructura para la vista `SECURITY_AUTHORIZATION` (ROLE)
--
CREATE OR REPLACE VIEW `SECURITY_AUTHORIZATION` AS select `u`.`username` AS `user`,`p`.`name` AS `permission` from ((`USER_HAS_PERMISSION` `uhp` join `CAR_DRIVER_USER` `u` on((`uhp`.`id_user` = `u`.`id`))) join `PERMISSION` `p` on((`uhp`.`id_permission` = `p`.`id`))) where ((`u`.`user_status_type` = 'ENABLED') and (`p`.`active` = 1));
-- --------------------------------------------------------
--
-- Estructura para la vista `SECURITY_AUTHENTICATION` (USER)
--
CREATE OR REPLACE VIEW `SECURITY_AUTHENTICATION` AS select `CAR_DRIVER_USER`.`username` AS `user`,`CAR_DRIVER_USER`.`password` AS `password` from `CAR_DRIVER_USER` where (`CAR_DRIVER_USER`.`user_status_type` = 'ENABLED') ;
-- --------------------------------------------------------
--
-- Estructura para la vista `REPORT_DAILY_MONEY`
--
CREATE OR REPLACE VIEW `REPORT_DAILY_MONEY` AS select uuid() AS `ID`,sum(`SALE`.`pay_day`) AS `pay_day`,sum(`SALE`.`pay_saving`) AS `pay_saving`,sum(`SALE`.`accident`) AS `accident`,((sum(`SALE`.`pay_day`) + sum(`SALE`.`pay_saving`)) + sum(`SALE`.`accident`)) AS `total_day`,(260 * (select count(`prs`.`id`) from (`TAXI` `tx` join `PERSON` `prs` on((`tx`.`driver_id` = `prs`.`id`))) where ((`prs`.`person_type` = 'DRIVER') and (`prs`.`active` = 1)))) AS `total_expected_day`,(20 * (select count(`prs`.`id`) from (`TAXI` `tx` join `PERSON` `prs` on((`tx`.`driver_id` = `prs`.`id`))) where ((`prs`.`person_type` = 'DRIVER') and (`prs`.`active` = 1)))) AS `total_expected_saving`,(10 * (select count(`prs`.`id`) from (`TAXI` `tx` join `PERSON` `prs` on((`tx`.`driver_id` = `prs`.`id`))) where ((`prs`.`person_type` = 'DRIVER') and (`prs`.`active` = 1)))) AS `total_expected_accident`,(select sum(`EXPENSE`.`payment`) from `EXPENSE` where (cast(`EXPENSE`.`payment_date` as date) = cast((now() + interval -(6) hour) as date))) AS `expense_today`,(select sum(`SANCTION`.`payment`) from `SANCTION` where ((`SANCTION`.`sanction_type` = 'SANCTION') and (cast(`SANCTION`.`payment_date` as date) = cast((now() + interval -(6) hour) as date)))) AS `sanction_today`,(select sum(`SANCTION`.`payment`) from `SANCTION` where ((`SANCTION`.`sanction_type` = 'DISPOSITION') and (cast(`SANCTION`.`payment_date` as date) = cast((now() + interval -(6) hour) as date)))) AS `disposition_today`,(select sum(`SANCTION`.`payment`) from `SANCTION` where ((`SANCTION`.`sanction_type` = 'ACCIDENT') and (cast(`SANCTION`.`payment_date` as date) = cast((now() + interval -(6) hour) as date)))) AS `accident_today`,(select ((sum(`SALE`.`pay_day`) + sum(`SALE`.`pay_saving`)) + sum(`SALE`.`accident`)) from `SALE` where (cast(`SALE`.`created_on` as date) = cast((now() + interval -(6) hour) as date))) AS `complete_total_today` from `SALE` where (cast(`SALE`.`pay_date` as date) = cast((now() + interval -(6) hour) as date));
-- --------------------------------------------------------
--
-- Estructura para la vista `REPORT_SANCTION_DISPOSITION_ACCIDENT_BY_DRIVER`
--
CREATE OR REPLACE VIEW `REPORT_SANCTION_DISPOSITION_ACCIDENT_BY_DRIVER` AS 
select 
    `prs`.`id` AS `id`,
    CONCAT(
            CASE
                WHEN prs.first_name IS NOT NULL AND prs.first_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.first_name), 1, 1),SUBSTR(LOWER(prs.first_name), 2), ' ')
                ELSE ''
            END,
            CASE
                WHEN prs.second_name IS NOT NULL AND prs.second_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.second_name), 1, 1),SUBSTR(LOWER(prs.second_name), 2), ' ')
                ELSE ''
            END, 
            CASE
                WHEN prs.last_name IS NOT NULL AND prs.last_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.last_name), 1, 1),SUBSTR(LOWER(prs.last_name), 2), ' ')
                ELSE ''
            END,
            CASE
                WHEN prs.middle_name IS NOT NULL AND prs.middle_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.middle_name), 1, 1),SUBSTR(LOWER(prs.middle_name), 2))
                ELSE ''
            END
        )
    AS person_name,
    IF(ISNULL(`tx`.`economic_number`),'',`tx`.`economic_number`) AS `economic_number`,
    cast(`prs`.`admission_date` as date) AS `admission_date`,
    IF(ISNULL(
		(select concat(count(0),' - ',group_concat(date_format(`SANCTION`.`payment_date`,'%d-%M') separator ',')) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'SANCTION')))
    ),'',(select concat(count(0),' - ',group_concat(date_format(`SANCTION`.`payment_date`,'%d-%M') separator ',')) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'SANCTION')))
    ) AS `num_sanction`,
    IF(ISNULL(
    (select concat(count(0),' - ',group_concat(date_format(`SANCTION`.`payment_date`,'%d-%M') separator ',')) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'DISPOSITION')))
    ),'',
    (select concat(count(0),' - ',group_concat(date_format(`SANCTION`.`payment_date`,'%d-%M') separator ',')) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'DISPOSITION')))
    )  `num_disposition`,
    IF(ISNULL(
    (select concat(count(0),' - ',group_concat(date_format(`SANCTION`.`payment_date`,'%d-%M') separator ',')) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'ACCIDENT')))
    ),'',
    (select concat(count(0),' - ',group_concat(date_format(`SANCTION`.`payment_date`,'%d-%M') separator ',')) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'ACCIDENT')))
    ) AS `num_accident`,
    (select IFNULL(sum(`SANCTION`.`payment`),0) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'SANCTION'))) AS `total_sanction`,
    (select IFNULL(sum(`SANCTION`.`payment`),0) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'DISPOSITION'))) AS `total_disposition`,
    (select IFNULL(sum(`SANCTION`.`payment`),0) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'ACCIDENT'))) AS `total_accident`,
    (select IFNULL(sum(`SANCTION`.`payment`),0) from `SANCTION` where ((`SANCTION`.`driver_id` = `prs`.`id`) and (`SANCTION`.`sanction_type` = 'ADD'))) AS `total_add`,
    (select IFNULL((sum(`SALE`.`pay_saving`)),0) from `SALE` where (`SALE`.`person_id` = `prs`.`id`)) AS `total_ahorro` 
from (`PERSON` `prs` left join `TAXI` `tx` on((`tx`.`driver_id` = `prs`.`id`))) 
where `prs`.`person_type` = 'DRIVER' 
order by `prs`.`first_name`,`prs`.`second_name`,`prs`.`last_name`,`prs`.`middle_name`;
-- --------------------------------------------------------
--
-- Estructura para la vista `RESUME_DAILY_SALE`
--
CREATE OR REPLACE VIEW `RESUME_DAILY_SALE` AS select `prs`.`id` AS `id`,(select sum(((`sl`.`pay_day` + `sl`.`accident`) + `sl`.`pay_saving`)) from `SALE` `sl` where ((`sl`.`person_id` = `prs`.`id`) and (cast(`sl`.`created_on` as date) = cast((now() + interval -(6) hour) as date)))) AS `total_pay`,(select (case when isnull(group_concat(distinct date_format(`sl`.`pay_date`,'%d-%M') separator ',')) then 'No registro venta hoy' else convert(group_concat(distinct date_format(`sl`.`pay_date`,'%d-%M') separator ',') using utf8mb4) end) from `SALE` `sl` where ((`sl`.`person_id` = `prs`.`id`) and (cast(`sl`.`created_on` as date) = cast((now() + interval -(6) hour) as date)))) AS `pay_today`,(select (case when isnull(group_concat(distinct date_format(`tc`.`to_collect`,'%d-%M') separator ',')) then 'Al corriente' else convert(group_concat(distinct date_format(`tc`.`to_collect`,'%d-%M') separator ',') using utf8mb4) end) from `TO_COLLECT` `tc` where ((`tc`.`driver_id` = `prs`.`id`) and (cast(`tc`.`to_collect` as date) < cast((cast((now() + interval -(6) hour) as date) + interval 1 day) as date)))) AS `pay_pending`,(select (case when isnull(group_concat(distinct `sl`.`description` separator ',')) then group_concat(distinct `sl`.`description` separator ',') else group_concat(distinct `sl`.`description` separator ',') end) from `SALE` `sl` where ((`sl`.`person_id` = `prs`.`id`) and (cast(`sl`.`created_on` as date) = cast((now() + interval -(6) hour) as date)))) AS `notes`,`prs`.`first_name` AS `first_name`,`prs`.`second_name` AS `second_name`,`prs`.`last_name` AS `last_name`,`prs`.`middle_name` AS `middle_name`,`tx`.`economic_number` AS `economic_number` from (`PERSON` `prs` join `TAXI` `tx` on((`prs`.`id` = `tx`.`driver_id`))) where ((`prs`.`person_type` = 'DRIVER') and (`prs`.`active` = 1)) group by `prs`.`id`,`tx`.`economic_number`;
-- --------------------------------------------------------
--
-- Estructura para la vista `TICKET`
--
-- CREATE OR REPLACE VIEW `TICKET` AS select `s`.`id` AS `id`,`s`.`pay_day` AS `pay_day`,`s`.`pay_saving` AS `pay_saving`,`s`.`accident` AS `accident`,`s`.`pay_date` AS `pay_date`,concat(`p`.`first_name`,' ',`p`.`second_name`,' ',`p`.`last_name`,' ',`p`.`middle_name`) AS `complete_name`,`t`.`economic_number` AS `economic_number` from ((`SALE` `s` join `PERSON` `p` on((`s`.`person_id` = `p`.`id`))) join `TAXI` `t` on((`s`.`taxi_id` = `t`.`id`))) where (`s`.`active` = 0);
CREATE OR REPLACE VIEW TICKET AS
    SELECT 
        s.id AS id,
        s.pay_day AS pay_day,
        s.pay_saving AS pay_saving,
        s.accident AS accident,
        s.pay_date AS pay_date,
        CONCAT(p.first_name,
                ' ',
                p.second_name,
                ' ',
                p.last_name,
                ' ',
                p.middle_name) AS complete_name,
                1 AS economic_number
       -- t.economic_number AS economic_number
        -- 'Venta' as tipo
    FROM
        ((SALE s
        JOIN PERSON p ON ((s.person_id = p.id)))
        JOIN TAXI t ON ((s.taxi_id = t.id)))
    WHERE
        (s.active = 0)
UNION
	SELECT
	sa.id AS id,
        sa.payment AS pay_day,
        0 AS pay_saving,
        0 AS accident,
        sa.created_on  AS pay_date,
        CONCAT(p2.first_name,
                ' ',
                p2.second_name,
                ' ',
                p2.last_name,
                ' ',
                p2.middle_name) AS complete_name,
		-- '' AS economic_number,
        (CASE WHEN sa.sanction_type = 'ADD' THEN 2
        WHEN sa.sanction_type = 'FEE' THEN 3
        WHEN sa.sanction_type = 'ESTUDIO' THEN 4
        END) AS economic_number
	FROM 
		(SANCTION sa
        INNER JOIN PERSON p2 ON p2.id = sa.driver_id)
	WHERE
         sa.active = 0 AND 
        sa.sanction_type IN ('ADD','FEE','ESTUDIO');
-- --------------------------------------------------------
--
-- Estructura para la vista `DASHBOARD_TO_COLLECT_VIEW`
--
CREATE OR REPLACE VIEW `DASHBOARD_TO_COLLECT_VIEW` AS 
SELECT 
    tx.id AS id_vehicle,
    tx.economic_number AS economic_number,
    vh.name AS vehicle_type,
    pr.id AS id_driver,
    CONCAT( CASE WHEN pr.first_name IS NOT NULL AND pr.first_name != '' THEN CONCAT(SUBSTR(UPPER(pr.first_name), 1, 1),SUBSTR(LOWER(pr.first_name), 2)) ELSE '' END, CASE  WHEN pr.second_name IS NOT NULL AND pr.second_name != '' THEN CONCAT(' ',SUBSTR(UPPER(pr.second_name), 1, 1),SUBSTR(LOWER(pr.second_name), 2))  ELSE '' END, CASE  WHEN pr.last_name IS NOT NULL AND pr.last_name != '' THEN CONCAT(' ',SUBSTR(UPPER(pr.last_name), 1, 1),SUBSTR(LOWER(pr.last_name), 2)) ELSE '' END, CASE  WHEN pr.middle_name IS NOT NULL AND pr.middle_name != '' THEN CONCAT(' ',SUBSTR(UPPER(pr.middle_name), 1, 1),SUBSTR(LOWER(pr.middle_name), 2)) ELSE '' END) AS driver_name,
    tx.app_platform AS app_platform,
    tx.pay_day AS pay_day,
    tx.pay_saving AS pay_saving,
    tx.pay_accident AS pay_accident,
    tx.pay_day+tx.pay_saving+tx.pay_accident AS total_to_pay,
    (
        SELECT 
            IFNULL(SUM(pay_day + pay_saving + accident),0) 
        FROM SALE 
        WHERE 
            person_id = pr.id AND 
            taxi_id = tx.id AND 
            DATE(created_on) = CURDATE()
    ) AS amount_paid,
    (SELECT IF(ISNULL(SUM(toc.total)) , 0 , SUM(toc.total)) FROM TO_COLLECT toc WHERE toc.driver_id = tx.driver_id) as total_adeudo,
    (CASE
        -- WHEN (SELECT COUNT(id) FROM SALE WHERE person_id = pr.id AND taxi_id = tx.id AND DATE(created_on) = CURDATE() AND (garage = 1 OR banca = 1)) > 0
        WHEN (SELECT COUNT(id) FROM SALE WHERE person_id = pr.id AND taxi_id = tx.id AND DATE(created_on) = CURDATE()) > 0
        THEN ''
        ELSE			
            CASE 
                -- list.amountPaid eq 0.0 and (list.payDay + list.paySaving + list.payAccident) lt list.totalAdeudo? 'datatableRowEmpty' = red
		WHEN (
                (SELECT IFNULL(SUM(pay_day + pay_saving + accident),0) FROM SALE WHERE person_id = pr.id AND taxi_id = tx.id AND DATE(created_on) = CURDATE()) = 0
                AND
                (tx.pay_day + tx.pay_saving + tx.pay_accident) < (SELECT IF(ISNULL(SUM(toc.total)) , 0 , SUM(toc.total)) FROM TO_COLLECT toc WHERE toc.driver_id = tx.driver_id)
                ) THEN 'datatableRowEmpty'
                -- : list.amountPaid ge (list.payDay + list.paySaving + list.payAccident) ? 'datatableRowGreen' = GREEN
                WHEN 
                (SELECT IFNULL(SUM(pay_day + pay_saving + accident),0) FROM SALE WHERE person_id = pr.id AND taxi_id = tx.id AND DATE(created_on) = CURDATE()) >= (tx.pay_day + tx.pay_saving + tx.pay_accident )
                THEN 'datatableRowGreen'
                -- : list.amountPaid eq 0.0 ? '' : 'datatableRowLittle'
                WHEN (SELECT IFNULL(SUM(pay_day + pay_saving + accident),0) FROM SALE WHERE person_id = pr.id AND taxi_id = tx.id AND DATE(created_on) = CURDATE()) = 0
                THEN 'datatableRowLittle'
                ELSE ''
            END
    END) AS style_class,
    tx.id_location AS id_location
FROM TAXI tx 
    INNER JOIN PERSON  pr ON tx.driver_id = pr.id
    INNER JOIN VEHICLE vh ON tx.vehicle_id = vh.id
WHERE 
    tx.active = 1 AND
    pr.active = 1 AND
    CASE
        WHEN (0 = (SELECT WEEKDAY(curdate())) AND tx.day_monday = 'ENEBLED')
        THEN 
            TRUE
        WHEN (1 = (SELECT WEEKDAY(curdate())) AND tx.day_tuesday = 'ENEBLED')
        THEN 
            TRUE
        WHEN (2 = (SELECT WEEKDAY(curdate())) AND tx.day_wednesday = 'ENEBLED')
        THEN 
            TRUE
        WHEN (3 = (SELECT WEEKDAY(curdate())) AND tx.day_thursday = 'ENEBLED')
        THEN 
            TRUE
        WHEN (4 = (SELECT WEEKDAY(curdate())) AND tx.day_friday = 'ENEBLED')
        THEN 
            TRUE
        WHEN (5 = (SELECT WEEKDAY(curdate())) AND tx.day_saturday = 'ENEBLED')
        THEN 
            TRUE
        WHEN (6 = (SELECT WEEKDAY(curdate())) AND tx.day_sunday = 'ENEBLED')
        THEN 
            TRUE
        ELSE 
            FALSE
    END;
-- --------------------------------------------------------------------
-- 
-- Estructura para la vista `PERSON_SEARCH_BY_ACTIVE_AND_BLACK_LIST_VIEW`
-- SIRVE PARA VER LAS PERSONAS EN SUS ESTATUS Y SI ESTAN EN LISTA NEGRA.
-- 
-- --------------------------------------------------------------------
CREATE OR REPLACE VIEW `PERSON_SEARCH_BY_ACTIVE_AND_BLACK_LIST_VIEW` AS
SELECT
id AS id,
CONCAT(
		CASE
			WHEN first_name IS NOT NULL AND first_name != ''
			THEN CONCAT(SUBSTR(UPPER(first_name), 1, 1),SUBSTR(LOWER(first_name), 2))
			ELSE ''
		END,
        CASE
			WHEN second_name IS NOT NULL AND second_name != ''
			THEN CONCAT(' ',SUBSTR(UPPER(second_name), 1, 1),SUBSTR(LOWER(second_name), 2))
			ELSE ''
		END,
        CASE
			WHEN last_name IS NOT NULL AND last_name != ''
			THEN CONCAT(' ',SUBSTR(UPPER(last_name), 1, 1),SUBSTR(LOWER(last_name), 2))
			ELSE ''
		END,
        CASE
			WHEN middle_name IS NOT NULL AND middle_name != ''
			THEN CONCAT(' ',SUBSTR(UPPER(middle_name), 1, 1),SUBSTR(LOWER(middle_name), 2))
			ELSE ''
		END
    ) AS person_name,
    active AS active,
    black_list AS black_list,
    black_list_description AS black_list_description,
    last_updated_on AS last_updated_on
FROM PERSON;
-- --------------------------------------------------------
--
-- Estructura para la vista `VIEW_DAILY_CASH_BY_USER`
--
CREATE OR REPLACE VIEW `VIEW_DAILY_CASH_BY_USER` AS 
SELECT 
    cdurs.id AS id,
    (
        SELECT IF(ISNULL(SUM(pay_day + pay_saving + accident)),0 , SUM(pay_day + pay_saving + accident)) 
        FROM SALE 
        WHERE DATE(created_on) > 
            (SELECT DATE(cd.created_on) FROM CLOSING_DAY cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = cdurs.id AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1) 
            AND created_by = cdurs.id AND transfer = 'DISABLED'
    ) AS total_sales,
    (
        SELECT IF(ISNULL(SUM(payment)),0, SUM(payment)) 
        FROM SANCTION 
        WHERE DATE(created_on)  > 
            (SELECT DATE(cd.created_on) FROM CLOSING_DAY cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = cdurs.id AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)  
            AND sanction_type IN ('ADD', 'FEE', 'ESTUDIO') AND created_by = cdurs.id
	) AS total_sanctions_in,
    (
        SELECT IF(ISNULL(SUM(payment)),0, SUM(payment)) 
        FROM EXPENSE 
        WHERE DATE(created_on)  >
            (SELECT DATE(cd.created_on) FROM CLOSING_DAY cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = cdurs.id AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)  
            AND expense_status_type = 'AUTHORIZED' AND created_by = cdurs.id AND expense_type IN ('INICIO','OTRAS_ENTRADAS')
	) AS total_expenses_in,
    (
        SELECT IF(ISNULL(SUM(payment)),0, SUM(payment))
        FROM SANCTION 
        WHERE DATE(created_on)  > 
            (SELECT DATE(cd.created_on) FROM CLOSING_DAY cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = cdurs.id AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1) 
            AND sanction_type IN ('SANCTION','DISPOSITION','ACCIDENT') AND created_by = cdurs.id
    )  AS total_sanctions_out ,
    (
        SELECT IF(ISNULL(SUM(payment)),0, SUM(payment)) 
        FROM EXPENSE 
        WHERE DATE(created_on)  > 
            (SELECT DATE(cd.created_on) FROM CLOSING_DAY cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = cdurs.id AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)  
            AND expense_status_type = 'AUTHORIZED' AND created_by = cdurs.id AND expense_type NOT IN ('INICIO','OTRAS_ENTRADAS','MANDADOS','APOYO_VIAL')
    ) AS total_expenses_out,
    (
        SELECT IF(ISNULL(SUM(total)),0, SUM(total)) AS total_invoices 
        FROM INVOICE  
        WHERE DATE(created_on)  > 
            (SELECT DATE(cd.created_on) FROM CLOSING_DAY cd WHERE DATE(cd.created_on) <= CURDATE() AND cd.user_id = cdurs.id AND cd.active_status = 'ENEBLED' order by cd.created_on DESC LIMIT 1)  
            AND status_type = 'APPROVED' AND created_by = cdurs.id
    ) AS total_invoices 
FROM CAR_DRIVER_USER cdurs 
WHERE cdurs.user_status_type = 'ENABLED';
-- --------------------------------------------------------
--
-- Estructura para la vista `MAINTENANCE_VIEW`
--
CREATE OR REPLACE VIEW `MAINTENANCE_VIEW` AS
SELECT 
	t.id AS id, 
	CONCAT(
		CASE
			WHEN p.first_name IS NOT NULL AND p.first_name != ''
				THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
			ELSE ''
		END,
		CASE
			WHEN p.second_name IS NOT NULL AND p.second_name != ''
				THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
			ELSE ''
		END, 
		CASE
			WHEN p.last_name IS NOT NULL AND p.last_name != ''
				THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
			ELSE ''
		END,
		CASE
			WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
				THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
			ELSE ''
		END
	) AS customer_name,
	CONCAT(
		CASE
			WHEN d.first_name IS NOT NULL AND d.first_name != ''
				THEN CONCAT(SUBSTR(UPPER(d.first_name), 1, 1),SUBSTR(LOWER(d.first_name), 2), ' ')
			ELSE ''
		END,
		CASE
			WHEN d.second_name IS NOT NULL AND d.second_name != ''
				THEN CONCAT(SUBSTR(UPPER(d.second_name), 1, 1),SUBSTR(LOWER(d.second_name), 2), ' ')
			ELSE ''
		END, 
		CASE
			WHEN d.last_name IS NOT NULL AND d.last_name != ''
				THEN CONCAT(SUBSTR(UPPER(d.last_name), 1, 1),SUBSTR(LOWER(d.last_name), 2), ' ')
			ELSE ''
		END,
		CASE
			WHEN d.middle_name IS NOT NULL AND d.middle_name != ''
				THEN CONCAT(SUBSTR(UPPER(d.middle_name), 1, 1),SUBSTR(LOWER(d.middle_name), 2))
			ELSE ''
		END
	) AS driver_name,
	CASE 
		WHEN 1 = (SELECT COUNT(id) FROM CONTRACT WHERE taxi_id = t.id)
			THEN 
				CASE
					WHEN 1 = (SELECT Count(s.name) FROM CONTRACT i_c 
						INNER JOIN CONTRACT_HAS_SERVICE chs ON i_c.id = chs.contract_id
						INNER JOIN SERVICE s ON chs.service_id = s.id
						WHERE i_c.taxi_id = t.id)
                        THEN 
							(SELECT s.name FROM CONTRACT i_c 
							INNER JOIN CONTRACT_HAS_SERVICE chs ON i_c.id = chs.contract_id
							INNER JOIN SERVICE s ON chs.service_id = s.id
							WHERE i_c.taxi_id = t.id)
                     ELSE 'Tiene varios paquetes'
                END
			WHEN 1 < (SELECT COUNT(id) FROM CONTRACT WHERE taxi_id = t.id)
			THEN 'Tiene varios contratos'
		ELSE 'No tiene contrato'
	END 
	AS service,
	CONCAT(t.placa, ' - ', v.name, ' - ',t.year, ' - ', c.name) AS vehicle,
	t.km AS km,
	t.km_maintenance AS maintenance,
	t.km_maintenance - t.km AS difference,
    (SELECT module FROM HISTORY_UPDATE_KM where id_taxi = t.id ORDER BY DATE(created_on) DESC limit 1) as modulo,
    (SELECT DATE(created_on) FROM HISTORY_UPDATE_KM where id_taxi = t.id ORDER BY DATE(created_on) DESC limit 1) as fecha_km,
    (SELECT cdu2.username FROM HISTORY_UPDATE_KM huk INNER JOIN CAR_DRIVER_USER cdu2 ON cdu2.id = huk.created_by where huk.id_taxi = t.id ORDER BY DATE(huk.created_on) DESC limit 1) as usuario_km,
    t.gps_number as gps_number
FROM TAXI t
	INNER JOIN VEHICLE v ON t.vehicle_id = v.id
	INNER JOIN COLOR c ON t.color_id = c.id
	INNER JOIN PERSON p ON t.customer_id = p.id
	INNER JOIN PERSON d ON t.driver_id = d.id
WHERE 
	t.active = 1
	AND t.km_maintenance > 0
ORDER BY (t.km_maintenance - t.km) ASC;
-- --------------------------------------------------------
--
-- Estructura para la vista `STOCKTAKING_INVOICE_VIEW`
--
CREATE OR REPLACE VIEW `STOCKTAKING_INVOICE_VIEW` AS 
SELECT 
	inv.id AS id,
	inv.folio AS folio, 
	CONCAT(
            CASE
                WHEN prs.first_name IS NOT NULL AND prs.first_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.first_name), 1, 1),SUBSTR(LOWER(prs.first_name), 2), ' ')
                ELSE ''
            END,
            CASE
                WHEN prs.second_name IS NOT NULL AND prs.second_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.second_name), 1, 1),SUBSTR(LOWER(prs.second_name), 2), ' ')
                ELSE ''
            END, 
            CASE
                WHEN prs.last_name IS NOT NULL AND prs.last_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.last_name), 1, 1),SUBSTR(LOWER(prs.last_name), 2), ' ')
                ELSE ''
            END,
            CASE
                WHEN prs.middle_name IS NOT NULL AND prs.middle_name != ''
                THEN CONCAT(SUBSTR(UPPER(prs.middle_name), 1, 1),SUBSTR(LOWER(prs.middle_name), 2))
                ELSE ''
            END
        )
        AS provider_name,
	inv.buy_date AS buy_date,
	inv.subtotal AS subtotal,
	inv.iva AS iva,
	inv.total AS total,
	inv.status_type AS status_type,
	inv.comment AS comment,
	tx.economic_number AS economic_number,
	inv.created_on AS created_on,
    (SELECT buildFullPersonName(p.first_name, p.second_name, p.last_name, p.middle_name) FROM CAR_DRIVER_USER cdu
	INNER JOIN PERSON p ON cdu.person_id = p.id
	WHERE cdu.id = inv.created_by) AS created_by
FROM INVOICE inv
INNER JOIN PERSON prs ON inv.provider_id = prs.id
LEFT JOIN TAXI tx ON inv.taxi_id = tx.id
WHERE inv.active = 1
ORDER BY inv.created_on DESC;
-- --------------------------------------------------------
--
-- Estructura para la vista `PERSON_LIST_VIEW`
--
CREATE OR REPLACE VIEW `PERSON_LIST_VIEW` AS
SELECT
p.id AS id,
CONCAT(
	CASE
		WHEN p.first_name IS NOT NULL AND p.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.second_name IS NOT NULL AND p.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN p.last_name IS NOT NULL AND p.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
		ELSE ''
	END
) AS full_name,
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'HOME' AND cn.person_id = p.id)AS contact_number_local, 
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'MOBILE' AND cn.person_id = p.id)AS contact_number_mobile, 
(SELECT a.address_google_maps FROM ADDRESS a WHERE a.address_type = 'HOME' AND a.person_id = p.id) AS address,
(
SELECT GROUP_CONCAT(CONCAT(economic_number)) FROM TAXI WHERE customer_id =p.id
GROUP BY customer_id
) AS customer_vehicles,
p.admission_date AS driver_admission_date,
p.person_type AS person_type,
IF(ISNULL(p.adeudo),0,p.adeudo) AS customer_adeudo,
IF(ISNULL(p.saving),0,p.saving) AS saving_adeudo
FROM PERSON p
WHERE p.active = 1
ORDER BY full_name;
-- --------------------------------------------------------
--
-- Estructura para la vista `DRIVER_INACTIVE_AND_BLACK_LIST_VIEW`
--
CREATE OR REPLACE VIEW `DRIVER_INACTIVE_AND_BLACK_LIST_VIEW` AS
SELECT
p.id AS id,
CONCAT(
	CASE
		WHEN p.first_name IS NOT NULL AND p.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.second_name IS NOT NULL AND p.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN p.last_name IS NOT NULL AND p.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
		ELSE ''
	END
) AS full_name,
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'HOME' AND cn.person_id = p.id)AS contact_number_local, 
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'MOBILE' AND cn.person_id = p.id)AS contact_number_mobile, 
(SELECT a.address_google_maps FROM ADDRESS a WHERE a.address_type = 'HOME' AND a.person_id = p.id) AS address,
p.admission_date AS driver_admission_date,
IF(ISNULL(p.black_list),'DISABLED', p.black_list) AS black_list,
p.black_list_description AS black_list_description,
p.last_updated_on AS black_list_date,
p.adeudo AS black_list_adeudo
FROM PERSON p
WHERE 
	p.active = 0 AND
    p.person_type = 'DRIVER'
ORDER BY full_name;
-- --------------------------------------------------------
--
-- Estructura para la vista `FEE_DASHBOARD_PERSON_LIST_VIEW`
--
CREATE OR REPLACE VIEW `FEE_DASHBOARD_PERSON_LIST_VIEW` AS
SELECT fee.driver_id AS id, SUM(fee.amount) AS amount, COUNT(fee.id) AS total,
CONCAT(
	CASE
		WHEN p.first_name IS NOT NULL AND p.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.second_name IS NOT NULL AND p.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN p.last_name IS NOT NULL AND p.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
		ELSE ''
	END
) AS full_name
FROM FEE_BY_DRIVER fee
INNER JOIN PERSON p ON fee.driver_id = p.id
WHERE fee.fee_status = 'NO_PAID'
GROUP BY fee.driver_id;
-- --------------------------------------------------------
--
-- Estructura para la vista `INSURANCE_DASHBOARD_LIST_VIEW`
--
CREATE OR REPLACE VIEW `INSURANCE_DASHBOARD_LIST_VIEW` AS
SELECT 
taxi.id AS id,
taxi.economic_number AS economic_number,
taxi.insurance_end_date AS insurance_end_date,
taxi.insurance_name AS insurance_name,
taxi.insurance_cobertura AS insurance_cobertura,
CONCAT(
	CASE
		WHEN driver.first_name IS NOT NULL AND driver.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.first_name), 1, 1),SUBSTR(LOWER(driver.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN driver.second_name IS NOT NULL AND driver.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.second_name), 1, 1),SUBSTR(LOWER(driver.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN driver.last_name IS NOT NULL AND driver.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.last_name), 1, 1),SUBSTR(LOWER(driver.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN driver.middle_name IS NOT NULL AND driver.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.middle_name), 1, 1),SUBSTR(LOWER(driver.middle_name), 2))
		ELSE ''
	END
) AS full_driver_name,
CONCAT(
	CASE
		WHEN customer.first_name IS NOT NULL AND customer.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.first_name), 1, 1),SUBSTR(LOWER(customer.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN customer.second_name IS NOT NULL AND customer.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.second_name), 1, 1),SUBSTR(LOWER(customer.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN customer.last_name IS NOT NULL AND customer.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.last_name), 1, 1),SUBSTR(LOWER(customer.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN customer.middle_name IS NOT NULL AND customer.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.middle_name), 1, 1),SUBSTR(LOWER(customer.middle_name), 2))
		ELSE ''
	END
) AS full_customer_name,
(
CASE
	WHEN ISNULL(taxi.insurance_end_date)
    THEN 'EMPETY'
	WHEN DATE(taxi.insurance_end_date) < CURDATE()
    THEN 'FINISHED'
    WHEN DATE(taxi.insurance_end_date) BETWEEN CURDATE() AND CURDATE() + 10
    THEN 'COMMING_SOON'
    ELSE 'PROGRESS'
END
) AS insurance_status
FROM TAXI taxi
LEFT JOIN PERSON driver ON taxi.driver_id = driver.id
LEFT JOIN PERSON customer ON taxi.customer_id = customer.id
WHERE taxi.active = 1
ORDER BY taxi.insurance_end_date;

CREATE OR REPLACE VIEW `FEE_DASHBOARD_PERSON_LIST_VIEW` AS
SELECT fee.driver_id AS id, SUM(fee.amount) AS amount, COUNT(fee.id) AS total,
CONCAT(
	CASE
		WHEN p.first_name IS NOT NULL AND p.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.second_name IS NOT NULL AND p.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN p.last_name IS NOT NULL AND p.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
		ELSE ''
	END
) AS full_name
FROM FEE_BY_DRIVER fee
INNER JOIN PERSON p ON fee.driver_id = p.id
WHERE fee.fee_status = 'NO_PAID'
GROUP BY fee.driver_id;
-- --------------------------------------------------------
--
-- Estructura para la vista `PERSON_LIST_VIEW`
--
CREATE OR REPLACE VIEW `PERSON_LIST_VIEW` AS
SELECT
p.id AS id,
CONCAT(
	CASE
		WHEN p.first_name IS NOT NULL AND p.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.second_name IS NOT NULL AND p.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN p.last_name IS NOT NULL AND p.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
		ELSE ''
	END
) AS full_name,
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'HOME' AND cn.person_id = p.id)AS contact_number_local, 
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'MOBILE' AND cn.person_id = p.id)AS contact_number_mobile, 
(SELECT a.address_google_maps FROM ADDRESS a WHERE a.address_type = 'HOME' AND a.person_id = p.id) AS address,
p.admission_date AS driver_admission_date,
IF(ISNULL(p.black_list),'DISABLED', p.black_list) AS black_list,
p.black_list_description AS black_list_description,
p.last_updated_on AS black_list_date,
p.adeudo AS black_list_adeudo
FROM PERSON p
WHERE 
	p.active = 0 AND
    p.person_type = 'DRIVER'
ORDER BY full_name;
-- --------------------------------------------------------
--
-- Estructura para la vista `INSURANCE_DASHBOARD_LIST_VIEW`
--
CREATE OR REPLACE VIEW `INSURANCE_DASHBOARD_LIST_VIEW` AS
SELECT 
taxi.id AS id,
taxi.economic_number AS economic_number,
taxi.insurance_end_date AS insurance_end_date,
taxi.insurance_name AS insurance_name,
taxi.insurance_cobertura AS insurance_cobertura,
CONCAT(
	CASE
		WHEN driver.first_name IS NOT NULL AND driver.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.first_name), 1, 1),SUBSTR(LOWER(driver.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN driver.second_name IS NOT NULL AND driver.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.second_name), 1, 1),SUBSTR(LOWER(driver.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN driver.last_name IS NOT NULL AND driver.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.last_name), 1, 1),SUBSTR(LOWER(driver.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN driver.middle_name IS NOT NULL AND driver.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(driver.middle_name), 1, 1),SUBSTR(LOWER(driver.middle_name), 2))
		ELSE ''
	END
) AS full_driver_name,
CONCAT(
	CASE
		WHEN customer.first_name IS NOT NULL AND customer.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.first_name), 1, 1),SUBSTR(LOWER(customer.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN customer.second_name IS NOT NULL AND customer.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.second_name), 1, 1),SUBSTR(LOWER(customer.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN customer.last_name IS NOT NULL AND customer.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.last_name), 1, 1),SUBSTR(LOWER(customer.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN customer.middle_name IS NOT NULL AND customer.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(customer.middle_name), 1, 1),SUBSTR(LOWER(customer.middle_name), 2))
		ELSE ''
	END
) AS full_customer_name,
(
CASE
	WHEN ISNULL(taxi.insurance_end_date)
    THEN 'EMPETY'
	WHEN DATE(taxi.insurance_end_date) < CURDATE()
    THEN 'FINISHED'
    WHEN DATE(taxi.insurance_end_date) BETWEEN CURDATE() AND CURDATE() + 10
    THEN 'COMMING_SOON'
    ELSE 'PROGRESS'
END
) AS insurance_status
FROM TAXI taxi
LEFT JOIN PERSON driver ON taxi.driver_id = driver.id
LEFT JOIN PERSON customer ON taxi.customer_id = customer.id
WHERE taxi.active = 1
ORDER BY taxi.insurance_end_date;
-- --------------------------------------------------------
--
-- Estructura para la vista `KARDEX_IN_STOCKTAKING_VIEW`
--
CREATE OR REPLACE VIEW KARDEX_IN_STOCKTAKING_VIEW AS 
SELECT  
CONCAT(i.id, p.id) as id,
i.created_on as fecha,
CONCAT(pr.first_name, ' ', pr.last_name) as proveedor,
ihp.quantity as cantidad,
p.name as producto,
p.code as producto_code,
ihp.price as precio_mayoreo,
ihp.price_menudeo as precio_menudeo,
(ihp.quantity * ihp.price_menudeo) as total,
i.comment as comentarios,
cdu.username as usuario,
i.folio as compra,
IF(ISNULL(t.economic_number),'Sin vehiculo', t.economic_number) nombre_taxi
FROM INVOICE_HAS_PRODUCT ihp 
INNER JOIN INVOICE i ON ihp.invoice_id = i.id
INNER JOIN PRODUCT p ON ihp.product_id = p.id
INNER JOIN PERSON pr ON pr.id = i.provider_id
INNER JOIN CAR_DRIVER_USER cdu ON cdu.id = i.created_by
LEFT JOIN TAXI t ON t.id = i.taxi_id
WHERE i.active = 1
ORDER BY i.created_on DESC;
-- --------------------------------------------------------
--
-- Estructura para la vista `SALE_DASHBOARD_VIEW` 
--
CREATE OR REPLACE VIEW `SALE_DASHBOARD_VIEW` AS 
SELECT 
    s.id AS id,
    s.person_id AS driver_id, s.taxi_id AS taxi_id, DATE_ADD(DATE(s.pay_date), INTERVAL 1 DAY) AS pay_date,
    buildFullPersonName(p.first_name, p.second_name, p.last_name, p.middle_name) AS full_name,
    SUM(s.pay_day) AS pay_day, SUM(s.pay_saving) AS pay_saving, SUM(s.accident) AS accident, 
    -- (SELECT IF(ISNULL(t.pay_day),0, t.pay_day) FROM TAXI t  WHERE t.id = s.taxi_id) - SUM(s.pay_day) AS to_complete_pay_day,
    s.pay_day_as_spected - SUM(s.pay_day) AS to_complete_pay_day,
    -- (SELECT IF(ISNULL(t.pay_saving),0, t.pay_saving) FROM TAXI t  WHERE t.id = s.taxi_id) - SUM(s.pay_saving) AS to_complete_pay_saving,
   s.pay_saving_as_spected - SUM(s.pay_saving) AS to_complete_pay_saving,
    -- (SELECT IF(ISNULL(t.pay_accident),0, t.pay_accident) FROM TAXI t  WHERE t.id = s.taxi_id) - SUM(s.accident) AS to_complete_pay_accident,
    s.accident_as_spected - SUM(s.accident) AS to_complete_pay_accident,
    -- (SELECT t.pay_day + t.pay_saving + t.pay_accident FROM TAXI t  WHERE t.id = s.taxi_id) AS total_to_pay,
    s.total_to_pay AS total_to_pay,
    (SUM(s.pay_day) + SUM(s.pay_saving) +  SUM(s.accident)) AS total_to_paid,
    GROUP_CONCAT(s.description SEPARATOR ',') AS description,
    IF(ISNULL(s.garage),0,s.garage) AS garage,
    IF(ISNULL(s.nueva_asignacion),0,s.nueva_asignacion) AS nueva_asignacion,
    IF(ISNULL(s.banca),0,s.banca) AS banca,
    (CASE
	WHEN (SUM(s.pay_day) + SUM(s.pay_saving)  + SUM(s.accident)) > s.total_to_pay
        THEN 'bigger'
        WHEN (SUM(s.pay_day) + SUM(s.pay_saving)  + SUM(s.accident)) = s.total_to_pay
        THEN 'complete'
        ELSE
            'incomplete'
    END) AS sale_status,
    s.id_bank_card AS id_bank_card,
    (SELECT numero FROM BANK_CARD WHERE id =  s.id_bank_card) AS account_number,
    s.transfer AS transfer
FROM SALE s
INNER JOIN PERSON p ON s.person_id = p.id
GROUP BY s.person_id, s.taxi_id, DATE(s.pay_date), s.total_to_pay
ORDER BY DATE(s.pay_date) DESC;
-- --------------------------------------------------------
--
-- Estructura para la vista `FEE_BY_DRIVER_DASHBOARD_VIEW` 
--
CREATE OR REPLACE VIEW `FEE_BY_DRIVER_DASHBOARD_VIEW` AS 
SELECT 
    f.id AS id,
    f.driver_id AS driver_id,
    buildFullPersonName(p.first_name, p.second_name, p.last_name, p.middle_name) AS full_name,
    (CASE
        WHEN f.comments = 'Multa automatica por sistema'
        THEN 
            f.fee_date
        ELSE
            DATE_ADD(DATE(f.fee_date), INTERVAL 1 DAY)
    END) AS fee_date,
    f.amount AS amount,
    f.fee_status AS fee_status,
    f.comments AS comments
FROM FEE_BY_DRIVER f
INNER JOIN PERSON p ON f.driver_id = p.id
WHERE f.fee_status IN ('NO_PAID', 'PAID');
-- --------------------------------------------------------
--
-- Estructura para la vista `FEE_BY_DRIVER_ADMIN_VIEW` 
--
CREATE OR REPLACE VIEW `FEE_BY_DRIVER_ADMIN_VIEW` AS 
SELECT 
    fbd.id AS id, p.id AS driver_id, fbd.fee_date AS fee_date, fbd.amount AS amount, fbd.comments AS comments, fbd.fee_status,
    buildFullPersonName(p.first_name, p.second_name, p.last_name, p.middle_name) AS full_name,
    (SELECT IF(ISNULL(username),'',username) FROM CAR_DRIVER_USER cdu  WHERE cdu.id = fbd.created_by) AS created_by,
    (SELECT IF(ISNULL(username),'',username) FROM CAR_DRIVER_USER cdu  WHERE cdu.id = fbd.last_updated_by) AS last_updated_by
FROM FEE_BY_DRIVER fbd
INNER JOIN PERSON p ON fbd.driver_id = p.id
ORDER BY fbd.fee_date DESC;

CREATE OR REPLACE VIEW KARDEX_IN_STOCKTAKING_VIEW AS 
SELECT  
CONCAT(i.id, p.id) as id,
i.created_on as fecha,
CONCAT(pr.first_name, ' ', pr.last_name) as proveedor,
ihp.quantity as cantidad,
p.name as producto,
ihp.price as precio_mayoreo,
ihp.price_menudeo as precio_menudeo,
(ihp.quantity * ihp.price) as total,
i.comment as comentarios,
cdu.username as usuario,
i.folio as compra,
IF(ISNULL(t.economic_number),'Sin vehiculo', t.economic_number) nombre_taxi,
i.iva as iva,
pr.id as provider_id,
p.id as product_id
FROM INVOICE_HAS_PRODUCT ihp 
INNER JOIN INVOICE i ON ihp.invoice_id = i.id
INNER JOIN PRODUCT p ON ihp.product_id = p.id
INNER JOIN PERSON pr ON pr.id = i.provider_id
INNER JOIN CAR_DRIVER_USER cdu ON cdu.id = i.created_by
LEFT JOIN TAXI t ON t.id = i.taxi_id
WHERE i.active = 1
ORDER BY i.created_on DESC;

CREATE OR REPLACE VIEW KARDEX_OUT_STOCKTAKING_VIEW AS 
SELECT  
CONCAT(i.id, p.id) as id,
i.created_on as fecha,
CONCAT(pr.economic_number) as taxi,
ihp.quantity as cantidad,
p.name as producto,
p.code as codigo_producto,
b.name as marca,
b.id as brand_id,
ihp.price as precio,
ihp.total as total,
ihp.mayoreo as mayoreo,
i.description as comentarios,
cdu.username as usuario,
i.name as orden_serivicio,
i.id as service_id,
p.id as product_id,
i.taxi_id as taxi_id,
i.service_order_type as estatus,
(CASE
	WHEN
    (SELECT COUNT(prdct.id) FROM PRODUCT prdct WHERE prdct.brand_id = '5d70cb1e-c545-4f87-9d2d-99f9d172992f' AND prdct.id = p.id) > 0 
    AND
    (SELECT COUNT(cntrct.id) FROM CONTRACT_HAS_SERVICE chs 
	INNER JOIN CONTRACT cntrct ON chs.contract_id = cntrct.id INNER JOIN SERVICE srvc ON chs.service_id = srvc.id
	WHERE cntrct.taxi_id = pr.id AND  srvc.discount_fix > 0 AND srvc.active = 1 AND cntrct.active = 1) > 0
    THEN
		(SELECT ihp.total - (ihp.total * (MAX(srvc.discount_fix) /100)) FROM CONTRACT_HAS_SERVICE chs 
		INNER JOIN CONTRACT cntrct ON chs.contract_id = cntrct.id
		INNER JOIN SERVICE srvc ON chs.service_id = srvc.id
		WHERE cntrct.taxi_id = pr.id
		AND  srvc.discount_fix > 0 AND srvc.active = 1 AND cntrct.active = 1)
    ELSE ihp.total
END) AS price_to_pay,
CASE WHEN cobrado = 'ENEBLED' THEN 'Cobrado'
WHEN cobrado = 'DISABLED' THEN 'No cobrado'
end as cobrado
FROM SERVICE_ORDER_HAS_PRODUCT ihp 
INNER JOIN SERVICE_ORDER i ON ihp.service_order_id = i.id
INNER JOIN PRODUCT p ON ihp.product_id = p.id
INNER JOIN BRAND b ON b.id = p.brand_id
INNER JOIN TAXI pr ON pr.id = i.taxi_id
INNER JOIN CAR_DRIVER_USER cdu ON cdu.id = i.created_by
WHERE i.active = 1
ORDER BY i.created_on DESC;

CREATE OR REPLACE VIEW `PERSON_LIST_FINANCING_VIEW` AS
SELECT
p.id AS id,
CONCAT(
	CASE
		WHEN p.first_name IS NOT NULL AND p.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.second_name IS NOT NULL AND p.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN p.last_name IS NOT NULL AND p.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
		ELSE ''
	END
) AS full_name,
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'HOME' AND cn.person_id = p.id)AS contact_number_local, 
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'MOBILE' AND cn.person_id = p.id)AS contact_number_mobile, 
(SELECT a.address_google_maps FROM ADDRESS a WHERE a.address_type = 'HOME' AND a.person_id = p.id) AS address,
(
SELECT GROUP_CONCAT(CONCAT(economic_number)) FROM TAXI WHERE customer_id =p.id
GROUP BY customer_id
) AS customer_vehicles,
p.admission_date AS driver_admission_date,
p.person_type AS person_type,
IF(ISNULL(p.adeudo),0,p.adeudo) AS customer_adeudo,
p.id_location as location
FROM PERSON p
ORDER BY full_name;

CREATE OR REPLACE VIEW `PERSON_LIST_CUSTOMER_FINANCING_VIEW` AS
SELECT
p.id AS id,
CONCAT(
	CASE
		WHEN p.first_name IS NOT NULL AND p.first_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.first_name), 1, 1),SUBSTR(LOWER(p.first_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.second_name IS NOT NULL AND p.second_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.second_name), 1, 1),SUBSTR(LOWER(p.second_name), 2), ' ')
		ELSE ''
	END, 
	CASE
		WHEN p.last_name IS NOT NULL AND p.last_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.last_name), 1, 1),SUBSTR(LOWER(p.last_name), 2), ' ')
		ELSE ''
	END,
	CASE
		WHEN p.middle_name IS NOT NULL AND p.middle_name != ''
		THEN CONCAT(SUBSTR(UPPER(p.middle_name), 1, 1),SUBSTR(LOWER(p.middle_name), 2))
		ELSE ''
	END
) AS full_name,
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'HOME' AND cn.person_id = p.id)AS contact_number_local, 
(SELECT cn.contact_number FROM CONTACT_NUMBER cn WHERE cn.number_type = 'MOBILE' AND cn.person_id = p.id)AS contact_number_mobile, 
(SELECT a.address_google_maps FROM ADDRESS a WHERE a.address_type = 'HOME' AND a.person_id = p.id) AS address,
(
SELECT GROUP_CONCAT(CONCAT(economic_number)) FROM TAXI WHERE customer_id =p.id
GROUP BY customer_id
) AS customer_vehicles,
p.admission_date AS driver_admission_date,
p.person_type AS person_type,
IF(ISNULL((SELECT SUM(adeudo_customer) FROM TAXI WHERE customer_id = p.id)),0,(SELECT SUM(adeudo_customer) FROM TAXI WHERE customer_id = p.id)) AS customer_adeudo,
p.id_location as location
FROM PERSON p
WHERE p.active = 1
ORDER BY full_name;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;