﻿DROP TABLE IF EXISTS territory
CREATE TABLE territory (id INTEGER PRIMARY KEY, territory_number INTEGER, locality TEXT, city_id INTEGER, type_id INTEGER, priority INTEGER, lang_id INTEGER, time_stamp INTEGER DEFAULT 0, active BOOLEAN DEFAULT 1, uuid TEXT)
CREATE TABLE if not exists territory_city (id INTEGER PRIMARY KEY, city TEXT, lang_id INT, time_stamp INT DEFAULT 0, active BOOLEAN DEFAULT 1, uuid TEXT);
CREATE TABLE if not exists territory_assignment (id INTEGER PRIMARY KEY, territory_id INTEGER, person_id INTEGER, checkedout_date DATE, checkedbackin_date DATE, lang_id INTEGER, time_stamp INTEGER DEFAULT 0, active BOOLEAN DEFAULT 1, uuid TEXT)
CREATE TABLE if not exists territory_type (id INTEGER PRIMARY KEY, type_name TEXT, lang_id INT, time_stamp INT DEFAULT 0, active BOOLEAN DEFAULT 1, uuid TEXT)

CREATE VIEW if not exists cityterritory AS SELECT territory_city.city, territory.* FROM territory LEFT JOIN territory_city ON territory.city_id = territory_city.id WHERE territory.active AND territory_city.active;
CREATE VIEW if not exists territoryassignments AS SELECT territory_assignment.id, territory_assignment.territory_id, territory_assignment.person_id, persons.lastname, persons.firstname, territory_assignment.checkedout_date, territory_assignment.checkedbackin_date, territory_assignment.lang_id , territory_assignment.active FROM territory_assignment LEFT JOIN persons ON territory_assignment.person_id = persons.id WHERE territory_assignment.active;
CREATE VIEW if not exists territories AS SELECT territory_city.city, territory.* ,territory_type.type_name, assignedTerritories.person_id, persons.firstname || ' ' || persons.lastname publisher, CASE WHEN workedthrough.assigneddays <= 187 THEN '< 6 months' WHEN workedthrough.assigneddays <= 365 THEN '6 to 12 months' WHEN workedthrough.assigneddays > 365 THEN '> 12 months ago' END AS workedthrough FROM territory LEFT JOIN territory_city ON territory.city_id = territory_city.id LEFT JOIN territory_type ON territory.type_id = territory_type.id LEFT JOIN (SELECT territory_id, person_id FROM territory_assignment WHERE territory_assignment.checkedbackin_date IS NULL AND territory_assignment.active) assignedTerritories ON territory.id = assignedTerritories.territory_id LEFT JOIN persons ON assignedTerritories.person_id = persons.id LEFT JOIN (SELECT territory_assignment.territory_id, julianday(datetime('now')) - julianday(max(territory_assignment.checkedbackin_date))  AS assigneddays FROM territory_assignment WHERE territory_assignment.checkedbackin_date IS NOT NULL AND  territory_assignment.active GROUP BY territory_assignment.territory_id) workedthrough ON territory.id = workedthrough.territory_id WHERE (territory_city.active OR territory_city.active IS NULL) AND (territory_type.active OR territory_type.active IS NULL) AND territory.active
