Przeglądaj źródła

Merge branch 'master' of https://code.google.com/p/squilu

mingodad 13 lat temu
rodzic
commit
eed58787ae
4 zmienionych plików z 167 dodań i 162 usunięć
  1. 36 36
      ourbiz/index.tpl
  2. 81 80
      ourbiz/ourbiz.nut
  3. 43 41
      ourbiz/sq-server-plugin.nut
  4. 7 5
      ourbiz/sq-server.nut

+ 36 - 36
ourbiz/index.tpl

@@ -2,7 +2,7 @@
 <!--
 Design by Free Responsive Templates
 http://www.free-responsive-templates.com
-Released for free under a Creative Commons Attribution 3.0 Unported License (CC BY 3.0) 
+Released for free under a Creative Commons Attribution 3.0 Unported License (CC BY 3.0)
 -->
 <html>
 <head>
@@ -21,7 +21,7 @@ article table.dist td:nth-child(3), td:nth-child(4), td:nth-child(5)  {
 	text-align: right;
 }
 table {
-	margin-left:auto; 
+	margin-left:auto;
     margin-right:auto;
 }
 table, th, td
@@ -41,7 +41,7 @@ table td {
 	padding:0;
 }
 </style>
-  
+
 <?
   local account_categories = [
 ["TOTAL EXEMPTION SMALL","1,417,506","46.38%"],
@@ -54,7 +54,7 @@ table td {
 ["MEDUM","5,523","0.18%"],
 ["ACCOUNTS TYPE NOT AVAILABLE","5,099","0.17%"],
 ["PARTIAL EXEMPTION","230","0.01%"],
-["INITIAL","7","0%"],  
+["INITIAL","7","0%"],
   ]
 
   local company_categories = [
@@ -108,7 +108,7 @@ local company_ages = [
 ["3","233,894","7.65%"],
 ["2","316,072","10.34%"],
 ["1","451,577","14.78%"],
-["-1","233,976","7.66%"],    
+["-1","233,976","7.66%"],
 ]
 
 function emptyOnNull(key){
@@ -118,12 +118,12 @@ function emptyOnNull(key){
 
 function getPageLink(page){
 	local fmt = "/?search_str=%s&search_post_code=%s&search_sic_code=%s&search_origin_post_code=%s&search_around_post_code=%s&page=%d";
-	return format(fmt, 
-		url_encode(emptyOnNull("search_str")),  
-		url_encode(emptyOnNull("search_post_code")),  
+	return format(fmt,
+		url_encode(emptyOnNull("search_str")),
+		url_encode(emptyOnNull("search_post_code")),
 		url_encode(emptyOnNull("search_sic_code")),
-		url_encode(emptyOnNull("search_origin_post_code")), 
-		url_encode(emptyOnNull("search_around_post_code")), 
+		url_encode(emptyOnNull("search_origin_post_code")),
+		url_encode(emptyOnNull("search_around_post_code")),
 		page);
 }
 
@@ -163,7 +163,7 @@ function getPageLink(page){
         // Instantiate and draw our chart, passing in some options.
         var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
         chart.draw(data, options);
-        
+
         // Create the data table.
         var data2 = new google.visualization.DataTable();
         data2.addColumn('string', 'Topping');
@@ -183,7 +183,7 @@ function getPageLink(page){
         // Instantiate and draw our chart, passing in some options.
         var chart2 = new google.visualization.PieChart(document.getElementById('chart2_div'));
         chart2.draw(data2, options2);
-        
+
         // Create the data table.
         var data3 = new google.visualization.DataTable();
         data3.addColumn('string', 'Topping');
@@ -203,7 +203,7 @@ function getPageLink(page){
         // Instantiate and draw our chart, passing in some options.
         var chart3 = new google.visualization.PieChart(document.getElementById('chart3_div'));
         chart3.draw(data3, options3);
-        
+
         // Create the data table.
         var data4 = new google.visualization.DataTable();
         data4.addColumn('string', 'Topping');
@@ -223,7 +223,7 @@ function getPageLink(page){
         // Instantiate and draw our chart, passing in some options.
         var chart4 = new google.visualization.PieChart(document.getElementById('chart4_div'));
         chart4.draw(data4, options4);
-	
+
         var data5 = google.visualization.arrayToDataTable([
           ['Year', 'Survive', 'Registered'],
 ["2000",50134,210350],
@@ -247,7 +247,7 @@ function getPageLink(page){
         };
 
         var chart5 = new google.visualization.ColumnChart(document.getElementById('chart5_div'));
-        chart5.draw(data5, options5);	
+        chart5.draw(data5, options5);
       }
     </script>
 <? } ?>
@@ -289,7 +289,7 @@ function loadFormFields(){
 		for(var i=0; i< saveLoadFormFields.length; ++i){
 			 frm[saveLoadFormFields[i]].value = getCookie(saveLoadFormFields[i]) || '';
 		}
-	}	
+	}
 }
 
 function show_location(position) {
@@ -334,7 +334,7 @@ function sortTable(id, col, numeric){
 		return (str1 < str2 ? -1 : (str1 > str2 ? 1 : 0));
 	});
     }
-    
+
     for(var i=0, len=store.length; i<len; i++){
         tbl.appendChild(store[i]);
     }
@@ -387,7 +387,7 @@ function sortTable(id, col, numeric){
 
 <? if (this.get("sic_street", null)  == "street"){ ?>
 
-<header><h1 id="results">Street Search Results</h1></header> 
+<header><h1 id="results">Street Search Results</h1></header>
 <? if (this.get("queryWasInterrupted", false)){ ?>
 <p>Please try again with more specific search terms, it took too long !</p>
 <? } ?>
@@ -415,11 +415,11 @@ function sortTable(id, col, numeric){
 </td></tr>
 <? } ?>
 </table>
-<? 
-	} 
+<?
+	}
 } else if (this.get("sicSearchResults", false)) { ?>
 
-<header><h1 id="results">SIC Code Search Results</h1></header> 
+<header><h1 id="results">SIC Code Search Results</h1></header>
 <? if (this.get("queryWasInterrupted", false)){ ?>
 <p>Please try again with more specific search terms, it took too long !</p>
 <? } ?>
@@ -447,11 +447,11 @@ function sortTable(id, col, numeric){
 </td></tr>
 <? } ?>
 </table>
-<? 
-	} 
+<?
+	}
 } else { ?>
 
-<header><h1 id="results">Companies Search Results</h1></header> 
+<header><h1 id="results">Companies Search Results</h1></header>
 <? if (this.get("queryWasInterrupted",false)) { ?>
 <p>Please try again with more specific search terms, it took too long !</p>
 <? } ?>
@@ -460,9 +460,9 @@ function sortTable(id, col, numeric){
 <tr><th><a href="" onclick="return sortTable('tblcr', 0)">Number</a></th>
 	<th><a href="" onclick="return sortTable('tblcr', 1)">Name</a></th>
 	<th><a href="" onclick="return sortTable('tblcr', 2, true)">Age (years)</a></th>
-<? 
-	local hasDistances = this.get("search_origin_post_code", false) && search_origin_post_code.len() > 0; 
-	if (hasDistances){ 
+<?
+	local hasDistances = this.get("search_origin_post_code", false) && search_origin_post_code.len() > 0;
+	if (hasDistances){
 ?>
 <th><a href="" onclick="return sortTable('tblcr', 3, true)">Dist. Meters</a></th>
 <? } ?>
@@ -496,9 +496,9 @@ function sortTable(id, col, numeric){
 <td>&nbsp;</td></tr>
 <? } ?>
 </table>
-<? 		
-		} 
-	} 
+<?
+		}
+	}
  }
    else if (page_name == "view_company") {
        var pc1, pc2, google_map_url, geo_link;
@@ -510,7 +510,7 @@ function sortTable(id, col, numeric){
 	if (longitude) geo_link = format("geo:%f,%f&z=16", latitude,longitude);
 	else  geo_link = "#";
 ?>
-    
+
 <header><h1 id="results"><?=company.number?> - <?=company.name?></h1></header>
 <table class="nj dist">
 <tr><td>Address</td><td>
@@ -560,13 +560,13 @@ function sortTable(id, col, numeric){
           <? } ?>
         </table>
 <? } ?>
-      
+
 <?
   if (this.get("show_map", false) && pc1 && pc2){
 ?>
 <br />
 <div style="margin: 0 auto; width: 425px;">
-<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" 
+<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"
 src="https://maps.google.co.uk/maps?key=AIzaSyAF53Wut8B5cvaUDY-pfegBhbftJdRHovM&amp;channel=cs&amp;q=<?=pc1?>+<?=pc2?>&amp;ie=UTF8&amp;hq=&amp;hnear=<?=pc1?>+<?=pc2?>,+United+Kingdom&amp;gl=uk&amp;t=m&amp;z=14&amp;output=embed"></iframe>
   <br /><small><a href="<?=google_map_url?>" style="color:#0000FF;text-align:left">View Larger Map</a></small>
 </div>
@@ -587,7 +587,7 @@ src="https://maps.google.co.uk/maps?key=AIzaSyAF53Wut8B5cvaUDY-pfegBhbftJdRHovM&
         </table>
     <!--Div that will hold the pie chart-->
     <div id="chart_div"></div>
-      
+
         <div class="clearfloat"></div>
     </article>
     <article class="post">
@@ -652,8 +652,8 @@ src="https://maps.google.co.uk/maps?key=AIzaSyAF53Wut8B5cvaUDY-pfegBhbftJdRHovM&
 </div>
 <footer>
 	<p>
-        Copyright &copy; Domingo Alvarez Duarte. All rights reserved. Designed by <a href="http://www.free-responsive-templates.com" title="free responsive templates">Free Responsive Templates</a>, Validation 
-        <a class="footerLink" href="http://validator.w3.org/check/referer" title="This page validates as HTML5"><abbr title="HyperText Markup Language">HTML5</abbr></a> | 
+        Copyright &copy; Domingo Alvarez Duarte. All rights reserved. Designed by <a href="http://www.free-responsive-templates.com" title="free responsive templates">Free Responsive Templates</a>, Validation
+        <a class="footerLink" href="http://validator.w3.org/check/referer" title="This page validates as HTML5"><abbr title="HyperText Markup Language">HTML5</abbr></a> |
         <a class="footerLink" href="http://jigsaw.w3.org/css-validator/check/referer" title="This page validates as CSS"><abbr title="Cascading Style Sheets">CSS3</abbr></a>
     </p>
 </footer>

+ 81 - 80
ourbiz/ourbiz.nut

@@ -4,7 +4,8 @@ if(!globals.get("APP_CODE_FOLDER", false)) ::APP_CODE_FOLDER <- ".";
 local constants = getconsttable();
 
 function getOurbizDBFileName(){
-	if (globals.get("jniLog", false)) return APP_CODE_FOLDER + "/ourbiz.db";
+	if(globals.get("jniLog", false)) return APP_CODE_FOLDER + "/ourbiz.db";
+	if(globals.get("WIN32", false)) return APP_CODE_FOLDER + "/../../ourbiz-uk/ourbiz.db";
 	return "/home/mingo/dev/FrontAccountLua/ourbiz.db";
 }
 
@@ -15,7 +16,7 @@ function getOurbizDB(){
 	//return checkCachedDB(APP_CODE_FOLDER + "/ourbiz.db");
 }
 
-if(AT_DEV_DBG || !globals.get("PdfSqlTable", false)) {
+if(globals.get("AT_DEV_DBG", false) || !globals.get("PdfSqlTable", false)) {
 	dofile(APP_CODE_FOLDER + "/pdf-table.nut");
 }
 
@@ -163,7 +164,7 @@ class DB_Manager {
 	editable_fields = null;
 	has_mdate = null;
 	has_version = null;
-	
+
 	constructor(ptable_name, peditable_fields = null){
 		if(!peditable_fields) peditable_fields =  ["is_active", "code", "description"];
 		table_name = ptable_name;
@@ -171,7 +172,7 @@ class DB_Manager {
 		has_mdate = true;
 		has_version = true;
 	}
-	
+
 	function db_action(db, data){
 		local action = data.__action__;
 		if (action == "insert") return db_insert(db,data);
@@ -200,14 +201,14 @@ class DB_Manager {
 			}
 		}
 		mf.write(")");
-		
+
 		local stmt = db.prepare(mf.tostring());
 		local x = 0;
 		foreach( k,v in editable_fields) {
 			if (data.get(v, false)){
 				stmt.bind_empty_null(++x, data[v]);
 			}
-		}			
+		}
 		local result = stmt.step();
 		stmt.finalize()
 		if (result == sqlite3.DONE) return db.last_insert_rowid();
@@ -230,17 +231,17 @@ class DB_Manager {
 
 		mf.write(" where id=? ");
 		if (self.has_version) mf.write(" and _version_=?");
-		
+
 		local stmt = db.prepare(mf.tostring());
 		local x = 0;
 		foreach( k,v in editable_fields) {
 			if (data.get(v, false)) {
 				stmt.bind_empty_null(++x, data[v]);
 			}
-		}			
+		}
 		stmt.bind(++x, data.__id__);
 		if (has_version) stmt.bind(++x, data.__version__);
-		
+
 		local result = stmt.step();
 		stmt.finalize();
 		if (result == sqlite3.SQLITE_DONE) return db.changes();
@@ -251,7 +252,7 @@ class DB_Manager {
 		local mf = blob();
 		mf.write("delete from ", table_name, " where id=? ");
 		if (has_version) mf.write(" and _version_=?");
-		
+
 		local stmt = db.prepare(mf.tostring());
 		stmt.bind(1, data.__id__);
 		if (has_version) stmt.bind(2, data.__version__);
@@ -261,23 +262,23 @@ class DB_Manager {
 		if (result == sqlite3.DONE) return db.changes();
 		throw db.error_message();
 	}
-	
+
 	function sql_get_one(req) {
-		return format("select * from %s where id=?", table_name); 
+		return format("select * from %s where id=?", table_name);
 	}
-	
+
 	function sql_list(qs_tbl=null, post_tbl=null) {
-		return format("select id, code, description, is_active from %s order by description", table_name); 
+		return format("select id, code, description, is_active from %s order by description", table_name);
 	}
-	
+
 	function sql_short_list(req) {
-		return format("select id, description from %s where is_active=1 order by 2", table_name); 
+		return format("select id, description from %s where is_active=1 order by 2", table_name);
 	}
 
 	function get_bar_chart_statistics_sql_core(aId, sab, str1, str2){
 		local mf = blob();
 
-		mf.write("SELECT ", str1, " as qm, sum(subtotal - total_discount + total_sales_tax1 + total_sales_tax2) as q, '", 
+		mf.write("SELECT ", str1, " as qm, sum(subtotal - total_discount + total_sales_tax1 + total_sales_tax2) as q, '",
 			sab, [==[' as sab
 FROM orders as o
 WHERE entity_id = ]==], aId);
@@ -309,7 +310,7 @@ class DB_Entities extends DB_Manager {
 		"tags", "tax_number", "use_sales_tax2", "user_code", "web", "zip",
 		"irpf_pct_retention"]);
 	}
-	
+
 	function past_products_sql(entity_id){
 		return format([==[
 SELECT
@@ -362,7 +363,7 @@ LEFT JOIN payment_types as pt
 			mf.write([==[
 select product_id as 'product_id|ID|8|R', description as "description|Product|-1",
 	sum(quantity) as 'quantity|Qty.|9|R|N', sum(]==], strTmp2, [==[) as "amount|Amount|9|R|M",
-]==], strTmp3, [==[ as "order_type_code|Type|6|C" 
+]==], strTmp3, [==[ as "order_type_code|Type|6|C"
 from ]==], strTmp, [==[
 group by product_id, description, ]==], strTmp3);
 		}
@@ -374,7 +375,7 @@ group by product_id, description, ]==], strTmp3);
 			case 4: mf.write(" order by 4 desc "); break;
 			case 5: mf.write(" order by 3 desc "); break;
 		}
-	
+
 		mf.write(" limit ", query_limit.tointeger());
 		//debug_print(tostring(mf), "\n");
 		return mf.tostring();
@@ -406,7 +407,7 @@ group by product_id, description, ]==], strTmp3);
 		local so = get_search_options(post_tbl);
 		checkQueryStringSAB(qs_tbl, so);
 		local mf = blob();
-		
+
 		mf.write(" select e.id, e.name, e.contact, e.phone, e.is_active, e.image_id ");
 		if (so.with_images) mf.write(", i.thumbnail, i.mime_type ");
 		mf.write(" from entities as e ");
@@ -421,7 +422,7 @@ group by product_id, description, ]==], strTmp3);
 			}
 			if (so.sales) mf.write("'S'");
 			else if (so.buys) mf.write("'B'");
-		
+
 			mf.write(" order by o.id desc");
 			if (so.query_limit != 0) mf.write(" limit ", so.query_limit);
 			mf.write(") order by 2");
@@ -517,8 +518,8 @@ from entities order by name
 			local sql = [==[
 select id as 'id|ID|6|R', name as 'name|Name|-1',
 	contact as 'contact|Contact|12',
-	phone as 'phone|Phone|12' 
-from entities 
+	phone as 'phone|Phone|12'
+from entities
 order by name
 ]==]
 			local db = getOurbizDB();
@@ -537,7 +538,7 @@ db_ourbiz_tables.entities <- new DB_Entities();
 // orders
 //
 
-if(AT_DEV_DBG || !globals.get("PDF_Order", false)) {
+if(globals.get("AT_DEV_DBG", false) || !globals.get("PDF_Order", false)) {
 	dofile(APP_CODE_FOLDER + "/pdf-order.nut");
 }
 
@@ -647,13 +648,13 @@ class CalcOrderLine
 		use_sales_tax2 = map.get("use_sales_tax2", false) == "1";
 		tax_exempt = map.get("tax_exempt", false) == "1";
 		price_decimals = map.get("price_decimals", 2).tointeger();
-		
+
 		foreach(field in fields){
 			this[field] = map.get(field, 0.0).tofloat();
 		}
 
 		calc();
-		
+
 		foreach(field in fields){
 			map[field] <- this[field];
 		}
@@ -739,7 +740,7 @@ class CalcOrderLine
 		}
 		line_total = round(line_subtotal + sales_tax1_amt + sales_tax2_amt, price_decimals);
 	}
-	
+
 	function calc2()
 	{
 		local num100 = Decimal(100);
@@ -785,7 +786,7 @@ class  CalcOrderTotals
 	total_amt = null;
 	weight_total = null;
 	lines_count = null;
-    
+
 	constructor()
 	{
 		clear();
@@ -814,7 +815,7 @@ class  CalcOrderTotals
 		add2sle(out_result, "sales_tax2_amt");
 		add2sle(out_result, "total_amt");
 	}
-	
+
 	function dumpSLEFieldValues(out_result)
 	{
 		add2sle(out_result, lines_count);
@@ -825,7 +826,7 @@ class  CalcOrderTotals
 		add2sle(out_result, sales_tax2_amt);
 		add2sle(out_result, total_amt);
 	}
-    
+
 	function dumpSLEArray(out_result)
 	{
 		out_result.write("[[");
@@ -873,7 +874,7 @@ from orders_lines where order_id=?]==]);
 		sales_tax2_amt += calc_line.sales_tax2_amt;
 		total_amt += calc_line.line_total;
 	}
-	
+
 	function number_format_trim(num){
 		local snum = math.number_format(num);
 		return snum;
@@ -925,7 +926,7 @@ from orders_lines where order_id=?]==]);
 		local stmt = db.prepare("select * from orders where id=?", id);
 		if(stmt.next_row())
 		{
-			local order_type_id = stmt.col("order_type_id");		
+			local order_type_id = stmt.col("order_type_id");
 			pdf_order.labelNumber = db.exec_get_one(
 				format("select description_to_print from order_types where id=%d",
 					order_type_id));
@@ -956,7 +957,7 @@ class MyCalcOrderTotals
 	order_totals = null;
 	calc_line = null;
 	db = null;
-    
+
 	constructor(adb)
 	{
 		db = adb;
@@ -987,7 +988,7 @@ class DB_Orders extends DB_Manager {
 		local so = get_search_options(post_tbl);
 		checkQueryStringSAB(qs_tbl, so);
 		local mf = blob();
-		
+
 		mf.write("SELECT o.id, o.order_date, ot.code, o.series, o.order_number,",
 			//" o.entity_name, get_order_total(o.id) as total_amt, pt.code "
 			" o.entity_name, ",
@@ -1032,7 +1033,7 @@ class DB_Orders extends DB_Manager {
 						" description like "" , search_str , "" order by id desc limit " , so.query_limit , ")");
 				}
 				else mf.write(" and ");
-				
+
 				if (so.notes) mf.write(" o.notes ");
 				else if (so.date) mf.write(" o.order_date ");
 				//lo_search_str = escapeSqlLikeSearchStr(dbDate(search_str))
@@ -1047,7 +1048,7 @@ class DB_Orders extends DB_Manager {
 		if (so.order_by_modification) mf.write(" and o.mdate is not null order by o.mdate desc ");
 		else if (so.order_by_creation) mf.write(" order by o.id desc ");
 		else mf.write(" order by o.order_date desc, o.id desc ");
-	    
+
 		if (so.query_limit && so.query_limit != 0) mf.write(" limit " , so.query_limit);
 		//debug_print(tostring(mf), "\n")
 		return  mf.tostring();
@@ -1070,7 +1071,7 @@ class DB_Orders extends DB_Manager {
 			strPU2 = ", pt ";
 		}
 		else strPU1 = strPU2 = "";
-		
+
 		local rc = get_sql_bar_chart_statistics_periodes(periode_count, periode_type);
 		local speriode = rc[0],  speriode_count = rc[1];
 
@@ -1139,9 +1140,9 @@ class DB_Products extends DB_Manager {
 		local so = get_search_options(post_tbl);
 		checkQueryStringSAB(qs_tbl, so);
 		local mf = blob();
-		
+
 		mf.write([==[
-select p.id, 
+select p.id,
 	p.reference_code,
 	p.sell_description,
 	ifnull(p.kit,  0)  as kit,
@@ -1159,7 +1160,7 @@ select p.id,
 		if ( (!so.group_id) && (!so.entity_id) && (! (so.search_str && (so.search_str.len() > 0)))){
 			//special case where we get the latest entities that made any transaction
 			mf.write(" p.id in(select distinct product_id from orders_lines where order_id in (select o.id from orders as o ");
-		
+
 			if (so.sales || so.buys){
 				mf.write(", order_types as ot where o.order_type_id = ot.id and ot.group_order =");
 				if (so.sales) mf.write("'S'");
@@ -1183,7 +1184,7 @@ select p.id,
 			mf.write(" and p.group_id=" , so.group_id , " ");
 
 		if (so.active) mf.write(" and p.is_active = 1 ");
-		
+
 		if (so.only_prices_older){
 			//local adate = parse_date(optNum)
 			//mf.write(" and p.price_update_date < '" ,
@@ -1247,14 +1248,14 @@ select product_id from orders_lines where order_id in (
 		}
 		else if (qs_tbl.get("print_list", false)){
 			return [==[
-select 
-    p.id  as 'id|ID|6|R', 
-    case when p.user_code isnull then ' ' else p.user_code end as 'reference|Reference|9', 
-    p.sell_description as 'sell_description|Description|-1', 
-    cast(case when p.kit isnull then 0 else kit end as text) as 'kit|Kit|4|C', 
-    round((p.sell_price * (1 + (st.rate1/100.0))),p.price_decimals) as 'price_taxed|Price+V.A.T.|12|R|M', 
-    round(case when p.kit > 0 then p.kit_onhand else p.quantity_onhand end, 4) as 'quantity_onhand|Onhand|10|R|N' 
-from products_onhand as p left join sales_tax_rates as st 
+select
+    p.id  as 'id|ID|6|R',
+    case when p.user_code isnull then ' ' else p.user_code end as 'reference|Reference|9',
+    p.sell_description as 'sell_description|Description|-1',
+    cast(case when p.kit isnull then 0 else kit end as text) as 'kit|Kit|4|C',
+    round((p.sell_price * (1 + (st.rate1/100.0))),p.price_decimals) as 'price_taxed|Price+V.A.T.|12|R|M',
+    round(case when p.kit > 0 then p.kit_onhand else p.quantity_onhand end, 4) as 'quantity_onhand|Onhand|10|R|N'
+from products_onhand as p left join sales_tax_rates as st
 on p.sales_tax_id = st.id order by 3
 ]==];
 		}
@@ -1265,14 +1266,14 @@ on p.sales_tax_id = st.id order by 3
 			pdf.water_mark = "T H I S   I S   A   D E M O";
 
 			local sql = [==[
-select 
-    p.id  as 'id|ID|6|R', 
-    case when p.user_code isnull then ' ' else p.user_code end as 'reference|Reference|9', 
-    p.sell_description as 'sell_description|Description|-1', 
-    cast(case when p.kit isnull then 0 else kit end as text) as 'kit|Kit|4|C', 
-    round((p.sell_price * (1 + (st.rate1/100.0))),p.price_decimals) as 'price_taxed|Price+V.A.T.|12|R|M', 
-    round(case when p.kit > 0 then p.kit_onhand else p.quantity_onhand end, 4) as 'quantity_onhand|Onhand|10|R|N' 
-from products_onhand as p left join sales_tax_rates as st 
+select
+    p.id  as 'id|ID|6|R',
+    case when p.user_code isnull then ' ' else p.user_code end as 'reference|Reference|9',
+    p.sell_description as 'sell_description|Description|-1',
+    cast(case when p.kit isnull then 0 else kit end as text) as 'kit|Kit|4|C',
+    round((p.sell_price * (1 + (st.rate1/100.0))),p.price_decimals) as 'price_taxed|Price+V.A.T.|12|R|M',
+    round(case when p.kit > 0 then p.kit_onhand else p.quantity_onhand end, 4) as 'quantity_onhand|Onhand|10|R|N'
+from products_onhand as p left join sales_tax_rates as st
 on p.sales_tax_id = st.id order by 3
 ]==]
 			local db = getOurbizDB();
@@ -1294,7 +1295,7 @@ class DB_Images extends DB_Manager {
 	constructor(){
 		base.constructor("images", ["mime_type", "name", "description", "group_set", "image", "thumbnail"]);
 	}
-	
+
 	function sql_list(qs_tbl, post_tbl){
 		local so = get_search_options(post_tbl);
 		local mf = blob();
@@ -1313,7 +1314,7 @@ class DB_Images extends DB_Manager {
 		//debug_print(tostring(mf), "\n")
 		return  mf.tostring();
 	}
-	
+
 	function sql_get_one(req){
 		local mf = blob();
 		mf.write("select id, _version_, mime_type, name, description, group_set, cdate, mdate, length(image) as img_size ");
@@ -1333,7 +1334,7 @@ class DB_order_types extends DB_Manager {
             "with_credit", "with_inventory", "with_payment", "with_ordered",
             "with_sales_tax", "with_sales_tax_included", "with_quote"]);
 	}
-	
+
 	function sql_list(qs_tbl, post_tbl){
 		if (qs_tbl.get("short_list", false)){
 			local sql = "select id, description from order_types where is_active = 1 ";
@@ -1374,7 +1375,7 @@ db_ourbiz_tables.payment_types <- new DB_Manager("payment_types", ["is_active",
 function check_payment_terms(txt){
 	local init = 0;
 	local pct = 0.0;
-	txt.gmatch("(%d+)%s+(%d+%.?%d*)%D+(%d+)%s+(%S+)", function(n, v, p, pt){ 
+	txt.gmatch("(%d+)%s+(%d+%.?%d*)%D+(%d+)%s+(%S+)", function(n, v, p, pt){
 		// n ->decimal number expected
 		// v -> pct number expected
 		pct += v.tofloat();
@@ -1392,14 +1393,14 @@ class DB_sales_tax_rates extends DB_Manager {
 	constructor(){
 		base.constructor("sales_tax_rates", ["is_active", "rate1", "rate2", "description"]);
 	}
-	
+
 	function sql_list(qs_tbl=null, post_tbl=null) {
 		return "select id,rate1,rate2,description,is_active from sales_tax_rates order by rate1";
 	}
 }
 
 db_ourbiz_tables.sales_tax_rates <- new DB_sales_tax_rates();
- 
+
 db_ourbiz_tables.warranty_types <- new DB_Manager("warranty_types")
 
 
@@ -1433,10 +1434,10 @@ function products_kit_list_sql (kit_id, partOf=false){
 		str2 = "and pk.product_id = p.id order by p.sell_description";
 	}
 	return format([==[
-select pk.id, 
+select pk.id,
 	p.id,
 	p.sell_description,
-	pk.quantity, 
+	pk.quantity,
 	round((p.sell_price*pk.quantity),4) as amount,
 	p.quantity_onhand
 from product_kits as pk, products as p
@@ -1508,7 +1509,7 @@ function ourbizDbMobile(request){
 	local data = {};
 	data.page_name = "list_products";
 	local query_string = request.info.query_string;
-	
+
 	local db = getOurbizDB();
 	local sql = "select id, reference_code, sell_description, sell_price, image_id from products ";
 	local search_str;
@@ -1544,10 +1545,10 @@ function ourbizDbGetList(request){
 		local sql, post_tbl, data;
 		if (isPost) post_tbl = get_post_fields(request, 1024);
 		else post_tbl = {};
-	
+
 		if (!post_tbl.get("query_limit", false)) post_tbl.query_limit <- 50;
 		gmFile.clear();
-		
+
 		if (list == "entity_groups") group_dump_data(db, gmFile, "entity_groups");
 		else if (list == "product_groups") group_dump_data(db, gmFile, "product_groups");
 		else if (list == "config") sql = "select key,value from config";
@@ -1567,7 +1568,7 @@ Content-Length: %d
 				return true;
 			}
 		}
-		
+
 		if (sql){
 			local stmt = db.prepare(sql);
 			//debug_print(sql, "\n", db.error_message(), "\n")
@@ -1577,7 +1578,7 @@ Content-Length: %d
 		else if (gmFile.len() > 0){
 			data = gmFile.tostring();
 		}
-		
+
 		if (data){
 			//using string.format with binary data gives wrong results
 			gmFile.clear()
@@ -1599,9 +1600,9 @@ function ourbizDbGetOne(request){
 		local tbl = tbl_keys[0];
 		local rec_id = tbl_qs[tbl];
 		local sql, data;
-		
+
 		gmFile.clear()
-		
+
 		if (tbl == "orders"){
 			if (request.get_var(query_string, "with_lines")){
 				sql = "select * from orders where id=?";
@@ -1639,14 +1640,14 @@ function ourbizDbGetOne(request){
 				stmt.bind(1, rec_id);
 				gmFile.write(stmt.asSleArray());
 				stmt.finalize();
-				
+
 				stmt = db.prepare(product_prices_list_sql(rec_id));
 				gmFile.write(stmt.asSleArray());
 				stmt.finalize();
-				
+
 				stmt = db.prepare(products_kit_list_sql(rec_id));
 				gmFile.write(stmt.asSleArray());
-				stmt.finalize();			
+				stmt.finalize();
 
 				stmt = db.prepare(products_kit_details_get_one(rec_id));
 				gmFile.write(stmt.asSleArray());
@@ -1656,7 +1657,7 @@ function ourbizDbGetOne(request){
 		}
 		else if (tbl == "config") sql = "select * from config where id=?";
 		else if (db_ourbiz_tables.get(tbl, false)) sql = db_ourbiz_tables[tbl].sql_get_one(tbl_qs);
-		
+
 		if (sql){
 			local stmt = db.prepare(sql);
 			stmt.bind(1, rec_id);
@@ -1665,7 +1666,7 @@ function ourbizDbGetOne(request){
 			stmt.finalize();
 		}
 		else if (gmFile.len() > 0) data = gmFile.tostring();
-		
+
 		if (data){
 			//using string.format with binary data gives wrong results
 			gmFile.clear();
@@ -1684,7 +1685,7 @@ function ourbizDbGetBin(request){
 		local image = request.get_var(query_string, "image");
 		local thumbnail = request.get_var(query_string, "thumbnail");
 		local stmt;
-		gmFile.clear();	
+		gmFile.clear();
 
 		if (image){
 			gmFile.write("select ");
@@ -1694,7 +1695,7 @@ function ourbizDbGetBin(request){
 			gmFile.write(", mime_type from images where id=",  image.tointeger());
 			stmt = db.prepare(gmFile.tostring());
 		}
-		
+
 		if (stmt){
 			local result = stmt.step() == stmt.SQLITE_ROW;
 			if (result){

+ 43 - 41
ourbiz/sq-server-plugin.nut

@@ -1,5 +1,6 @@
 local globals = getroottable();
 if(!globals.get("APP_CODE_FOLDER", false)) ::APP_CODE_FOLDER <- ".";
+WIN32 <- os.getenv("WINDIR") != null;
 
 //local AT_DEV_DBG=true;
 
@@ -9,6 +10,7 @@ if(!globals.get("APP_CODE_FOLDER", false)) ::APP_CODE_FOLDER <- ".";
 
 function checkCompaniesUkDBFile(){
 	if (globals.get("jniLog", false)) return APP_CODE_FOLDER + "/companies-uk-RG.db";
+	if (globals.get("WIN32", false)) return APP_CODE_FOLDER + "/../../companies-uk/companies-uk-RG.db";
 	return "/media/USBHD320/bo/uk/companies-uk-RG.db";
 }
 
@@ -17,7 +19,7 @@ if(!globals.get("__tplCache", false)) ::__tplCache <- {};
 if(!globals.get("__stmtCache", false)) ::__stmtCache <- {};
 if(!globals.get("db", false)) ::db <- SQLite3(checkCompaniesUkDBFile());
 ::db.exec_dml("PRAGMA cache_size = 4000;");
-	
+
 function getTemplate(fname, nocache){
 	local mixBase = ::__tplCache.get(fname, false);
 	if (!mixBase || nocache){
@@ -29,7 +31,7 @@ function getTemplate(fname, nocache){
 			debug_print("\n", e);
 		}
 		::__tplCache[fname] <- mixBase;
-	}		
+	}
 	return mixBase;
 }
 
@@ -90,7 +92,7 @@ function split_filename(path){
 function insert_field (dest, key, value){
   local fld = dest.get(key, null);
   if (!fld) dest[key] <- value;
-  else 
+  else
   {
 	if (type (fld) == "array") fld.push(value);
 	else  dest[key] <- [fld, value];
@@ -152,7 +154,7 @@ function multipart_data_file_value(file_contents, file_name, file_size, headers)
 
 function multipart_data_parse_field(input, state){
 	local headers, value;
-	
+
 	headers = multipart_data_read_field_headers(input, state);
 	if (headers) {
 		local name_value=[];
@@ -251,7 +253,7 @@ function parse_post_data(input_type, data, tab = null){
 				tab[names[i]] = values[i];
 			}
 		}
-	}  
+	}
 	return tab;
 }
 
@@ -266,7 +268,7 @@ function get_post_fields(request, max_len=1024*1000){
 		fd.write(data, data.len());
 		fd.close();
 		debug_print(conn_get_header("Content-Type"), "\n");
-*/		
+*/
 		parse_post_data(content_type, data, post_fields);
 	}
 	return post_fields;
@@ -322,7 +324,7 @@ function getFilesInPath(path, files=null, prefix=""){
 			else pf = file;
 
 			local attr = sqfs.attributes (f);
-			
+
 			if(attr.mode == "directory") getFilesInPath (f, files, pf);
 			else
 			{
@@ -358,7 +360,7 @@ function getDbListFromStmt(stmt, maxSeconds=0){
 	} catch(e){
 		error_code = db.error_code();
 	}
-	
+
 	if (maxSeconds) db.progress_handler(null);
 	stmt.reset();
 	//debug_print("\n", rows.len(), "\n");
@@ -370,10 +372,10 @@ function strHasContent(v){
 	return false;
 }
 
-function getCiaUkSearchList(search_str, search_post_code, search_sic_code, 
+function getCiaUkSearchList(search_str, search_post_code, search_sic_code,
 			search_origin_post_code, search_around_post_code , sic_street, page, limit){
 	local offset = page * limit;
-	local post_code_radius = strHasContent(search_around_post_code) ? search_around_post_code.tointeger() : 0; 
+	local post_code_radius = strHasContent(search_around_post_code) ? search_around_post_code.tointeger() : 0;
 	local stmt, stmt_count, bind_str;
 	local hasSicSearch = false;
 	local bind_names;
@@ -436,8 +438,8 @@ limit ? offset ?
 			hasSicSearch = true;
 			local sic_code_sql;
 			if (search_sic_code.find_lua("%d+") == 0){
-				stmt = getCachedStmt("getCiaUkSearchList5", @() format([==[ 
-%s, companies_sic_codes csc 
+				stmt = getCachedStmt("getCiaUkSearchList5", @() format([==[
+%s, companies_sic_codes csc
 where csc.sic_code like :sic_code
 and c.id = csc.company_id
 and c.post_code like :post_code
@@ -447,7 +449,7 @@ limit :limit offset :offset
 			}
 			else
 			{
-				stmt = getCachedStmt("getCiaUkSearchList6", @() format([==[ 
+				stmt = getCachedStmt("getCiaUkSearchList6", @() format([==[
 %s , companies_sic_codes csc , sic_codes_fts sc
 where sic_codes_fts match :sic_code
 and csc.sic_code = sc.docid
@@ -460,7 +462,7 @@ limit :limit offset :offset
 		}
 		else
 		{
-			stmt = getCachedStmt("getCiaUkSearchList7", @() format([==[ 
+			stmt = getCachedStmt("getCiaUkSearchList7", @() format([==[
 %s, companies_fts cf
 where companies_fts match ?
 and c.id = cf.docid
@@ -488,14 +490,14 @@ limit ? offset ?
 	else
 	{
 		bind_str = search_str;
-		stmt = getCachedStmt("getCiaUkSearchList11", @() format([==[ 
+		stmt = getCachedStmt("getCiaUkSearchList11", @() format([==[
 %s, companies_fts cf
 where cf.name match ?
 and c.id = cf.docid
 limit ? offset ?
 ]==], base_sql));
 	}
-	
+
 	local xp = 1;
 	stmt.reset();
 //debug_print("\n", bind_str, ":", limit, ":", offset);
@@ -545,8 +547,8 @@ function getCiaUkByIdOldNames(id){
 function getDistances(search_origin_post_code, rows){
 	if (rows.len() > 0){
 		local stmt = getCachedStmt("getDistances", [==[
-select 
-	round(distance(ref.easting, ref.northing, pc.easting, pc.northing)), 
+select
+	round(distance(ref.easting, ref.northing, pc.easting, pc.northing)),
 	ifnull(round(bearing(ref.easting, ref.northing, pc.easting, pc.northing)), 0)
 from companies c left join post_codes pc on c.post_code = pc.post_code,
 	post_codes ref
@@ -659,17 +661,17 @@ function osGridToLatLong(easting, northing){
   local dE5 = dE3*dE2;
   local dE6 = dE4*dE2;
   local dE7 = dE5*dE2;
-  
+
   lat = lat - VII*dE2 + VIII*dE4 - IX*dE6;
   local lon = lon0 + X*dE - XI*dE3 + XII*dE5 - XIIA*dE7;
-  
+
   return [toDeg(lat), toDeg(lon)];
   //return lat, lon
 }
 
 function osGridToLatLongAdjusted(easting, northing){
 	local lat_long = osGridToLatLong(easting, northing)
-	//adjust lat, lon 
+	//adjust lat, lon
 	lat_long[0] += 0.0024;
 	lat_long[1] -=  0.00145;
 	return lat_long;
@@ -689,7 +691,7 @@ function downloadChunked(host, file, extra_header=null){
 	local req;
 	if (extra_header) req = extra_header;
 	else req = format("GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", file, host);
-	
+
 	//print("REQUEST:", req)
 	sock.send(req);
 	local s;
@@ -719,7 +721,7 @@ function getExtraCompanyDataOnNet(cnum){
 	} catch(e){
 	}
 	if (!page) return "";
-	
+
 	local cookie1, cookie2;
 	local function getCookie(){
 		page.gmatch("Set%-Cookie: (chcookie=[^;]+)", function(m){ cookie1=m; return false});
@@ -728,7 +730,7 @@ function getExtraCompanyDataOnNet(cnum){
 	}
 	local location;
 	page.gmatch("Location: http://wck2.companieshouse.gov.uk(.-)wcframe", function(m) {location=m; return false;});
-	
+
 	//print("LOCATION:", getCookie(), location, page)
 
 	//http://wck2.companieshouse.gov.uk/466fc35f66bf9ef61decbe1581a24080/companysearch
@@ -783,7 +785,7 @@ User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.11 (KHTML, like Gecko)
 	if (!data) return "";
 
 	data.gmatch([==[<!%-%- FILE_END::.-tmpl %-%->.-<td align="left" class="text">(.-)</td>.-<td align="left"><span class="text">(.-)</span>.-<td class="text">(.-)</td>]==],
-		function(vtype, vdate, vdesc){ tdata.push(format("%s|%s|%s", vtype, vdate, vdesc)); return true;}); 
+		function(vtype, vdate, vdesc){ tdata.push(format("%s|%s|%s", vtype, vdate, vdesc)); return true;});
 
 	data = tdata.concat("\n");
 	data = data.gsub("<[^>]->", "");
@@ -798,7 +800,7 @@ function getExtraCompanyData(cid, cnum){
 	local stmt = ::db.prepare("select data from company_extra_data where id = ?");
 	stmt.reset();
 	stmt.bind(1, cid);
-	
+
 	if (stmt.step() == stmt.SQLITE_ROW){
 		data = stmt.col(0);
 	}
@@ -840,7 +842,7 @@ local uri_handlers = {
 		}
 		request.print("</ul></body></html>");
 		return true;
-	},	
+	},
 	["/SQ/logout"] = function(request){
 		request.close_session();
 		request.print(format("HTTP/1.1 302 Found\r\nLocation: http://%s\r\n\r\n", request.info.http_headers.Host))
@@ -852,12 +854,12 @@ local uri_handlers = {
 		//print("EDIT_MD5_PASSWORD=", EDIT_MD5_PASSWORD, "\n")
 		bool_t isViewOnly = VIEW_MD5_PASSWORD && request.check_password(VIEW_MD5_PASSWORD);
 		if (!isViewOnly) canEdit = EDIT_MD5_PASSWORD && request.check_password(EDIT_MD5_PASSWORD);
-	
+
 		if(!(canEdit || isViewOnly) ) {
 			request.send_authorization_request("r.dadbiz.es");
 			return true;
 		}
-		 
+
 		table_t data = {
 			file_name=null,
 			content=null,
@@ -883,7 +885,7 @@ local uri_handlers = {
 			}
 		}
 		else if( query_string ) data.file_name <- request.get_var(query_string, "file");
-		
+
 		//debug_print(data.search_id, "\n")
 		if( data.file_name ){
 			data.file_name = sanitizePath(data.file_name);
@@ -897,9 +899,9 @@ local uri_handlers = {
 				}
 			}
 		}
-				
+
 		//debug_tprint(data.company)
-		
+
 		local mFile = gmFile;
 		mFile.clear(); //allways reset global vars
 		data.mix_write <- function(str){ mFile.write(str || "")}
@@ -914,7 +916,7 @@ local uri_handlers = {
 		data.limit <- 25;
 		local query_string = request.info.query_string;
 		bool_t isPost = request.info.request_method == "POST";
-		local filed_names = ["search_str", "search_post_code", "search_origin_post_code", 
+		local filed_names = ["search_str", "search_post_code", "search_origin_post_code",
 			"search_around_post_code", "search_sic_code", "sic_street", "page"];
 		if (isPost) {
 			local post_fields =  get_post_fields(request);
@@ -926,13 +928,13 @@ local uri_handlers = {
 		else foreach(k in filed_names) data[k] <- null;
 		if(!data.get("page", null))  data.page <- 0;
 		else data.page = data.page.tointeger();
-		
+
 		local errcode;
 		if (strHasContent(data.search_str) || strHasContent(data.search_post_code) || strHasContent(data.search_sic_code)) {
 			data.sicSearchResults <- strHasContent(data.search_sic_code) && !(strHasContent(data.search_str) || strHasContent(data.search_post_code))
-			local result = getCiaUkSearchList(data.search_str, data.search_post_code, data.search_sic_code, 
+			local result = getCiaUkSearchList(data.search_str, data.search_post_code, data.search_sic_code,
 				data.search_origin_post_code, data.search_around_post_code , data.sic_street, data.page, data.limit);
-				
+
 			if (result[1] /*errcode*/ == SQLite3.SQLITE_INTERRUPT) {
 				data.queryWasInterrupted <- true;
 			}
@@ -940,13 +942,13 @@ local uri_handlers = {
 			data.limit <- result[2];
 			if (!data.sicSearchResults && data.rows.len() == 1) {
 					request.print(format("HTTP/1.1 302 Found\r\nLocation: /view?id=%d\r\n\r\n", data.rows[0][0]));
-					return true;			
+					return true;
 			}
 			if (strHasContent(data.search_origin_post_code)) {
 				getDistances(data.search_origin_post_code, data.rows);
 			}
 		}
-		
+
 		local mFile = gmFile;
 		mFile.clear();
 		data.mix_write <- function(str) {if(str) mFile.write(str);}
@@ -975,12 +977,12 @@ local uri_handlers = {
 				data.longitude <- lat_long[1];
 			}
 		}
-		local filed_names = ["search_str", "search_post_code", "search_origin_post_code", 
+		local filed_names = ["search_str", "search_post_code", "search_origin_post_code",
 			"search_around_post_code", "search_sic_code", "sic_street", "page"];
 		foreach(k in filed_names) data[k] <- null;
-		
+
 		//debug_tprint(data.company)
-		
+
 		local mFile = gmFile;
 		mFile.clear();
 		data.mix_write <- function(str) {mFile.write(str || "");}

+ 7 - 5
ourbiz/sq-server.nut

@@ -1,6 +1,8 @@
 local globals = getroottable();
 if(!globals.get("APP_CODE_FOLDER", false)) ::APP_CODE_FOLDER <- ".";
 
+WIN32 <- os.getenv("WINDIR") != null;
+
 /*
 local _old_import = import;
 ::__imported_files <-  {};
@@ -15,19 +17,19 @@ function getUserCallbackSetup(fn){
 	local code = fd.read(fd.len());
 	fd.close();
 	local extra_code = format("APP_CODE_FOLDER <- \"%s\";\n", APP_CODE_FOLDER);
-	
+
 	if (globals.get("VIEW_MD5_PASSWORD", false)){
 		extra_code += format("VIEW_MD5_PASSWORD <- \"%s\";\n", VIEW_MD5_PASSWORD);
 	} else extra_code += "VIEW_MD5_PASSWORD <- nul;\n";
-	
+
 	if (globals.get("EDIT_MD5_PASSWORD", false)){
 		extra_code += format("EDIT_MD5_PASSWORD <- \"%s\";\n", EDIT_MD5_PASSWORD);
 	} else extra_code += "EDIT_MD5_PASSWORD <- null;\n";
-	
+
 	if (globals.get("AT_DEV_DBG", false)){
 		extra_code += "AT_DEV_DBG <- true;\n"
 	} else extra_code += "AT_DEV_DBG <- false;\n"
-	
+
 	return compilestring(format("%s\n%s", extra_code, code));
 }
 
@@ -68,7 +70,7 @@ local mongoose_start_params = {
 			//return true;
 			return false;
 		}
-		else if(event == "MG_HTTP_ERROR" 
+		else if(event == "MG_HTTP_ERROR"
 			|| event == "MG_INIT_SSL"){
 				return false;
 		}