Typica is a free program for professional coffee roasters. https://typica.us
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. <window id="navwindow">
  2. <layout type="horizontal">
  3. <layout type="vertical">
  4. <layout type="grid">
  5. <row>
  6. <column>
  7. <button name="Configure Roasters" id="configure" type="push" />
  8. </column>
  9. </row>
  10. <row>
  11. <column>
  12. <button name="Roasting Schedule" id="schedule" type="push" />
  13. </column>
  14. </row>
  15. <row>
  16. <column>
  17. <sqldrop id="machineselector" />
  18. </column>
  19. <column>
  20. <button name="Roast Coffee" id="roast" type="push" />
  21. </column>
  22. </row>
  23. <row>
  24. <column>
  25. <button name="Manual Roasting Log Entry" id="manual" type="push" />
  26. </column>
  27. </row>
  28. <row>
  29. <column>
  30. <button name="Purchase Green Coffee" id="green" type="push" />
  31. </column>
  32. </row>
  33. <row>
  34. <column>
  35. <button name="Manage Roasted Coffee Items" id="newroasted" type="push" />
  36. </column>
  37. </row>
  38. <row>
  39. <column>
  40. <button name="Edit Roasting Specification" id="roastspec" type="push" />
  41. </column>
  42. </row>
  43. <row>
  44. <column>
  45. <button name="Update Inventory" id="inventory" type="push" />
  46. </column>
  47. </row>
  48. <row>
  49. <column>
  50. <button name="New Cupping Session" id="createcupping" type="push" />
  51. </column>
  52. </row>
  53. <row>
  54. <column>
  55. <button name="Join Cupping Session" id="joincupping" type="push" />
  56. </column>
  57. </row>
  58. <row>
  59. <column>
  60. <button name="Summarize Cupping Session" id="sumcupping" type="push" />
  61. </column>
  62. </row>
  63. <row>
  64. <column>
  65. <button name="View Target Roast Profiles" id="profilehistory" type="push" />
  66. </column>
  67. </row>
  68. <row>
  69. <column>
  70. <button name="Import Target Roast Profiles" id="target" type="push" />
  71. </column>
  72. </row>
  73. <row>
  74. <column>
  75. <button name="Enter Green Coffee Sales" id="greensales" type="push" />
  76. </column>
  77. </row>
  78. </layout>
  79. <stretch />
  80. </layout>
  81. <webview id="dashboard" stretch="1" />
  82. </layout>
  83. <menu name="Reports" type="reports" src="Reports" />
  84. <menu name="Database">
  85. <item id="resetconnection">Forget Connection Details</item>
  86. </menu>
  87. <menu name="Users">
  88. <item id="switchuser">Switch User</item>
  89. <item id="createuser">Create New Users</item>
  90. </menu>
  91. <program>
  92. var window = this;
  93. var navigationwindow = window;
  94. window.loggingWindow = undefined;
  95. var roasterlist = findChildObject(this, 'machineselector');
  96. var model = new DeviceTreeModel;
  97. roasterlist.setModel(model);
  98. roasterlist.currentIndex = QSettings.value("machineSelection", 0);
  99. roasterlist['currentIndexChanged(int)'].connect(function() {
  100. QSettings.setValue("machineSelection", roasterlist.currentIndex);
  101. });
  102. var resetdbconnection = findChildObject(this, 'resetconnection');
  103. resetdbconnection.triggered.connect(function() {
  104. QSettings.setValue("database/exists", false);
  105. QSettings.setValue("database/hostname", "");
  106. QSettings.setValue("database/dbname", "");
  107. QSettings.setValue("database/user", "");
  108. QSettings.setValue("database/password", "");
  109. });
  110. var schedule = findChildObject(this, 'schedule');
  111. schedule.clicked.connect(function() {
  112. createWindow("schedule");
  113. });
  114. var manual = findChildObject(this, 'manual');
  115. manual.clicked.connect(function() {
  116. createWindow("manualLogEntry");
  117. });
  118. var profilehistory = findChildObject(this, 'profilehistory');
  119. profilehistory.clicked.connect(function() {
  120. createWindow("profilehistory");
  121. });
  122. var greensalesbutton = findChildObject(this, 'greensales');
  123. greensalesbutton.clicked.connect(function() {
  124. createWindow("greensales");
  125. });
  126. var sumcup = findChildObject(this, 'sumcupping');
  127. sumcup.clicked.connect(function() {
  128. var sessionlist = createWindow("finsessionlist");
  129. sessionlist.windowTitle = TTR("navwindow", "Typica - Summarize Cupping Session");
  130. });
  131. var ncsbutton = findChildObject(this, 'createcupping')
  132. ncsbutton.clicked.connect(function() {
  133. var ncswindow = createWindow("session");
  134. ncswindow.windowTitle = TTR("navwindow", "Typica - New Cupping Session");
  135. });
  136. var jcsbutton = findChildObject(this, 'joincupping')
  137. jcsbutton.clicked.connect(function() {
  138. var jcswindow = createWindow("sessionlist");
  139. jcswindow.windowTitle = TTR("navwindow", "Typica - Join Cupping Session");
  140. });
  141. /*
  142. var nrbutton = findChildObject(this, 'newroaster');
  143. nrbutton.clicked.connect(function() {
  144. var nrwindow = createWindow("newroaster");
  145. nrwindow.windowTitle = TTR("navwindow", "Typica - New Roaster");
  146. });
  147. */
  148. var inventory = findChildObject(this, 'inventory');
  149. inventory.clicked.connect(function() {
  150. var invwin = createWindow("inventory");
  151. invwin.windowTitle = TTR("navwindow", "Typica - Inventory");
  152. });
  153. var roastspecbutton = findChildObject(this, 'roastspec');
  154. roastspecbutton.clicked.connect(function() {
  155. var specwindow = createWindow("roastspec");
  156. });
  157. var gbutton = findChildObject(this, 'green');
  158. gbutton.clicked.connect(function() {
  159. var purchasewindow = createWindow("purchase");
  160. });
  161. var nrbutton = findChildObject(this, 'newroasted');
  162. nrbutton.clicked.connect(function() {
  163. var nrwindow = createWindow("newroasted");
  164. nrwindow.windowTitle = TTR("navwindow", "Manage Roasted Coffee Items");
  165. });
  166. var importb = findChildObject(this, 'target');
  167. importb.clicked.connect(function() {
  168. var importWindow = createWindow("importTargets");
  169. importWindow.windowTitle = TTR("navwindow", "Typica - Import Target Roast Profiles");
  170. });
  171. var roastbutton = findChildObject(this, 'roast');
  172. roastbutton.clicked.connect(function() {
  173. if(typeof(window.loggingWindow) == "undefined")
  174. {
  175. window.loggingWindow = createWindow("basicWindow");
  176. window.loggingWindow.windowTitle = "Typica [*]";
  177. window.loggingWindow.navigationWindow = window;
  178. }
  179. else
  180. {
  181. window.loggingWindow.raise();
  182. window.loggingWindow.activateWindow();
  183. }
  184. });
  185. var configurebutton = findChildObject(this, 'configure');
  186. configurebutton.clicked.connect(function() {
  187. var confwindow = new SettingsWindow;
  188. confwindow.show();
  189. });
  190. <![CDATA[
  191. var DBCreateBase = function() {
  192. var query = new QSqlQuery();
  193. query.exec("CREATE TABLE IF NOT EXISTS certifications (item bigint NOT NULL, certification text NOT NULL)");
  194. query.exec("CREATE TABLE IF NOT EXISTS cupping_samples (session bigint NOT NULL, sample text NOT NULL, position bigint NOT NULL, type text NOT NULL, \"time\" timestamp without time zone, machine bigint, point text, item bigint)");
  195. query.exec("CREATE TABLE cupping_sessions (id bigserial NOT NULL, event text, name text NOT NULL, \"time\" timestamp without time zone NOT NULL, blind boolean NOT NULL, open boolean NOT NULL, note text)");
  196. query.exec("CREATE TABLE IF NOT EXISTS cuppingforms (session bigint NOT NULL, sample text NOT NULL, position bigint NOT NULL, grader text, finalscore numeric, notes text, serialization text)");
  197. query.exec("CREATE TABLE IF NOT EXISTS cuppingform_t1 (aroma numeric, flavor numeric, aftertaste numeric, acidity numeric, body numeric, uniformity numeric, balance numeric, cleancup numeric, sweetness numeric, overall numeric, total numeric) INHERITS (cuppingforms)");
  198. query.exec("CREATE TABLE IF NOT EXISTS invoices (id bigserial PRIMARY KEY NOT NULL, invoice text, vendor text NOT NULL, \"time\" timestamp without time zone NOT NULL)");
  199. query.exec("CREATE TABLE IF NOT EXISTS invoice_items (invoice_id bigint NOT NULL, record_type text NOT NULL, item_id bigint, description text NOT NULL, cost numeric NOT NULL)");
  200. query.exec("CREATE TABLE IF NOT EXISTS transactions (\"time\" timestamp without time zone NOT NULL, item bigint NOT NULL)");
  201. query.exec("CREATE TABLE IF NOT EXISTS inventory (quantity numeric NOT NULL) INHERITS (transactions)");
  202. query.exec("CREATE TABLE IF NOT EXISTS loss (quantity numeric NOT NULL, reason text) INHERITS (transactions)");
  203. query.exec("CREATE TABLE IF NOT EXISTS make (quantity numeric NOT NULL) INHERITS (transactions)");
  204. query.exec("CREATE TABLE IF NOT EXISTS purchase (quantity numeric NOT NULL, cost numeric NOT NULL, vendor text NOT NULL) INHERITS (transactions)");
  205. query.exec("CREATE TABLE IF NOT EXISTS sale (quantity numeric NOT NULL, customer text) INHERITS (transactions)");
  206. query.exec("CREATE TABLE IF NOT EXISTS use (quantity numeric NOT NULL) INHERITS (transactions)");
  207. query.exec("CREATE VIEW all_transactions AS ((((SELECT purchase.\"time\", purchase.item, purchase.quantity, purchase.cost, purchase.vendor, NULL::unknown AS reason, NULL::unknown AS customer, 'PURCHASE' AS type FROM purchase UNION SELECT use.\"time\", use.item, use.quantity, NULL::unknown AS cost, NULL::unknown AS vendor, NULL::unknown AS reason, NULL::unknown AS customer, 'USE' AS type FROM use) UNION SELECT inventory.\"time\", inventory.item, inventory.quantity, NULL::unknown AS cost, NULL::unknown AS vendor, NULL::unknown AS reason, NULL::unknown AS customer, 'INVENTORY' AS type FROM inventory) UNION SELECT loss.\"time\", loss.item, loss.quantity, NULL::unknown AS cost, NULL::unknown AS vendor, loss.reason, NULL::unknown AS customer, 'LOSS' AS type FROM loss) UNION SELECT make.\"time\", make.item, make.quantity, NULL::unknown AS cost, NULL::unknown AS vendor, NULL::unknown AS reason, NULL::unknown AS customer, 'MAKE' AS type FROM make) UNION SELECT sale.\"time\", sale.item, sale.quantity, NULL::unknown AS cost, NULL::unknown AS vendor, NULL::unknown AS reason, sale.customer, 'SALE' AS type FROM sale");
  208. query.exec("CREATE FUNCTION time_range(bigint) RETURNS integer AS $$ BEGIN IF (SELECT quantity FROM items WHERE id = $1) > 0 THEN RETURN (SELECT current_date - min(time)::date + 1 FROM use WHERE item = $1); ELSE RETURN (SELECT max(time)::date - min(time)::date + 1 FROM use WHERE item = $1); END IF; END; $$ LANGUAGE plpgsql STRICT");
  209. query.exec("CREATE TABLE IF NOT EXISTS items(id bigint NOT NULL, name text NOT NULL, reference text, unit text NOT NULL, quantity numeric DEFAULT 0, category text)");
  210. query.exec("CREATE SEQUENCE items_id_seq INCREMENT BY 1 NO MAXVALUE NO MINVALUE CACHE 1");
  211. query.exec("CREATE TABLE IF NOT EXISTS coffees(origin text NOT NULL, region text, producer text, grade text, milling text, drying text) INHERITS (items)");
  212. query.exec("CREATE VIEW coffee_history AS SELECT coffees.id, coffees.name, coffees.origin, coffees.quantity AS stock, (SELECT sum(use.quantity) AS sum FROM use WHERE (use.item = coffees.id)) AS used, time_range(coffees.id) AS \"interval\", ((SELECT (sum(use.quantity) / (time_range(use.item))::numeric) FROM use WHERE (use.item = coffees.id) GROUP BY use.item))::numeric(10,2) AS rate, (SELECT (('now'::text)::date + ((coffees.quantity / (SELECT (sum(use.quantity) / (time_range(use.item))::numeric) FROM use WHERE (use.item = coffees.id) GROUP BY use.item)))::integer)) AS \"out\" FROM coffees WHERE (coffees.id IN (SELECT use.item FROM use)) ORDER BY coffees.origin");
  213. query.exec("CREATE TABLE IF NOT EXISTS current_items (item bigint NOT NULL)");
  214. query.exec("CREATE TABLE IF NOT EXISTS decaf_coffees (decaf_method text NOT NULL) INHERITS (coffees)");
  215. query.exec("CREATE TABLE IF NOT EXISTS files (id bigint NOT NULL, name text NOT NULL, type text NOT NULL, note text, file bytea NOT NULL)");
  216. query.exec("CREATE TABLE IF NOT EXISTS item_files(\"time\" timestamp without time zone NOT NULL, item bigint NOT NULL, files bigint[] NOT NULL)");
  217. query.exec("CREATE TYPE item_transaction_with_balance AS (\"time\" timestamp without time zone, item bigint, quantity numeric, cost numeric, vendor text, reason text, customer text, type text, balance numeric)");
  218. query.exec("CREATE TABLE IF NOT EXISTS lb_bag_conversion (item bigint NOT NULL, conversion numeric NOT NULL)");
  219. query.exec("CREATE TABLE IF NOT EXISTS machine (id bigint NOT NULL, name text NOT NULL)");
  220. query.exec("CREATE VIEW regular_coffees AS SELECT coffees.id, coffees.name, coffees.reference, coffees.unit, coffees.quantity, coffees.category, coffees.origin, coffees.region, coffees.producer, coffees.grade, coffees.milling, coffees.drying FROM coffees WHERE (NOT (coffees.id IN (SELECT decaf_coffees.id FROM decaf_coffees)))");
  221. query.exec("CREATE TABLE IF NOT EXISTS roasting_log (\"time\" timestamp without time zone NOT NULL, unroasted_id bigint[], unroasted_quantity numeric[], unroasted_total_quantity numeric, roasted_id bigint, roasted_quantity numeric, transaction_type text NOT NULL, annotation text, machine bigint NOT NULL, duration interval, approval boolean, humidity numeric, barometric numeric, indoor_air numeric, outdoor_air numeric, files bigint[])");
  222. query.exec("CREATE VIEW short_log AS SELECT roasting_log.\"time\", (SELECT items.name FROM items WHERE (items.id = roasting_log.roasted_id)) AS name, roasting_log.unroasted_total_quantity, roasting_log.roasted_quantity, ((((roasting_log.unroasted_total_quantity - roasting_log.roasted_quantity) / roasting_log.unroasted_total_quantity) * (100)::numeric))::numeric(12,2) AS weight_loss, roasting_log.duration FROM roasting_log ORDER BY roasting_log.\"time\"");
  223. query.exec("CREATE FUNCTION add_inventory() RETURNS trigger AS $$ BEGIN UPDATE items SET quantity = quantity + NEW.quantity WHERE id = NEW.item; RETURN NEW; END; $$ LANGUAGE plpgsql");
  224. query.exec("CREATE FUNCTION bags_in_stock(bigint) RETURNS numeric AS $_$SELECT quantity / (SELECT conversion FROM lb_bag_conversion WHERE item = id) FROM items WHERE id = $1;$_$ LANGUAGE sql IMMUTABLE STRICT");
  225. query.exec("CREATE FUNCTION log_use() RETURNS trigger AS $$ DECLARE i integer := array_lower(NEW.unroasted_id, 1); u integer := array_upper(NEW.unroasted_id, 1); BEGIN WHILE i <= u LOOP INSERT INTO use VALUES(NEW.time, NEW.unroasted_id[i], NEW.unroasted_quantity[i]); i := i + 1; END LOOP; RETURN NEW; END; $$ LANGUAGE plpgsql");
  226. query.exec("CREATE FUNCTION replace_inventory() RETURNS trigger AS $$ BEGIN UPDATE items SET quantity = NEW.quantity WHERE id = NEW.item; RETURN NEW; END; $$ LANGUAGE plpgsql");
  227. query.exec("CREATE FUNCTION subtract_inventory() RETURNS trigger AS $$ BEGIN UPDATE items SET quantity = quantity - NEW.quantity WHERE id = NEW.item; RETURN NEW; END; $$ LANGUAGE plpgsql");
  228. query.exec("CREATE SEQUENCE files_id_seq START WITH 1 INCREMENT BY 1 NO MAXVALUE NO MINVALUE CACHE 1");
  229. query.exec("ALTER TABLE files ALTER COLUMN id SET DEFAULT nextval('files_id_seq'::regclass)");
  230. query.exec("ALTER TABLE items ALTER COLUMN id SET DEFAULT nextval('items_id_seq'::regclass)");
  231. query.exec("ALTER TABLE ONLY files ADD CONSTRAINT file_pkey PRIMARY KEY (id)");
  232. query.exec("ALTER TABLE ONLY items ADD CONSTRAINT items_pkey PRIMARY KEY (id)");
  233. query.exec("ALTER TABLE ONLY lb_bag_conversion ADD CONSTRAINT lb_bag_conversion_item_key UNIQUE (item)");
  234. query.exec("ALTER TABLE ONLY roasting_log ADD CONSTRAINT roasting_log_pkey PRIMARY KEY (\"time\", machine)");
  235. query.exec("CREATE INDEX itemcategories ON items USING btree (category)");
  236. query.exec("CREATE INDEX itemnames ON items USING btree (name)");
  237. query.exec("CREATE INDEX roasting_log_index ON roasting_log USING btree (\"time\")");
  238. query.exec("CREATE INDEX transactionitems ON transactions USING btree (item)");
  239. query.exec("CREATE INDEX transactiontimes ON transactions USING btree (\"time\")");
  240. query.exec("CREATE TRIGGER add_inventory_trigger AFTER INSERT ON purchase FOR EACH ROW EXECUTE PROCEDURE add_inventory()");
  241. query.exec("CREATE TRIGGER add_inventory_trigger AFTER INSERT ON make FOR EACH ROW EXECUTE PROCEDURE add_inventory()");
  242. query.exec("CREATE TRIGGER log_use_trigger AFTER INSERT ON roasting_log FOR EACH ROW EXECUTE PROCEDURE log_use()");
  243. query.exec("CREATE TRIGGER replace_inventory_trigger AFTER INSERT ON inventory FOR EACH ROW EXECUTE PROCEDURE replace_inventory()");
  244. query.exec("CREATE TRIGGER subtract_inventory_trigger AFTER INSERT ON loss FOR EACH ROW EXECUTE PROCEDURE subtract_inventory()");
  245. query.exec("CREATE TRIGGER subtract_inventory_trigger AFTER INSERT ON sale FOR EACH ROW EXECUTE PROCEDURE subtract_inventory()");
  246. query.exec("CREATE TRIGGER subtract_inventory_trigger AFTER INSERT ON use FOR EACH ROW EXECUTE PROCEDURE subtract_inventory()");
  247. query.exec("ALTER TABLE ONLY item_files ADD CONSTRAINT item_files_item_fkey FOREIGN KEY (item) REFERENCES items(id)");
  248. query.exec("ALTER TABLE ONLY transactions ADD CONSTRAINT transactions_item_fkey FOREIGN KEY (item) REFERENCES items(id)");
  249. query.exec("INSERT INTO TypicaFeatures (feature, enabled, version) VALUES('base-features', TRUE, 1)");
  250. query = query.invalidate();
  251. };
  252. /* Some changes to the database are required for sample roasting features in
  253. Typica 1.6 and later. */
  254. var DBCreateSampleRoasting = function() {
  255. var query = new QSqlQuery;
  256. query.exec("CREATE TABLE IF NOT EXISTS item_attributes (id bigserial PRIMARY KEY NOT NULL, name text NOT NULL)");
  257. query.exec("CREATE TABLE IF NOT EXISTS coffee_sample_items(arrival timestamp without time zone, vendor text, attribute_ids bigint[], attribute_values text[], item_id bigint) INHERITS (items)");
  258. query.exec("INSERT INTO TypicaFeatures (feature, enabled, version) VALUES('sample-roasting', TRUE, 1)");
  259. query = query.invalidate();
  260. };
  261. /* Some changes to the database are required to log who performed what tasks.
  262. This adds logging for all transaction types and also for the roasting log.*/
  263. var DBUpdateMultiUser = function() {
  264. var query = new QSqlQuery;
  265. query.exec("ALTER TABLE transactions ADD COLUMN person text DEFAULT NULL");
  266. query.exec("ALTER TABLE roasting_log ADD COLUMN person text DEFAULT NULL");
  267. query.exec("CREATE OR REPLACE FUNCTION log_session_user() RETURNS trigger AS $$ BEGIN NEW.person := session_user; RETURN NEW; END; $$ LANGUAGE plpgsql");
  268. query.exec("CREATE TRIGGER log_person BEFORE INSERT ON inventory FOR EACH ROW EXECUTE PROCEDURE log_session_user()");
  269. query.exec("CREATE TRIGGER log_person BEFORE INSERT ON loss FOR EACH ROW EXECUTE PROCEDURE log_session_user()");
  270. query.exec("CREATE TRIGGER log_person BEFORE INSERT ON make FOR EACH ROW EXECUTE PROCEDURE log_session_user()");
  271. query.exec("CREATE TRIGGER log_person BEFORE INSERT ON purchase FOR EACH ROW EXECUTE PROCEDURE log_session_user()");
  272. query.exec("CREATE TRIGGER log_person BEFORE INSERT ON sale FOR EACH ROW EXECUTE PROCEDURE log_session_user()");
  273. query.exec("CREATE TRIGGER log_person BEFORE INSERT ON use FOR EACH ROW EXECUTE PROCEDURE log_session_user()");
  274. query.exec("CREATE TRIGGER log_person BEFORE INSERT ON roasting_log FOR EACH ROW EXECUTE PROCEDURE log_session_user()");
  275. query.exec("UPDATE TypicaFeatures SET version = 2 WHERE feature = 'base-features'");
  276. query = query.invalidate();
  277. };
  278. /* Bug fix and optimization for item_history */
  279. var DBUpdateHistory = function() {
  280. var query = new QSqlQuery;
  281. query.exec("CREATE TYPE transaction_type AS (type text, quantity numeric)");
  282. query.exec("CREATE FUNCTION update_balance(numeric, transaction_type) RETURNS numeric AS $$ BEGIN CASE $2.type WHEN 'PURCHASE', 'MAKE' THEN RETURN $1 + $2.quantity; WHEN 'INVENTORY' THEN RETURN $2.quantity; WHEN 'USE', 'SALE', 'LOSS' THEN RETURN $1 - $2.quantity; END CASE; END; $$ LANGUAGE plpgsql STRICT");
  283. query.exec("CREATE AGGREGATE transaction_balance (BASETYPE = transaction_type, SFUNC = update_balance, STYPE = numeric, INITCOND = '0')");
  284. query.exec("CREATE OR REPLACE FUNCTION item_history(bigint) RETURNS SETOF item_transaction_with_balance AS $$ SELECT time, item, quantity, cost, vendor, reason, customer, type, transaction_balance((type, quantity)::transaction_type) OVER (PARTITION BY item ORDER BY time ASC) AS balance FROM all_transactions WHERE item = $1; $$ LANGUAGE SQL");
  285. query.exec("DROP FUNCTION calculate_inventory_balance()");
  286. query = query.invalidate();
  287. };
  288. /* Asynchronous notifications */
  289. var DBUpdateNotifications = function() {
  290. var query = new QSqlQuery;
  291. query.exec("CREATE OR REPLACE FUNCTION notify_roasting_log_change() RETURNS TRIGGER AS $$ BEGIN NOTIFY RoastingLogChange; RETURN NULL; END; $$ LANGUAGE plpgsql");
  292. query.exec("CREATE TRIGGER notify_roasting_log_change AFTER INSERT OR UPDATE ON roasting_log FOR EACH STATEMENT EXECUTE PROCEDURE notify_roasting_log_change()");
  293. query = query.invalidate();
  294. };
  295. /* Update trigger functions to make column names explicit */
  296. var DBUpdateTriggers = function() {
  297. var query = new QSqlQuery;
  298. query.exec("CREATE OR REPLACE FUNCTION log_make_update() RETURNS trigger AS $$ BEGIN IF NEW.roasted_quantity <> OLD.roasted_quantity AND NEW.roasted_quantity IS NOT NULL THEN INSERT INTO make (time, item, quantity) VALUES(NEW.time, NEW.roasted_id, NEW.roasted_quantity); END IF; RETURN NEW; END; $$ LANGUAGE plpgsql");
  299. query.exec("UPDATE TypicaFeatures SET version = 4 WHERE feature = 'base-features'");
  300. };
  301. var DBUpdateReminders = function() {
  302. var query = new QSqlQuery;
  303. query.exec("CREATE TABLE IF NOT EXISTS reminders (id bigserial PRIMARY KEY NOT NULL, reminder text NOT NULL)");
  304. query.exec("UPDATE TypicaFeatures SET version = 5 WHERE feature = 'base-features'");
  305. query = query.invalidate();
  306. };
  307. var DBUpdateSpecification = function() {
  308. var query = new QSqlQuery;
  309. query.exec("CREATE TABLE IF NOT EXISTS roasting_specification (\"time\" timestamp without time zone NOT NULL, item bigint NOT NULL, loss numeric, tolerance numeric, notes text)");
  310. query.exec("UPDATE TypicaFeatures SET version = 6 WHERE feature = 'base-features'");
  311. query = query.invalidate();
  312. };
  313. /* Updates for Typica version 1.8 */
  314. var DBUpdate18 = function() {
  315. var query = new QSqlQuery;
  316. /* Create a table for Typica users login data */
  317. query.exec("CREATE TABLE IF NOT EXISTS typica_users(name TEXT PRIMARY KEY NOT NULL, password TEXT, active boolean NOT NULL, auto_login boolean NOT NULL)");
  318. /* Update session user logging to only use the database user when a Typica user is not explicitly provided. This maintains compatibility for mixed version use. */
  319. query.exec("CREATE OR REPLACE FUNCTION log_session_user() RETURNS trigger AS $$ BEGIN IF NEW.person IS NULL THEN NEW.person := session_user; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql");
  320. query.exec("CREATE OR REPLACE FUNCTION log_use() RETURNS trigger AS $$ DECLARE i integer := array_lower(NEW.unroasted_id, 1); u integer := array_upper(NEW.unroasted_id, 1); BEGIN IF NEW.transaction_type = 'ROAST' THEN WHILE i <= u LOOP INSERT INTO use (time, item, quantity, person) VALUES(NEW.time, NEW.unroasted_id[i], NEW.unroasted_quantity[i], NEW.person); i := i + 1; END LOOP; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql");
  321. query.exec("CREATE OR REPLACE FUNCTION log_make() RETURNS trigger AS $$ BEGIN IF NEW.roasted_quantity IS NOT NULL THEN INSERT INTO make (time, item, quantity, person) VALUES(NEW.time, NEW.roasted_id, NEW.roasted_quantity, NEW.person); END IF; RETURN NEW; END; $$ LANGUAGE plpgsql");
  322. query.exec("CREATE TABLE IF NOT EXISTS sample_roast_profiles(\"time\" timestamp without time zone NOT NULL, profile_name TEXT NOT NULL, file bigint NOT NULL)");
  323. query.exec("UPDATE TypicaFeatures SET version = 7 WHERE feature = 'base-features'");
  324. query = query.invalidate();
  325. };
  326. /* Updates for Typica version 1.9 */
  327. var DBUpdate19 = function() {
  328. var query = new QSqlQuery;
  329. query.exec("ALTER TABLE roasting_specification ADD COLUMN spec jsonb");
  330. query.exec("ALTER TABLE roasting_log ADD COLUMN additional_data jsonb");
  331. query.exec("CREATE TABLE IF NOT EXISTS scheduled_roasts (id bigserial PRIMARY KEY, machine bigint, \"time\" timestamp without time zone, data jsonb NOT NULL)");
  332. query.exec("CREATE OR REPLACE FUNCTION notify_scheduled_roasts_changed() RETURNS trigger AS $$ BEGIN NOTIFY ScheduledRoastsChange; RETURN NULL; END; $$ LANGUAGE plpgsql");
  333. query.exec("CREATE TRIGGER notify_scheduled_roasts_changed AFTER INSERT OR UPDATE OR DELETE OR TRUNCATE ON scheduled_roasts FOR EACH STATEMENT EXECUTE PROCEDURE notify_scheduled_roasts_changed()");
  334. query.exec("CREATE OR REPLACE FUNCTION notify_transactions_changed() RETURNS trigger AS $$ BEGIN NOTIFY TransactionsChange; RETURN NULL; END; $$ LANGUAGE plpgsql");
  335. query.exec("CREATE TRIGGER notify_transactions_changed AFTER INSERT OR UPDATE OR DELETE ON transactions FOR EACH STATEMENT EXECUTE PROCEDURE notify_transactions_changed()");
  336. query.exec("CREATE OR REPLACE FUNCTION notify_purchase_changed() RETURNS trigger AS $$ BEGIN NOTIFY PurchaseChange; RETURN NULL; END; $$ LANGUAGE plpgsql");
  337. query.exec("CREATE TRIGGER notify_purchase_changed AFTER INSERT OR UPDATE OR DELETE ON purchase FOR EACH STATEMENT EXECUTE PROCEDURE notify_purchase_changed()");
  338. query.exec("CREATE OR REPLACE FUNCTION notify_sale_changed() RETURNS trigger AS $$ BEGIN NOTIFY SaleChange; RETURN NULL; END; $$ LANGUAGE plpgsql");
  339. query.exec("CREATE TRIGGER notify_sale_changed AFTER INSERT OR UPDATE OR DELETE ON sale FOR EACH STATEMENT EXECUTE PROCEDURE notify_sale_changed()");
  340. query.exec("CREATE OR REPLACE FUNCTION notify_invoices_changed() RETURNS trigger AS $$ BEGIN NOTIFY InvoicesChange; RETURN NULL; END; $$ LANGUAGE plpgsql");
  341. query.exec("CREATE TRIGGER nofify_invoices_changed AFTER INSERT OR UPDATE OR DELETE ON invoices FOR EACH STATEMENT EXECUTE PROCEDURE notify_invoices_changed()");
  342. query.exec("CREATE TRIGGER notify_invoices_changed AFTER INSERT OR UPDATE OR DELETE ON invoice_items FOR EACH STATEMENT EXECUTE PROCEDURE notify_invoices_changed()");
  343. query.exec("CREATE TRIGGER notify_transactions_changed AFTER INSERT OR UPDATE OR DELETE ON inventory FOR EACH STATEMENT EXECUTE PROCEDURE notify_transactions_changed()");
  344. query.exec("CREATE TRIGGER notify_transactions_changed AFTER INSERT OR UPDATE OR DELETE ON loss FOR EACH STATEMENT EXECUTE PROCEDURE notify_transactions_changed()");
  345. query.exec("CREATE TRIGGER notify_transactions_changed AFTER INSERT OR UPDATE OR DELETE ON make FOR EACH STATEMENT EXECUTE PROCEDURE notify_transactions_changed()");
  346. query.exec("CREATE TRIGGER notify_transactions_changed AFTER INSERT OR UPDATE OR DELETE ON purchase FOR EACH STATEMENT EXECUTE PROCEDURE notify_transactions_changed()");
  347. query.exec("CREATE TRIGGER notify_transactions_changed AFTER INSERT OR UPDATE OR DELETE ON sale FOR EACH STATEMENT EXECUTE PROCEDURE notify_transactions_changed()");
  348. query.exec("CREATE TRIGGER notify_transactions_changed AFTER INSERT OR UPDATE OR DELETE ON use FOR EACH STATEMENT EXECUTE PROCEDURE notify_transactions_changed()");
  349. query.exec("CREATE OR REPLACE FUNCTION notify_reminders_changed() RETURNS trigger AS $$ BEGIN NOTIFY RemindersChange; RETURN NULL; END; $$ LANGUAGE plpgsql");
  350. query.exec("CREATE TRIGGER notify_reminders_changed AFTER INSERT OR UPDATE OR DELETE ON reminders FOR EACH STATEMENT EXECUTE PROCEDURE notify_reminders_changed()");
  351. query.exec("UPDATE TypicaFeatures SET version = 8 WHERE feature = 'base-features'");
  352. query = query.invalidate();
  353. };
  354. if(Application.databaseConnected()) {
  355. query = new QSqlQuery();
  356. /* A table keeps track of database versioning information. This
  357. table is created
  358. if required. */
  359. query.exec("CREATE TABLE IF NOT EXISTS TypicaFeatures (feature TEXT PRIMARY KEY, enabled boolean, version bigint)");
  360. query.exec("SELECT feature, enabled, version FROM TypicaFeatures WHERE feature = 'base-features'");
  361. if(query.next())
  362. {
  363. if(query.value(2) < 1)
  364. {
  365. DBCreateBase();
  366. }
  367. if(query.value(2) < 2)
  368. {
  369. DBUpdateMultiUser();
  370. DBUpdateHistory();
  371. }
  372. if(query.value(2) < 3)
  373. {
  374. DBUpdateNotifications();
  375. }
  376. if(query.value(2) < 4)
  377. {
  378. DBUpdateTriggers();
  379. }
  380. if(query.value(2) < 5)
  381. {
  382. DBUpdateReminders();
  383. }
  384. if(query.value(2) < 6)
  385. {
  386. DBUpdateSpecification();
  387. }
  388. if(query.value(2) < 7) {
  389. DBUpdate18();
  390. }
  391. if(query.value(2) < 8) {
  392. DBUpdate19();
  393. }
  394. }
  395. else
  396. {
  397. DBCreateBase();
  398. DBUpdateMultiUser();
  399. DBUpdateHistory();
  400. DBUpdateNotifications();
  401. DBUpdateTriggers();
  402. DBUpdateReminders();
  403. DBUpdateSpecification();
  404. DBUpdate18();
  405. DBUpdate19();
  406. }
  407. query.exec("SELECT feature, enabled, version FROM TypicaFeatures WHERE feature = 'sample-roasting'");
  408. if(query.next())
  409. {
  410. if(query.value(2) < 1)
  411. {
  412. DBCreateSampleRoasting();
  413. }
  414. }
  415. else
  416. {
  417. DBCreateSampleRoasting();
  418. }
  419. var promptNewUsers = true;
  420. query.exec("SELECT count(1) FROM typica_users");
  421. if(query.next()) {
  422. if(Number(query.value(0)) > 0) {
  423. promptNewUsers = false;
  424. }
  425. }
  426. if(promptNewUsers) {
  427. var newUserDialog = new NewTypicaUser();
  428. newUserDialog.exec();
  429. }
  430. if(!Application.autoLogin()) {
  431. var loginDialog = new LoginDialog();
  432. loginDialog.exec();
  433. }
  434. query = query.invalidate();
  435. }
  436. var switchuser = findChildObject(this, 'switchuser');
  437. switchuser.triggered.connect(function() {
  438. var loginDialog = new LoginDialog();
  439. loginDialog.exec();
  440. });
  441. var createuser = findChildObject(this, 'createuser');
  442. createuser.triggered.connect(function() {
  443. var newUserDialog = new NewTypicaUser();
  444. newUserDialog.exec();
  445. });
  446. var dashboard = findChildObject(this, 'dashboard');
  447. var refresh = function() {
  448. var buffer = new QBuffer;
  449. buffer.open(3);
  450. var output = new XmlWriter(buffer);
  451. output.writeStartDocument("1.0");
  452. output.writeDTD('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg.dtd">');
  453. output.writeStartElement("html");
  454. output.writeAttribute("xmlns", "http://www.w3.org/1999/xhtml");
  455. output.writeStartElement("head");
  456. output.writeStartElement("link");
  457. output.writeAttribute("rel", "stylesheet");
  458. output.writeAttribute("href", QSettings.value("config") + "/Scripts/dashboard.css");
  459. output.writeEndElement();
  460. output.writeEndElement(); // head
  461. output.writeStartElement("body");
  462. output.writeStartElement("div");
  463. output.writeAttribute("class", "container");
  464. var query = new QSqlQuery;
  465. drawReminders(output, query);
  466. drawSchedule(output, query);
  467. drawProductionTrends(output, query);
  468. drawLatest(output, query);
  469. drawRecentlyOut(output, query);
  470. drawLeastAvailable(output, query);
  471. drawUnused(output, query);
  472. drawMostRoasted(output, query);
  473. drawLeastRoasted(output, query);
  474. query = query.invalidate();
  475. output.writeEndElement(); // End of container
  476. output.writeEndElement(); // body
  477. output.writeEndElement(); // html
  478. output.writeEndDocument();
  479. dashboard.setContent(buffer);
  480. buffer.close();
  481. }
  482. var startCell = function(output, title) {
  483. output.writeStartElement("div");
  484. output.writeAttribute("class", "cell");
  485. output.writeStartElement("div");
  486. output.writeAttribute("class", "cell-wrapper");
  487. output.writeStartElement("div");
  488. output.writeAttribute("class", "cell-title");
  489. output.writeCharacters(title);
  490. output.writeEndElement();
  491. }
  492. var startStage = function(output) {
  493. output.writeStartElement("div");
  494. output.writeAttribute("class", "cell-stage");
  495. }
  496. var endStage = function(output) {
  497. output.writeEndElement();
  498. }
  499. var endCell = function(output, summary) {
  500. if(arguments.length > 1) {
  501. output.writeStartElement("div");
  502. output.writeAttribute("class", "cell-notes");
  503. output.writeCharacters(summary);
  504. output.writeEndElement();
  505. }
  506. output.writeEndElement();
  507. output.writeEndElement();
  508. }
  509. var drawReminders = function(output, query) {
  510. query.exec("SELECT id, reminder FROM reminders");
  511. e = new Array();
  512. while(query.next()) {
  513. var reminder = JSON.parse(query.value(1));
  514. reminder.dbid = query.value(0);
  515. var start_time = "" + reminder.start_year + "-" + reminder.start_month + "-" + reminder.start_day + " " + reminder.start_time;
  516. if(reminder.condition == "PRODUCTIONWEIGHT") {
  517. var convert = 1;
  518. var unittext = TTR("navwindow", " Lb");
  519. if(reminder.unit == "KG") {
  520. convert = 2.2;
  521. unittext = TTR("navwindow", " Kg");
  522. }
  523. var dq = new QSqlQuery;
  524. dq.prepare("SELECT sum(roasted_quantity)/:conversion FROM roasting_log WHERE time > :since");
  525. dq.bind(":conversion", convert);
  526. dq.bind(":since", start_time);
  527. dq.exec();
  528. dq.next();
  529. var proportion;
  530. var remain;
  531. if(reminder.value == 0 || (reminder.value < Number(dq.value(0)))) {
  532. proportion = 1;
  533. } else {
  534. proportion = Number(dq.value(0)) / reminder.value;
  535. }
  536. remain = (reminder.value - Number(dq.value(0))).toFixed(0);
  537. reminder.completion = proportion;
  538. reminder.detail = remain + unittext;
  539. dq = dq.invalidate();
  540. } else if (reminder.condition == "DAYS") {
  541. var dq = new QSqlQuery;
  542. dq.prepare("SELECT 'now'::date - :since::date");
  543. dq.bind(":since", start_time);
  544. dq.exec();
  545. dq.next();
  546. var proportion;
  547. var remain;
  548. if(reminder.value == 0 || (reminder.value < Number(dq.value(0)))) {
  549. proportion = 1;
  550. } else {
  551. proportion = Number(dq.value(0)) / reminder.value;
  552. }
  553. remain = reminder.value - Number(dq.value(0));
  554. reminder.completion = proportion;
  555. reminder.detail = remain + TTR("navwindow", " Days");
  556. dq = dq.invalidate();
  557. } else if (reminder.condition == "PRODUCTIONBATCHES") {
  558. var dq = new QSqlQuery;
  559. dq.prepare("SELECT count(1) FROM roasting_log WHERE time > :since");
  560. dq.bind(":since", start_time);
  561. dq.exec();
  562. dq.next();
  563. var proportion;
  564. var remain;
  565. if(reminder.value == 0 || (reminder.value < Number(dq.value(0)))) {
  566. proportion = 1;
  567. } else {
  568. proportion = Number(dq.value(0)) / reminder.value;
  569. }
  570. remain = reminder.value - Number(dq.value(0));
  571. reminder.completion = proportion;
  572. reminder.detail = remain + TTR("navwindow", " Batches");
  573. dq = dq.invalidate();
  574. } else if (reminder.condition == "PRODUCTIONHOURS") {
  575. var dq = new QSqlQuery;
  576. dq.prepare("SELECT extract(epoch FROM (SELECT sum(duration) FROM roasting_log WHERE time > :since) / 3600)");
  577. dq.bind(":since", start_time);
  578. dq.exec();
  579. dq.next();
  580. var proportion;
  581. var remain;
  582. if(reminder.value == 0 || (reminder.value < Number(dq.value(0)))) {
  583. proportion = 1;
  584. } else {
  585. proportion = Number(dq.value(0)) / reminder.value;
  586. }
  587. remain = reminder.value - Number(dq.value(0));
  588. reminder.completion = proportion;
  589. reminder.detail = remain.toFixed(1) + TTR("navwindow", " Hours");
  590. dq = dq.invalidate();
  591. }
  592. e[reminder.dbid] = reminder;
  593. }
  594. var s = e.filter(function(n) {
  595. return n.hasOwnProperty("completion")}).sort(function(a, b) {
  596. return b.completion - a.completion});
  597. var c = 0;
  598. var so = 0;
  599. s.forEach(function(item) {
  600. if(item.completion >= 1) {
  601. c += 1;
  602. } else if (item.completion >= 0.8) {
  603. so += 1;
  604. }
  605. });
  606. if(c > 0 || so > 0) {
  607. output.writeStartElement("a");
  608. output.writeAttribute("href", "typica://script/reminders");
  609. startCell(output, TTR("navwindow", "Reminders"));
  610. startStage(output);
  611. var summaryText;
  612. if(c > 0) {
  613. summaryText = "" + c + TTR("navwindow", " reminders due");
  614. for(var i = 0; i < c; i++) {
  615. output.writeStartElement("div");
  616. output.writeAttribute("class", "reminder");
  617. output.writeTextElement("p", s[i].title);
  618. output.writeTextElement("p", Math.floor(s[i].completion * 100) + "%");
  619. output.writeTextElement("p", s[i].detail);
  620. output.writeEndElement();
  621. }
  622. } else {
  623. summaryText = "" + so + TTR("navwindow", " reminders due soon");
  624. for(var i = 0; i < so; i++) {
  625. output.writeStartElement("div");
  626. output.writeAttribute("class", "reminder");
  627. output.writeTextElement("p", s[i].title);
  628. output.writeTextElement("p", Math.floor(s[i].completion * 100) + "%");
  629. output.writeTextElement("p", s[i].detail);
  630. output.writeEndElement();
  631. }
  632. }
  633. endStage(output);
  634. endCell(output, summaryText);
  635. output.writeEndElement();
  636. }
  637. }
  638. var kilounit = TTR("navwindow", "Kg");
  639. var poundunit = TTR("navwindow", "Lb");
  640. var unitData = function() {
  641. var retval = new Object;
  642. if(Number(QSettings.value("script/report_unit")) == 0) {
  643. retval.conversion = 2.2;
  644. retval.unittext = "Kg";
  645. } else {
  646. retval.conversion = 1;
  647. retval.unittext = "Lb";
  648. }
  649. return retval;
  650. }
  651. var drawSchedule = function(output, query) {
  652. var c = 0;
  653. var u = unitData();
  654. query.prepare("SELECT (SELECT name FROM items WHERE id = (data#>>'{roasted}')::numeric), (data#>>'{green_weight}')::numeric/:conversion FROM scheduled_roasts WHERE machine IS NULL");
  655. query.bind(":conversion", u.conversion);
  656. query.exec();
  657. if(query.next()) {
  658. output.writeStartElement("a");
  659. output.writeAttribute("href", "typica://script/schedule");
  660. startCell(output, TTR("navwindow", "Scheduled Roasts"));
  661. startStage(output);
  662. do {
  663. c += 1;
  664. output.writeTextElement("p", query.value(1) + u.unittext + " " + query.value(0));
  665. } while(query.next());
  666. endStage(output);
  667. endCell(output, "" + c + TTR("navwindow", " batches scheduled"));
  668. output.writeEndElement();
  669. }
  670. }
  671. var drawLatest = function(output, query) {
  672. var u = unitData();
  673. query.prepare("SELECT time, roasted_quantity/:conversion, (SELECT name FROM items WHERE id = roasted_id), approval FROM roasting_log ORDER BY time DESC LIMIT 5");
  674. query.bind(":conversion", u.conversion);
  675. query.exec();
  676. if(query.next()) {
  677. output.writeStartElement("a");
  678. output.writeAttribute("href", "typica://script/log");
  679. startCell(output, TTR("navwindow", "Latest Batches"));
  680. startStage(output);
  681. do {
  682. output.writeStartElement("p");
  683. if(query.value(3) == "false") {
  684. output.writeAttribute("style", "color: #FF0000;");
  685. }
  686. output.writeCharacters(query.value(0).replace("T", " ") + " " + query.value(1) + u.unittext + " " + query.value(2));
  687. output.writeEndElement();
  688. } while(query.next());
  689. endStage(output);
  690. endCell(output);
  691. output.writeEndElement();
  692. }
  693. }
  694. var drawMostRoasted = function(output, query) {
  695. var u = unitData();
  696. query.prepare("SELECT (sum(roasted_quantity)/:conversion) AS sum, (SELECT name FROM items WHERE id = roasted_id) FROM roasting_log WHERE time > 'now'::date - '28 days'::interval AND approval = true GROUP BY roasted_id ORDER BY sum DESC LIMIT 5");
  697. query.bind(":conversion", u.conversion);
  698. query.exec();
  699. if(query.next()) {
  700. startCell(output, TTR("navwindow", "Most Roasted Coffees (Last 28 Days)"));
  701. startStage(output);
  702. do {
  703. output.writeTextElement("p", query.value(0) + u.unittext + " " + query.value(1));
  704. } while(query.next());
  705. endStage(output);
  706. endCell(output);
  707. }
  708. }
  709. var drawLeastRoasted = function(output, query) {
  710. var u = unitData();
  711. query.prepare("SELECT (sum(roasted_quantity)/:conversion) AS sum, (SELECT name FROM items WHERE id = roasted_id) FROM roasting_log WHERE time > 'now'::date - '28 days'::interval AND approval = true GROUP BY roasted_id ORDER BY sum ASC LIMIT 5");
  712. query.bind(":conversion", u.conversion);
  713. query.exec();
  714. if(query.next()) {
  715. startCell(output, TTR("navwindow", "Least Roasted Coffees (Last 28 Days)"));
  716. startStage(output);
  717. do {
  718. output.writeTextElement("p", query.value(0) + u.unittext + " " + query.value(1));
  719. } while(query.next());
  720. endStage(output);
  721. endCell(output);
  722. }
  723. }
  724. var drawLeastAvailable = function(output, query) {
  725. var u = unitData();
  726. query.prepare("SELECT name, (quantity / :conversion)::numeric(12,2) AS quantity, (SELECT out FROM coffee_history WHERE coffee_history.id = items.id) AS out FROM items WHERE quantity > 0 ORDER BY out ASC LIMIT 5");
  727. query.bind(":conversion", u.conversion);
  728. query.exec();
  729. if(query.next()) {
  730. startCell(output, TTR("navwindow", "Least Available Coffes"));
  731. startStage(output);
  732. output.writeStartElement("table");
  733. do {
  734. output.writeStartElement("tr");
  735. output.writeTextElement("td", query.value(1) + u.unittext);
  736. output.writeTextElement("td", query.value(0));
  737. output.writeTextElement("td", query.value(2));
  738. output.writeEndElement();
  739. } while(query.next());
  740. output.writeEndElement();
  741. endStage(output);
  742. endCell(output);
  743. }
  744. }
  745. var drawRecentlyOut = function(output, query) {
  746. query.exec("SELECT (SELECT name FROM items WHERE id = item), max(time)::date AS last_transaction FROM transactions WHERE item IN (SELECT id FROM items WHERE quantity = 0) GROUP BY item ORDER BY last_transaction DESC LIMIT 5");
  747. if(query.next()) {
  748. startCell(output, TTR("navwindow", "Latest Out of Stock Coffees"));
  749. startStage(output);
  750. output.writeStartElement("table");
  751. do {
  752. output.writeStartElement("tr");
  753. output.writeTextElement("td", query.value(1));
  754. output.writeTextElement("td", query.value(0));
  755. output.writeEndElement();
  756. } while(query.next());
  757. output.writeEndElement();
  758. endStage(output);
  759. endCell(output);
  760. }
  761. }
  762. var drawUnused = function(output, query) {
  763. query.exec("SELECT name FROM coffees WHERE id NOT IN (SELECT item FROM use) AND quantity > 0");
  764. var c = 0;
  765. if(query.next()) {
  766. startCell(output, TTR("navwindow", "Unused Coffees"));
  767. startStage(output);
  768. do {
  769. c += 1;
  770. output.writeTextElement("p", query.value(0));
  771. } while(query.next());
  772. endStage(output);
  773. endCell(output, "" + c + TTR("navwindow", " unused coffees"));
  774. }
  775. }
  776. var calculateChange = function(current, previous) {
  777. var difference = Number(current) - Number(previous);
  778. var retval;
  779. if(difference > 0) {
  780. retval = "+";
  781. } else if(difference < 0) {
  782. retval = "";
  783. }
  784. retval += ((difference/Number(previous)) * 100).toFixed(1);
  785. retval += "%";
  786. return retval;
  787. }
  788. var outputChange = function(output, value) {
  789. output.writeStartElement("td");
  790. if(value[0] == '+') {
  791. output.writeAttribute("style", "color: #008B00");
  792. } else if(value[0] == '-') {
  793. output.writeAttribute("style", "color: #8B0000");
  794. }
  795. output.writeCharacters(value);
  796. output.writeEndElement();
  797. }
  798. var outputChangeRow = function(output, query, p1, p2) {
  799. var u = unitData();
  800. query.prepare("SELECT sum(roasted_quantity)/:conversion FROM roasting_log WHERE approval = true AND time > 'now'::date - '" + p1 + " days'::interval");
  801. query.bind(":conversion", u.conversion);
  802. query.exec();
  803. query.next();
  804. var current = Number(query.value(0));
  805. output.writeTextElement("td", "" + current.toFixed(0) + u.unittext);
  806. query.prepare("SELECT sum(roasted_quantity)/:conversion FROM roasting_log WHERE approval = true AND time > 'now'::date - '" + p2 + " days'::interval AND time < 'now'::date - '" + p1 + " days'::interval");
  807. query.bind(":conversion", u.conversion);
  808. query.exec();
  809. query.next();
  810. var previous = Number(query.value(0));
  811. output.writeTextElement("td", "" + previous.toFixed(0) + u.unittext);
  812. outputChange(output, calculateChange(current, previous));
  813. }
  814. var drawProductionTrends= function(output, query) {
  815. startCell(output, TTR("navwindow", "Production Trends"));
  816. startStage(output);
  817. output.writeStartElement("table");
  818. output.writeStartElement("tr");
  819. output.writeTextElement("th", TTR("navwindow", "Period"));
  820. output.writeTextElement("th", TTR("navwindow", "Production"));
  821. output.writeTextElement("th", TTR("navwindow", "Previous"));
  822. output.writeTextElement("th", TTR("navwindow", "Change"));
  823. output.writeEndElement();
  824. output.writeStartElement("tr");
  825. output.writeTextElement("th", TTR("navwindow", "Today"));
  826. outputChangeRow(output, query, 0, 1);
  827. output.writeEndElement();
  828. output.writeStartElement("tr");
  829. output.writeTextElement("th", TTR("navwindow", "Last 7 Days"));
  830. outputChangeRow(output, query, 6, 13);
  831. output.writeEndElement();
  832. output.writeStartElement("tr");
  833. output.writeTextElement("th", TTR("navwindow", "Last 30 Days"));
  834. outputChangeRow(output, query, 29, 59);
  835. output.writeEndElement();
  836. output.writeStartElement("tr");
  837. output.writeTextElement("th", TTR("navwindow", "Last 90 Days"));
  838. outputChangeRow(output, query, 89, 179);
  839. output.writeEndElement();
  840. output.writeStartElement("tr");
  841. output.writeTextElement("th", TTR("navwindow", "Last 365 Days"));
  842. outputChangeRow(output, query, 364, 729);
  843. output.writeEndElement();
  844. output.writeEndElement();
  845. endStage(output);
  846. endCell(output);
  847. }
  848. refresh();
  849. dashboard.scriptLinkClicked.connect(function(url) {
  850. if(url == "reminders") {
  851. createReport("reminders.xml");
  852. } else if(url == "log") {
  853. createReport("historyreport.xml");
  854. } else if(url == "schedule") {
  855. createWindow("schedule");
  856. }
  857. });
  858. var remindernotification = Application.subscribe("reminderschange");
  859. remindernotification.notify.connect(function() {
  860. refresh();
  861. });
  862. var schedulenotification = Application.subscribe("scheduledroastschange");
  863. schedulenotification.notify.connect(function() {
  864. refresh();
  865. });
  866. var lognotification = Application.subscribe("transactionschange");
  867. lognotification.notify.connect(function() {
  868. refresh();
  869. });
  870. ]]>
  871. </program>
  872. </window>