INSERT INTO config (cfg_key, cfg_value) VALUES ('DATEFORMAT_PRINT', 'd.m.Y');
INSERT INTO config (cfg_key, cfg_value) VALUES ('SHOWPRJTITLELENGHT', '60');
INSERT INTO config (cfg_key, cfg_value) VALUES ('SHOWOPCATTITLELENGHT', '60');
INSERT INTO config (cfg_key, cfg_value) VALUES ('VERSION_DB', '0.3');
INSERT INTO config (cfg_key, cfg_value) values ('MAIN_SHOW_PRJSTAT', '');
INSERT INTO config (cfg_key, cfg_value) values ('GRAPHVIZ_ENABLED', 'false');
INSERT INTO config (cfg_key, cfg_value) values ('FIN_UNBILLED_GRPBY', '');
INSERT INTO config (cfg_key, cfg_value) values ('MAIN_PRJTAB_SORT', '');

alter table companies add column "cpn_address2" character varying(250);

alter table persons add column "pe_address2" character varying(250);
alter table persons add column pe_hourlyrate numeric(12,2);

alter table users add column usr_perm character varying(250);

alter table operations add op_billabletype int;
alter table operations alter op_billabletype set default 0;
alter table operations add column op_amount numeric(12,2);

alter table projects add column prj_deadline date;
alter table projects add column prj_planned_manhours int;
alter table projects add column prj_planned_cost_manhours numeric(12,2);
alter table projects add column prj_planned_cost_material numeric(12,2);
alter table projects add prj_billabletype int;

alter table projects alter prj_billabletype set default 0;

-- Uncomment the following line if all of your projects are billable, othwise
-- set the status for each project from the projects interface
--
-- update projects set prj_billabletype=0 where prj_billabletype is null;

alter table operationcat add column opcat_color character varying(20);

update users set usr_perm='1|2|3|4|5|6|7|8|9|10|11|12|14|15|13|16' where usr_priv=1;

CREATE TABLE log (
        id INT NOT NULL,
        logtime TIMESTAMP NOT NULL,
        ident CHAR(16) NOT NULL,
        priority INT NOT NULL,
        message text,
        PRIMARY KEY (id)
);

CREATE OR REPLACE VIEW v_summary_notbilledhours AS
        SELECT p.cpn_id,
        cpn_name,
        p.prj_id,
        prj_title,
        SUM(op_duration) as prj_duration,
        SUM(prjmem_hourlyrate * (cast(op_duration AS FLOAT)/ 60))  AS prj_amount,
        to_char(cast(min(op_timestamp_start) AS abstime), 'yyyy-mm-dd hh:mi') AS op_min_start,
        to_char(cast(max(op_timestamp_end) AS abstime), 'yyyy-mm-dd hh:mi') AS op_max_end
        FROM projects p
        LEFT JOIN operations o ON o.prj_id = p.prj_id
        LEFT JOIN project_members pm ON (pm.prj_id = o.prj_id AND pm.pe_id = o.pe_id)
        LEFT JOIN companies c ON c.cpn_id = p.cpn_id
        WHERE (prj_billabletype IS NULL OR prj_billabletype = 0)
        AND (o.bill_id IS NULL OR o.bill_id = 0)
        AND (op_billabletype IS NULL OR op_billabletype = 0)
        GROUP BY p.cpn_id, cpn_name, p.prj_id, prj_title
        ORDER BY cpn_name, prj_title;

create or replace view v_summary_notbilledhours_bycustomer as
        SELECT p.cpn_id, cpn_name, sum(op_duration) AS prj_duration,
        sum(prjmem_hourlyrate::double precision * (op_duration::double precision / 60::double precision)) AS prj_amount,
        to_char(min(op_timestamp_start)::abstime::timestamp with time zone, 'yyyy-mm-dd hh:mi'::text) AS op_min_start,
        to_char(max(op_timestamp_end)::abstime::timestamp with time zone, 'yyyy-mm-dd hh:mi'::text) AS op_max_end
        FROM projects p
        LEFT JOIN operations o ON o.prj_id = p.prj_id
        LEFT JOIN project_members pm ON pm.prj_id = o.prj_id AND pm.pe_id = o.pe_id
        LEFT JOIN companies c ON c.cpn_id = p.cpn_id
        WHERE (prj_billabletype IS NULL OR prj_billabletype = 0)
        AND (o.bill_id IS NULL OR o.bill_id = 0)
        AND (op_billabletype IS NULL OR op_billabletype = 0)
        GROUP BY p.cpn_id, cpn_name
        ORDER BY cpn_name;


CREATE SEQUENCE "lineitems_lit_id_seq";

CREATE TABLE "lineitems" (
	"lit_id" bigint DEFAULT nextval('lineitems_lit_id_seq'::text) NOT NULL,
	"bill_id" bigint,
	"quot_id" bigint,
        "op_id" bigint,
        "lit_prodcode" character varying(18),
	"lit_desc" text,
	"lit_qty" character varying(10),
        "lit_netprice" numeric(12,2),
	Constraint "lineitems_pkey" Primary Key ("lit_id")
);

CREATE INDEX lit_prodcode_lineitems_index ON lineitems USING btree (lit_prodcode);
CREATE INDEX bill_id_lineitems_index ON lineitems USING btree (bill_id);
CREATE INDEX quot_id_lineitems_index ON lineitems USING btree (quot_id);
CREATE INDEX op_id_lineitems_index ON lineitems USING btree (op_id);

ALTER TABLE lineitems ADD CONSTRAINT fk_lineitems_bill_id FOREIGN KEY (bill_id) REFERENCES bills(bill_id) MATCH FULL;
ALTER TABLE lineitems ADD CONSTRAINT fk_lineitems_quot_id FOREIGN KEY (quot_id) REFERENCES quotations(quot_id) MATCH FULL;
ALTER TABLE lineitems ADD CONSTRAINT fk_lineitems_op_id FOREIGN KEY (op_id) REFERENCES operations(op_id) MATCH FULL;

alter table bills add column bill_payterm character varying(30);
alter table quotations add column quot_payterm character varying(30);
alter table projects add column prj_priority smallint;

ALTER TABLE bills ALTER COLUMN bill_desc DROP NOT NULL;
ALTER TABLE quotations ALTER COLUMN quot_desc DROP NOT NULL;
alter table billing_methods add column bmt_status smallint;

alter table projects add column quot_id bigint;
CREATE INDEX quot_id_projects_index ON projects USING btree (quot_id);
ALTER TABLE projects ADD CONSTRAINT fk_projects_quot_id FOREIGN KEY (quot_id) REFERENCES quotations(quot_id) MATCH FULL;

alter table projects add column prj_manager_pe_id bigint;
CREATE INDEX prj_manager_pe_id_projects_index ON projects USING btree (prj_manager_pe_id);
ALTER TABLE projects ADD CONSTRAINT fk_projects_prj_manager_pe_id FOREIGN KEY (prj_manager_pe_id) REFERENCES persons(pe_id) MATCH FULL;

CREATE INDEX prj_prj_id_projects_index ON projects USING btree (prj_prj_id);

alter table companies add column cpn_defaultpayterm character varying(30);

INSERT INTO config (cfg_key, cfg_value) values ('FIN_FISCYEAR_MONTH', 1);
INSERT INTO config (cfg_key, cfg_value) values ('FIN_FISCYEAR_DAY', 1);

CREATE SEQUENCE "files_file_id_seq";

CREATE TABLE "files" (
	"file_id" bigint DEFAULT nextval('files_file_id_seq'::text) NOT NULL,
        "file_added" timestamp without time zone DEFAULT now() NOT NULL,
	"pe_id" bigint NOT NULL,
        "file_original_name" character varying(500) not null,
        "file_local_name" character varying(100) not null,
        "file_rel_type" int not null,
        "file_rel_id" bigint not null,
        "file_mimetype" character varying(30),
	Constraint "files_pkey" Primary Key ("file_id")
);

CREATE INDEX pe_id_files_index ON files USING btree (pe_id);
ALTER TABLE files ADD CONSTRAINT fk_files_pe_id FOREIGN KEY (pe_id) REFERENCES persons(pe_id) MATCH FULL;

INSERT INTO config (cfg_key, cfg_value) VALUES ('DATETIMEFORMAT_LONG', '%A, %d. %B %Y %R');
INSERT INTO config (cfg_key, cfg_value) VALUES ('DATETIMEFORMAT_SHORT', '%d.%m.%Y (%a) %R');

CREATE SEQUENCE "productcat_prcat_id_seq";

CREATE TABLE "productcat" (
       "prcat_id" bigint DEFAULT nextval('productcat_prcat_id_seq'::text) NOT NULL,
       "prcat_title" character varying(100) NOT NULL,
       Constraint "productcat_pkey" Primary Key ("prcat_id")
);

CREATE UNIQUE INDEX prcat_title_productcat_ind ON productcat USING btree (prcat_title);


CREATE SEQUENCE "products_prod_id_seq";

CREATE TABLE "products" (
       "prod_id" bigint DEFAULT nextval('products_prod_id_seq'::text) NOT NULL,
       "prod_code" character varying(18) NOT NULL,
       "prod_name" character varying(100) NOT NULL,
       "prod_price" numeric(12,2),
       "prod_consumption" numeric(12,4),
       "prod_stock" int,
       "prcat_id" bigint,
       "prod_created" timestamp without time zone default now() NOT NULL,
       "prod_lastmod" timestamp without time zone NOT NULL,
       Constraint "products_pkey" Primary key ("prod_id")
);

ALTER TABLE products ADD CONSTRAINT fk_products_prcat_id FOREIGN KEY (prcat_id) REFERENCES productcat(prcat_id) MATCH FULL;
CREATE INDEX prod_code_products_index ON products USING btree (prod_code);
CREATE INDEX prcat_id_products_index ON products USING btree (prcat_id);
CREATE UNIQUE INDEX prod_code_products_ind ON products USING btree (prod_code);


CREATE SEQUENCE "material_mat_id_seq";

CREATE TABLE "material" (
	"mat_id" bigint DEFAULT nextval('material_mat_id_seq'::text) NOT NULL,
        "mat_prodcode" character varying(100),
        "prod_id" bigint,
        "mat_name" character varying(100),
	"mat_desc" text,
        "mat_qty" integer,
	"mat_price" numeric(12,2) NOT NULL,
	"curr_id" smallint NOT NULL,
	"mat_added" timestamp without time zone default now() NOT NULL,
	"prj_id" bigint NOT NULL,
	"pe_id" bigint NOT NULL,
	"bill_id" bigint,
	Constraint "material_pkey" Primary Key ("mat_id")
);

CREATE INDEX bill_id_material_index ON material USING btree (bill_id);
CREATE INDEX pe_id_material_index ON material USING btree (pe_id);
CREATE INDEX prj_id_material_index ON material USING btree (prj_id);
CREATE INDEX prod_id_material_index ON material USING btree (prod_id);

ALTER TABLE material ADD CONSTRAINT fk_material_prod_id FOREIGN KEY (prod_id) REFERENCES products(prod_id) MATCH FULL;
ALTER TABLE material ADD CONSTRAINT fk_material_pe_id FOREIGN KEY (pe_id) REFERENCES persons(pe_id) MATCH FULL;
ALTER TABLE material ADD CONSTRAINT fk_material_prj_id FOREIGN KEY (prj_id) REFERENCES projects(prj_id) MATCH FULL;
ALTER TABLE material ADD CONSTRAINT fk_material_bill_id FOREIGN KEY (bill_id) REFERENCES bills(bill_id) MATCH FULL;

alter table lineitems add column mat_id bigint;
ALTER TABLE lineitems ADD CONSTRAINT fk_lineitems_mat_id FOREIGN KEY (mat_id) REFERENCES material(mat_id) MATCH FULL;
CREATE INDEX mat_id_lineitems_index ON lineitems USING btree (mat_id);

alter table operationcat add column opcat_hourlyrate numeric(12,2);


CREATE SEQUENCE "projects_hourlyrates_phr_id_seq";

CREATE TABLE "projects_hourlyrates" (
	"phr_id" bigint DEFAULT nextval('projects_hourlyrates_phr_id_seq'::text) NOT NULL,
        "phr_lastmod" timestamp without time zone DEFAULT now() NOT NULL,
	"pe_id_lastmod" bigint NOT NULL,
	"prj_id" bigint NOT NULL,
        "pe_id" bigint,
	"opcat_id" bigint NOT NULL,
        "phr_hourlyrate" numeric(12,2) NOT NULL,
	Constraint "projects_hourlyrates_pkey" Primary Key ("phr_id")
);

CREATE UNIQUE INDEX projects_hourlyrates_prj_pe_opcat ON projects_hourlyrates USING btree (prj_id, pe_id, opcat_id);

ALTER TABLE projects_hourlyrates ADD CONSTRAINT fk_projects_hourlyrates_pe_id_lastmod FOREIGN KEY (pe_id_lastmod) REFERENCES persons(pe_id) MATCH FULL;
ALTER TABLE projects_hourlyrates ADD CONSTRAINT fk_projects_hourlyrates_pe_id FOREIGN KEY (pe_id) REFERENCES persons(pe_id) MATCH FULL;
ALTER TABLE projects_hourlyrates ADD CONSTRAINT fk_projects_hourlyrates_prj_id FOREIGN KEY (prj_id) REFERENCES projects(prj_id) MATCH FULL;
ALTER TABLE projects_hourlyrates ADD CONSTRAINT fk_projects_hourlyrates_opcat_id FOREIGN KEY (opcat_id) REFERENCES operationcat(opcat_id) MATCH FULL;


drop view v_summary_notbilledhours;

CREATE VIEW v_summary_notbilledhours AS
 SELECT p.cpn_id,
        cpn_name,
        p.prj_id,
        prj_title,
        SUM(op_duration) as prj_duration,
        SUM(case when (ph.phr_hourlyrate IS NOT NULL) then ph.phr_hourlyrate ELSE case when prjmem_hourlyrate IS NOT NULL THEN prjmem_hourlyrate ELSE phn.phr_hourlyrate END END * (cast(op_duration AS FLOAT)/ 60))  AS prj_amount,
        to_char(cast(min(op_timestamp_start) AS abstime), 'yyyy-mm-dd hh:mi') AS op_min_start,
        to_char(cast(max(op_timestamp_end) AS abstime), 'yyyy-mm-dd hh:mi') AS op_max_end
        FROM projects p
        LEFT JOIN operations o ON o.prj_id = p.prj_id
        LEFT JOIN project_members pm ON (pm.prj_id = o.prj_id AND pm.pe_id = o.pe_id)
        LEFT JOIN companies c ON c.cpn_id = p.cpn_id
        LEFT JOIN projects_hourlyrates ph ON (ph.opcat_id = o.opcat_id and ph.prj_id = o.prj_id AND ph.pe_id = o.pe_id)
        LEFT JOIN projects_hourlyrates phn ON (phn.opcat_id = o.opcat_id and phn.prj_id = o.prj_id AND phn.pe_id IS NULL)
        WHERE (prj_billabletype IS NULL OR prj_billabletype = 0)
        AND (o.bill_id IS NULL OR o.bill_id = 0)
        AND (op_billabletype IS NULL OR op_billabletype = 0)
        GROUP BY p.cpn_id, cpn_name, p.prj_id, prj_title
        ORDER BY cpn_name, prj_title;


DROP VIEW v_summary_notbilledhours_bycustomer;

create or replace view v_summary_notbilledhours_bycustomer as
SELECT p.cpn_id, cpn_name, sum(op_duration) AS prj_duration,
        SUM(case when (ph.phr_hourlyrate IS NOT NULL) then ph.phr_hourlyrate ELSE case when prjmem_hourlyrate IS NOT NULL THEN prjmem_hourlyrate ELSE phn.phr_hourlyrate END END * (cast(op_duration AS FLOAT)/ 60))  AS prj_amount,
        to_char(min(op_timestamp_start)::abstime::timestamp with time zone, 'yyyy-mm-dd hh:mi'::text) AS op_min_start,
        to_char(max(op_timestamp_end)::abstime::timestamp with time zone, 'yyyy-mm-dd hh:mi'::text) AS op_max_end
        FROM projects p
        LEFT JOIN operations o ON o.prj_id = p.prj_id
        LEFT JOIN project_members pm ON pm.prj_id = o.prj_id AND pm.pe_id = o.pe_id
        LEFT JOIN companies c ON c.cpn_id = p.cpn_id
        LEFT JOIN projects_hourlyrates ph ON (ph.opcat_id = o.opcat_id and ph.prj_id = o.prj_id AND ph.pe_id = o.pe_id)
        LEFT JOIN projects_hourlyrates phn ON (phn.opcat_id = o.opcat_id and phn.prj_id = o.prj_id AND phn.pe_id IS NULL)
        WHERE (prj_billabletype IS NULL OR prj_billabletype = 0)
        AND (o.bill_id IS NULL OR o.bill_id = 0)
        AND (op_billabletype IS NULL OR op_billabletype = 0)
        GROUP BY p.cpn_id, cpn_name
        ORDER BY cpn_name;


INSERT INTO config (cfg_key, cfg_value) values ('SORT_PROJECTS', 18);
INSERT INTO config (cfg_key, cfg_value) values ('SORT_OPERATIONS', 2);
INSERT INTO config (cfg_key, cfg_value) values ('SORT_COMPANIES', 51);
INSERT INTO config (cfg_key, cfg_value) values ('SORT_PERSONS', 31);
INSERT INTO config (cfg_key, cfg_value) values ('RECORDS_PERPAGE', 20);
INSERT INTO config (cfg_key, cfg_value) values ('SITENAME', 'phpaga');

UPDATE config SET cfg_value = '0.9' WHERE cfg_key = 'VERSION_DB';
