iSalesDB.m 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. //
  2. // iSalesDB.m
  3. // RedAnt ERP Mobile
  4. //
  5. // Created by Ray on 14-6-24.
  6. // Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "iSalesDB.h"
  9. #import "AESCrypt.h"
  10. //#import "AppDelegate.h"
  11. #import "RASingleton.h"
  12. NSLock *dblock ;
  13. int count_dbconn;
  14. //int count_tmpdbconn;
  15. @implementation iSalesDB
  16. +(BOOL)checkForField:(NSString *)table field:(NSString *)field db:(sqlite3 *)db
  17. {
  18. sqlite3_stmt *stmt;
  19. NSString *sql = [NSString stringWithFormat:@"PRAGMA table_info(%@)",table];
  20. if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL) == SQLITE_OK)
  21. {
  22. while(sqlite3_step(stmt) == SQLITE_ROW)
  23. {
  24. NSString *fieldName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
  25. if([field isEqualToString:fieldName])
  26. {
  27. sqlite3_finalize(stmt);
  28. return YES;
  29. }
  30. }
  31. }
  32. return NO;
  33. }
  34. void offline_dirty(sqlite3_context *context, int argc, sqlite3_value **argv) {
  35. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  36. if(btrigger)
  37. {
  38. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  39. [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  40. [defaults setBool:true forKey:@"OFFLINE_DIRTY"];
  41. [defaults synchronize];
  42. }
  43. }
  44. void encryptfield (sqlite3_context *context, int argc, sqlite3_value **argv) {
  45. assert(argc == 1);
  46. switch (sqlite3_value_type(argv[0])){
  47. case SQLITE_TEXT: {
  48. unsigned const char *string = sqlite3_value_text (argv[0]);
  49. //Get the Objective C string (much easier to manage)
  50. NSString *ocString = [[NSString alloc] initWithUTF8String:(char *) string] ;
  51. NSString* encrypt=[AESCrypt fastencrypt:ocString];
  52. // //Split it on punctuation and spaces
  53. // NSMutableCharacterSet *cset = [NSCharacterSet punctuationCharacterSet];
  54. // [cset addCharactersInString:@" "];
  55. // NSArray *tokens = [ocString componentsSeparatedByCharactersInSet:cset];
  56. // //Sort it
  57. // NSArray *sortedArray = [tokens sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  58. // ocString = [sortedArray componentsJoinedByString:@" "];
  59. // ocString = [ocString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  60. const char *rString = [encrypt UTF8String];
  61. //DebugLog (@"%@", [[[NSString alloc] initWithUTF8String:(char *) rString] autorelease]);
  62. sqlite3_result_text(context, rString, (int)strlen(rString) * sizeof(char), NULL);
  63. break;
  64. }
  65. default: {
  66. sqlite3_result_null(context);
  67. break;
  68. }
  69. }
  70. }
  71. void decryptfield (sqlite3_context *context, int argc, sqlite3_value **argv) {
  72. assert(argc == 1);
  73. switch (sqlite3_value_type(argv[0])){
  74. case SQLITE_TEXT: {
  75. unsigned const char *string = sqlite3_value_text (argv[0]);
  76. //Get the Objective C string (much easier to manage)
  77. NSString *ocString = [[NSString alloc] initWithUTF8String:(char *) string] ;
  78. NSString* decrypt=[AESCrypt fastdecrypt:ocString];
  79. // //Split it on punctuation and spaces
  80. // NSMutableCharacterSet *cset = [NSCharacterSet punctuationCharacterSet];
  81. // [cset addCharactersInString:@" "];
  82. // NSArray *tokens = [ocString componentsSeparatedByCharactersInSet:cset];
  83. // //Sort it
  84. // NSArray *sortedArray = [tokens sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  85. // ocString = [sortedArray componentsJoinedByString:@" "];
  86. // ocString = [ocString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  87. const char *rString = [decrypt UTF8String];
  88. //DebugLog (@"%@", [[[NSString alloc] initWithUTF8String:(char *) rString] autorelease]);
  89. sqlite3_result_text(context, rString, (int)(strlen(rString) * sizeof(char)), NULL);
  90. break;
  91. }
  92. default: {
  93. sqlite3_result_null(context);
  94. break;
  95. }
  96. }
  97. }
  98. //+(void) icuRegexpFunc:(sqlite3_context *)p nArg:(int) nArg apArg: (sqlite3_value **)apArg
  99. //{
  100. //}
  101. +(int) AddExFunction:(sqlite3 *) db
  102. {
  103. int nResult = 0;
  104. nResult=sqlite3_create_function(db, "decrypt", -1, SQLITE_ANY, 0, decryptfield, 0, 0);
  105. nResult=sqlite3_create_function(db, "encrypt", -1, SQLITE_ANY, 0, encryptfield, 0, 0);
  106. nResult=sqlite3_create_function(db, "offline_dirty", -1, SQLITE_ANY, 0, offline_dirty, 0, 0);
  107. // sqlite3_create_function(database, "yourAwesome", 4, SQLITE_UTF8, NULL, &yourAwesomeFunc, NULL, NULL);
  108. // nResult = sqlite3_create_function(db, "containi", -1, SQLITE_ANY, 0, icuContainiFunc, 0, 0);
  109. return nResult;
  110. }
  111. +(NSArray*) get_saveduser
  112. {
  113. {
  114. sqlite3* db = [self get_db ];
  115. NSMutableArray* ret = [[NSMutableArray alloc] init];
  116. // ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
  117. // NSString* user = appDelegate.user;
  118. NSString *sqlQuery = @"select name,pwd from login_info ";
  119. sqlite3_stmt * statement;
  120. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  121. {
  122. while (sqlite3_step(statement) == SQLITE_ROW)
  123. {
  124. // char *name = (char*)sqlite3_column_text(statement, 1);
  125. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  126. NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
  127. NSString *pwd = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
  128. name = [AESCrypt decrypt:name password:@"usai"];
  129. pwd = [AESCrypt decrypt:pwd password:@"usai"];
  130. NSMutableDictionary* up = [[NSMutableDictionary alloc]init];
  131. up[@"name"]=name;
  132. up[@"pwd"]=pwd;
  133. [ret addObject:up];
  134. // char *address = (char*)sqlite3_column_text(statement, 3);
  135. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  136. }
  137. sqlite3_finalize(statement);
  138. }
  139. [iSalesDB close_db:db];
  140. return ret;
  141. }
  142. }
  143. //+(void)testdata
  144. //{
  145. //
  146. // //---------------- init db --------------------
  147. // // NSString* date;
  148. // // NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  149. // // [formatter setDateFormat:@"YYYY-MM-dd-hh-mm-ss"];
  150. // // date = [formatter stringFromDate:[NSDate date]];
  151. // //
  152. // // NSString* dbname=[NSString stringWithFormat:@"%@.db",date];
  153. // //
  154. // // DebugLog (@"initializeDB");
  155. // //
  156. // // // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  157. // // NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];//[paths objectAtIndex:0];
  158. // // NSString *database_path = [documents stringByAppendingPathComponent:dbname];
  159. // //
  160. // //
  161. // // // move db file from document to cache ;
  162. // // // NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  163. // // NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] ;//[searchPaths objectAtIndex: 0];
  164. // // NSString* dbFilePath = [documentFolderPath stringByAppendingPathComponent:dbname];
  165. // // if ([[NSFileManager defaultManager] fileExistsAtPath: dbFilePath])
  166. // // {
  167. // // [[NSFileManager defaultManager] moveItemAtPath:dbFilePath toPath:database_path error:nil];
  168. // //
  169. // // }
  170. // // // end move;
  171. // //
  172. //
  173. //
  174. //
  175. //
  176. // sqlite3 *db = [iSalesDB get_db];
  177. //
  178. // NSString* drop_model =@"DROP TABLE IF EXISTS MODEL;";
  179. // NSString* drop_IMAGE =@"DROP TABLE IF EXISTS model_image;";
  180. // NSString* drop_image_price =@"DROP TABLE IF EXISTS model_price;";
  181. // NSString* drop_category =@"DROP TABLE IF EXISTS category;";
  182. // NSString* drop_login =@"DROP TABLE IF EXISTS offline_login;";
  183. // NSString* drop_cart =@"DROP TABLE IF EXISTS offline_cart;";
  184. // NSString* drop_wish =@"DROP TABLE IF EXISTS offline_wishlist;";
  185. // NSString* drop_contact =@"DROP TABLE IF EXISTS offline_contact;";
  186. // NSString* drop_contact_image =@"DROP TABLE IF EXISTS contact_image;";
  187. //
  188. //
  189. // [iSalesDB execSql:drop_model db:db];
  190. // [iSalesDB execSql:drop_IMAGE db:db];
  191. // [iSalesDB execSql:drop_image_price db:db];
  192. // [iSalesDB execSql:drop_category db:db];
  193. // [iSalesDB execSql:drop_login db:db];
  194. // [iSalesDB execSql:drop_cart db:db];
  195. // [iSalesDB execSql:drop_wish db:db];
  196. // [iSalesDB execSql:drop_contact db:db];
  197. // [iSalesDB execSql:drop_contact_image db:db];
  198. //
  199. // NSString* create_model=@"CREATE TABLE IF NOT EXISTS model ( _id INTEGER PRIMARY KEY, name VARCHAR(20), description VARCHAR(20), product_id INTEGER, color VARCHAR(20), legcolor VARCHAR(20) ,availability INTEGER, incoming_stock INTEGER , demension VARCHAR(20), seat_height VARCHAR(20), material VARCHAR(20), box_dim VARCHAR(20), volume VARCHAR(20), weight VARCHAR(20), model_set VARCHAR(20), load_ability VARCHAR(20),default_category VARCHAR(20), category VARCHAR(100),fabric_content VARCHAR(20), assembling VARCHAR(20), made_in VARCHAR(20), special_remarks VARCHAR(20),stockUom integer,fashion VARCHAR(20), isnew integer,property_field VARCHAR(20),property_display VARCHAR(20),selector_field VARCHAR(20),selector_display VARCHAR(20),ETA DATE);";
  200. //
  201. //
  202. //
  203. // NSString* create_image=@"CREATE TABLE IF NOT EXISTS model_image ( _id INTEGER PRIMARY KEY, name VARCHAR(20), url VARCHAR(256), type integer, product_id INTEGER);";
  204. //
  205. // NSString* create_model_price=@"CREATE TABLE IF NOT EXISTS model_price ( _id INTEGER PRIMARY KEY, product_id INTEGER,price float , type integer);";
  206. // NSString* create_category=@"CREATE TABLE IF NOT EXISTS category ( _id INTEGER PRIMARY KEY, code VARCHAR(20),name VARCHAR(20));";
  207. //
  208. // NSString* create_offline_login=@"CREATE TABLE IF NOT EXISTS offline_login ( _id INTEGER PRIMARY KEY, username VARCHAR(40),password VARCHAR(40), can_show_price integer ,can_see_price integer,contact_id VARCHAR(20),user_type integer,can_cancel_order integer,can_set_cart_price integer,can_create_portfolio integer, can_delete_order integer,can_submit_order integer,can_set_tearsheet_price integer,can_create_order integer, mode VARCHAR(20), sales_code VARCHAR(20));";
  209. //
  210. //
  211. //
  212. // NSString* create_offline_cart=@"CREATE TABLE IF NOT EXISTS offline_cart ( _id INTEGER PRIMARY KEY, product_id INTEGER,price float , discount float , so_no VARCHAR(40));";
  213. // NSString* create_offline_wish=@"CREATE TABLE IF NOT EXISTS offline_wishlist ( _id INTEGER PRIMARY KEY, product_id INTEGER);";
  214. //
  215. // NSString* create_offline_contact=@"CREATE TABLE IF NOT EXISTS offline_contact ( _id INTEGER PRIMARY KEY, country VARCHAR(40),company_name VARCHAR(40),contact_id VARCHAR(20),addr_1 text, addr_2 text , addr_3 text, addr_4 text, zipcode varchar(20),state VARCHAR(40), city VARCHAR(40), first_name VARCHAR(40) ,last_name VARCHAR(40),phone VARCHAR(40),fax VARCHAR(40),email VARCHAR(40),notes text, price_type VARCHAR(40), sales_rep VARCHAR(40), type VARCHAR(40),create_time timestamp,editable integer,contact_name VARCHAR(40) , addr text);";
  216. //
  217. // NSString* create_contact_image=@"CREATE TABLE IF NOT EXISTS contact_image ( _id INTEGER PRIMARY KEY, name VARCHAR(20), url VARCHAR(256), contact_id VARCHAR(20));";
  218. //
  219. //
  220. // // NSString* create_model_category=@"CREATE TABLE IF NOT EXISTS model_category ( _id INTEGER PRIMARY KEY, product_id INTEGER,code VARCHAR(20));";
  221. //
  222. // // CREATE TABLE users (_id integer PRIMARY KEY,name varchar(20),pass varchar(20));
  223. // // [self execSql:create_actions_info db:db];
  224. // // [self execSql:create_fields_info db:db];
  225. // // [self execSql:create_search_history db:db];
  226. // // [self execSql:create_push_message db:db];
  227. // // [self execSql:create_favorites db:db];
  228. // // [self execSql:create_history db:db];
  229. // // [self execSql:create_location db:db];
  230. // [iSalesDB execSql:create_model db:db];
  231. //
  232. // [iSalesDB execSql:create_image db:db];
  233. //
  234. // [iSalesDB execSql:create_model_price db:db];
  235. // [iSalesDB execSql:create_category db:db];
  236. //
  237. // [iSalesDB execSql:create_offline_login db:db];
  238. //
  239. // [iSalesDB execSql:create_offline_cart db:db];
  240. // [iSalesDB execSql:create_offline_wish db:db];
  241. //
  242. //
  243. // [iSalesDB execSql:create_offline_contact db:db];
  244. //
  245. // [iSalesDB execSql:create_contact_image db:db];
  246. //
  247. // NSString * insert_user_queeniey=@"insert into offline_login(can_show_price,can_see_price,contact_id,user_type,can_cancel_order,can_set_cart_price,can_create_portfolio,can_delete_order,can_submit_order,can_set_tearsheet_price,can_create_order,mode,username,password) values(1,1,'NPD',1,1,1,1,1,1,1,1,'Regular Mode','QueenieY','lj0EPk2Th9zZCVwrcskZOA==')";
  248. // [iSalesDB execSql:insert_user_queeniey db:db];
  249. // // [self execSql:create_model_category db:db];
  250. //
  251. // // if( ![self checkForField:@"search_history" field:@"level" db:db])
  252. // // {
  253. // // NSString* alter_search_history = @"ALTER TABLE search_history ADD level INTEGER";
  254. // // [self execSql:alter_search_history db:db];
  255. // // }
  256. // // NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
  257. // // double t = time-2592000; //NSTimeInterval返回的是double类型
  258. // // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  259. // // [formatter setDateFormat:@"yyyy-MM-dd"];
  260. // //
  261. // // NSString*timestr=[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:t]];
  262. // //
  263. // // // [self execSql:[NSString stringWithFormat:@"delete from search_history where h_time<%@",timestr ] db:db];
  264. // // [self execSql:@"delete from search_history where julianday('now', 'localtime')-julianday(h_time, 'localtime')>30" db:db];
  265. // // int ret=[iSalesDB close_db:db];
  266. //
  267. //
  268. // DebugLog (@"bottom of initializeDb");
  269. //
  270. //
  271. // NSString* IMS_S=@"http://113.28.30.235:80/site//u/NPD/20150715/3857_1455_s.jpg";
  272. // //NSString* IMS_M=@"http://113.28.30.235:80/site//u/NPD/20150715/3857_1455_m.jpg";
  273. // NSString* IMS_L=@"http://113.28.30.235:80/site//u/NPD/20150715/3857_1455_l.jpg";
  274. //
  275. // //----------------- fill data -------------------
  276. // NSString* img_url1 = IMS_S;
  277. // // NSString* img_url2 = IMS_M;
  278. // NSString* img_url3 = IMS_L;
  279. //
  280. // CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
  281. // [iSalesDB execSql:@"begin" db:db];
  282. // // NSString* exec = @"";
  283. // for(int i=0;i<1000;i++)
  284. // {
  285. //
  286. // int category = arc4random() % 4;
  287. // NSString* sql = [NSString stringWithFormat:@"insert into model(ETA,property_display,property_field,selector_display,isnew,selector_field,fashion,stockUom,name,description,product_id,color,legcolor,availability,incoming_stock,demension,seat_height,material,box_dim,volume,weight,model_set,load_ability,default_category,category,fabric_content,assembling,made_in,special_remarks) values('07/13/2016','Leg Color','legcolor','Color',1,'color','108526-48-BS%d',1,'108526-48-BS%d','Charlotte Fabric Counter Stool Brushed Smoke Legs, Putty%d',%d,'red color%d','white color%d',15%d,25%d,'20.00\"w 22.00\"d 39.00\"h%d','26.0\"h','Solid Birch Wood%d','20.50\"w 23.00\"d 40.00\"h',10.91%d,23.00%d,'Sold in quantities of 1','Load ability%d','%d','%d','77%% Polyester, 15%% Cotton, 8%% Linen', 'Fully Assembled;%d','China%d','Special Remarks%d');",i,i,i,i,i,i,i,i,i,i,i,i,i,category,category,i,i,i];
  288. //
  289. //
  290. // NSString* sql_1=[NSString stringWithFormat:@"insert into model_price (product_id,price,type) values(%d,12.%d,0);",i,i%100];
  291. // NSString* sql_2=[NSString stringWithFormat:@"insert into model_price (product_id,price,type) values(%d,12.%d,1);",i,i%100];
  292. // NSString* sql_3=[NSString stringWithFormat:@"insert into model_price (product_id,price,type) values(%d,12.%d,2);",i,i%100];
  293. //
  294. //
  295. //
  296. // NSString* sql_4=[NSString stringWithFormat:@"insert into model_image(product_id,type,url) values(%d,0,'%@')",i,img_url1];
  297. // NSString* sql_5=[NSString stringWithFormat:@"insert into model_image(product_id,type,url) values(%d,1,'%@')",i,img_url3];
  298. //
  299. // // exec=[exec stringByAppendingString:sql];
  300. // //
  301. // // exec=[exec stringByAppendingString:sql_1];
  302. // // exec=[exec stringByAppendingString:sql_2];
  303. // // exec=[exec stringByAppendingString:sql_3];
  304. //
  305. //
  306. // [iSalesDB execSql:sql db:db];
  307. //
  308. // [iSalesDB execSql:sql_1 db:db];
  309. // [iSalesDB execSql:sql_2 db:db];
  310. // [iSalesDB execSql:sql_3 db:db];
  311. // [iSalesDB execSql:sql_4 db:db];
  312. // [iSalesDB execSql:sql_5 db:db];
  313. //
  314. // }
  315. // // [iSalesDB execSql:exec db:db];
  316. //
  317. // [iSalesDB execSql:@"update model set category='#001003#;' where category='0'" db:db];
  318. // [iSalesDB execSql:@"update model set category='#001001#;' where category='1'" db:db];
  319. // [iSalesDB execSql:@"update model set category='#001002#;' where category='2'" db:db];
  320. // [iSalesDB execSql:@"update model set category='#001003#;' where category='3'" db:db];
  321. // [iSalesDB execSql:@"commit" db:db];
  322. // [iSalesDB close_db:db];
  323. //
  324. // CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
  325. //
  326. // // ((double)(begintime-endtime))/(1000*1000);
  327. // DebugLog(@"time cost: %0.3f", end - start);
  328. //
  329. //
  330. //
  331. //
  332. //
  333. //
  334. //}
  335. + (sqlite3*) get_db
  336. {
  337. // if(![dblock tryLock])
  338. // return nil;
  339. [dblock lock];
  340. sqlite3* db = nil;
  341. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  342. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  343. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  344. DebugLog(@"DB path:%@",database_path);
  345. count_dbconn++;
  346. DebugLog(@"OPEN DB current dbconn: %d",count_dbconn);
  347. if (sqlite3_open([database_path UTF8String], &db) != SQLITE_OK) {
  348. DebugLog(@"sqlite3_open failed. msg:%s",sqlite3_errmsg(db));
  349. [iSalesDB close_db:db];
  350. }
  351. [self AddExFunction:db];
  352. [RASingleton sharedInstance].currentDB = db;
  353. return db;
  354. }
  355. + (void) close_db:(sqlite3 *)db
  356. {
  357. sqlite3_close(db);
  358. count_dbconn--;
  359. DebugLog(@"CLOSE DB current dbconn: %d",count_dbconn);
  360. [RASingleton sharedInstance].currentDB = nil;
  361. [dblock unlock];
  362. }
  363. + (sqlite3*) get_db_at:(NSString* )path
  364. {
  365. sqlite3* db = nil;
  366. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  367. // NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  368. // NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  369. // DebugLog(@"DB path:%@",database_path);
  370. //count_dbconn++;
  371. DebugLog(@"current dbconn: %d",count_dbconn);
  372. if (sqlite3_open([path UTF8String], &db) != SQLITE_OK) {
  373. DebugLog(@"sqlite3_open failed. msg:%s",sqlite3_errmsg(db));
  374. sqlite3_close(db);
  375. //[iSalesDB close_db:db];
  376. }
  377. [self AddExFunction:db];
  378. return db;
  379. }
  380. + (NSString* ) sqliteEscape :(NSString*) keyWord
  381. {
  382. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
  383. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  384. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"[" withString:@"/["];
  385. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"]" withString:@"/]"];
  386. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"%" withString:@"/%"];
  387. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"&" withString:@"/&"];
  388. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"_" withString:@"/_"];
  389. keyWord = [keyWord stringByReplacingOccurrencesOfString:@"(" withString:@"/("];
  390. keyWord = [keyWord stringByReplacingOccurrencesOfString:@")" withString:@"/)"];
  391. return keyWord;
  392. }
  393. + (void) save_pdf: (NSString*) temp_path filename:(NSString*) filename
  394. {
  395. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  396. //
  397. // if(appDelegate.bEnable_Cache==false)
  398. // return ;
  399. if(temp_path==nil)
  400. return;
  401. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  402. NSString *cachefolder = [paths objectAtIndex:0];
  403. NSString *pdf_cache = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  404. NSFileManager* fileManager = [NSFileManager defaultManager];
  405. BOOL bdir=YES;
  406. if(! [fileManager fileExistsAtPath:pdf_cache isDirectory:&bdir])
  407. {
  408. NSError *error = nil;
  409. bool bsuccess=[fileManager createDirectoryAtPath:pdf_cache withIntermediateDirectories:YES attributes:nil error:&error];
  410. if(!bsuccess)
  411. DebugLog(@"Create cache folder failed");
  412. // if(bsuccess)
  413. // {
  414. // sqlite3 *db = [self get_db];
  415. //
  416. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  417. // [iSalesDB close_db:db];
  418. // }
  419. }
  420. NSString *save_path = [pdf_cache stringByAppendingPathComponent:filename];
  421. NSError *error = nil;
  422. bool bsuccess=[fileManager copyItemAtPath:temp_path toPath:save_path error:&error];
  423. if(bsuccess)
  424. DebugLog(@"PDF SAVE SUCCESS,%@",filename);
  425. else
  426. DebugLog(@"PDF SAVE FAILED,%@",filename);
  427. }
  428. + (void) cache_img: (NSData*) imgData filename:(NSString*) name saveTo:(NSString*) path
  429. {
  430. path=[path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  431. path=[path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  432. path=[path stringByReplacingOccurrencesOfString:name withString:@""];
  433. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  434. // NSString *cachefolder = [paths objectAtIndex:0];
  435. // NSString *img_cache = [cachefolder stringByAppendingPathComponent:[NSString stringWithFormat:@"img_cache/%@",@"www.newpacificdirect.com/u/NPD/20160615/mytest/"]];
  436. // if ([[NSFileManager defaultManager] fileExistsAtPath:img_cache]) {
  437. //
  438. // DebugLog(@"目录已经存在了");
  439. //
  440. // }
  441. // else
  442. // {
  443. // NSError *error = nil;
  444. // bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:img_cache withIntermediateDirectories:YES attributes:nil error:&error];
  445. //
  446. // if(!bsuccess)
  447. // DebugLog(@"Create temp folder failed");
  448. // }
  449. if(path.length==0)
  450. path=@"";
  451. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  452. //
  453. // if(appDelegate.bEnable_Cache==false)
  454. // return ;
  455. if(imgData==nil)
  456. return;
  457. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  458. NSString *cachefolder = [paths objectAtIndex:0];
  459. NSString *img_cache = [cachefolder stringByAppendingPathComponent:[NSString stringWithFormat:@"img_cache/%@",path]];
  460. NSFileManager* fileManager = [NSFileManager defaultManager];
  461. BOOL bdir=YES;
  462. if(! [fileManager fileExistsAtPath:img_cache isDirectory:&bdir])
  463. {
  464. NSError *error = nil;
  465. bool bsuccess=[fileManager createDirectoryAtPath:img_cache withIntermediateDirectories:YES attributes:nil error:&error];
  466. if(!bsuccess)
  467. DebugLog(@"Create cache folder failed");
  468. // if(bsuccess)
  469. // {
  470. // sqlite3 *db = [self get_db];
  471. //
  472. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  473. // [iSalesDB close_db:db];
  474. // }
  475. }
  476. NSString *filePath = [img_cache stringByAppendingPathComponent:name];
  477. bool bsuccess=[imgData writeToFile:filePath atomically:YES];
  478. if(bsuccess)
  479. DebugLog(@"IMG CACHE SUCCESS,%@",name);
  480. else
  481. DebugLog(@"IMG CACHE FAILED,%@",name);
  482. }
  483. + (NSData*) load_cached_img:(NSString*) filename loadFrom:(NSString*) path
  484. {
  485. if(path.length==0)
  486. return nil;
  487. // bool b= [Singleton sharedInstance].homeItemClick ;
  488. path=[path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  489. path=[path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  490. // path=[path stringByReplacingOccurrencesOfString:filename withString:@""];
  491. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  492. //
  493. // if(appDelegate.bEnable_Cache==false)
  494. // return nil;
  495. NSData* data = nil;
  496. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  497. NSString *cachefolder = [paths objectAtIndex:0];
  498. NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
  499. NSString *filePath = [img_cache stringByAppendingPathComponent:path];
  500. NSFileManager* fileManager = [NSFileManager defaultManager];
  501. if( [fileManager fileExistsAtPath:filePath ])
  502. {
  503. data = [NSData dataWithContentsOfFile: filePath];
  504. }
  505. // NSString* sqliteQuery = [NSString stringWithFormat:@"SELECT img FROM img_cache WHERE name = '%@'", filename];
  506. // sqlite3_stmt* statement;
  507. // sqlite3 *db = [self get_db];
  508. //
  509. //// if( sqlite3_prepare_v2(db, [sqliteQuery UTF8String], -1, &statement, NULL) == SQLITE_OK )
  510. //// {
  511. //// if( sqlite3_step(statement) == SQLITE_ROW )
  512. //// {
  513. //// int length = sqlite3_column_bytes(statement, 0);
  514. //// data = [NSData dataWithBytes:sqlite3_column_blob(statement, 0) length:length];
  515. //// }
  516. //// }
  517. //
  518. // // Finalize and close database.
  519. // sqlite3_finalize(statement);
  520. // [iSalesDB close_db:db];
  521. return data;
  522. }
  523. + (int) initializeDb {
  524. DebugLog (@"initializeDB");
  525. count_dbconn=0;
  526. //count_tmpdbconn=0;
  527. // return false;
  528. //
  529. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  530. // NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  531. // NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  532. //
  533. // move db file from document to cache ;
  534. // NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  535. // NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] ;//[searchPaths objectAtIndex: 0];
  536. // NSString* dbFilePath = [documentFolderPath stringByAppendingPathComponent:DBNAME];
  537. // if ([[NSFileManager defaultManager] fileExistsAtPath: dbFilePath])
  538. // {
  539. // [[NSFileManager defaultManager] moveItemAtPath:dbFilePath toPath:database_path error:nil];
  540. //
  541. // }
  542. // end move;
  543. if(dblock==nil)
  544. dblock= [[NSLock alloc] init];
  545. // /* test dblock in thread*/
  546. // for(int i=0;i<50;i++)
  547. //
  548. // {
  549. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  550. //
  551. // DebugLog(@"%d is running",i);
  552. // sqlite3* testdb = [self get_db];
  553. //
  554. // int sec=arc4random() % 10;
  555. // DebugLog(@"%d is processing, will take %d sec",i,sec);
  556. // sleep(sec);
  557. // [self close_db:testdb];
  558. //
  559. // DebugLog(@"%d is finish",i);
  560. //
  561. //
  562. // });
  563. // }
  564. //
  565. // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
  566. sqlite3 *db = [self get_db];
  567. // int result= [iSalesDB AddExFunction:db];
  568. // [iSalesDB execSql:@"update model_price set price=decrypt(price);" db:db];
  569. // [self execSql:@"PRAGMA journal_mode = WAL;" db:db];
  570. NSString* create_product=@"CREATE TABLE IF NOT EXISTS product ( _id INTEGER PRIMARY KEY, name VARCHAR(20,0), upc_code VARCHAR(42,0), description VARCHAR(20,0), product_id INTEGER, color VARCHAR(20,0), legcolor VARCHAR(20,0), availability INTEGER, incoming_stock INTEGER, ETA DATE, demension VARCHAR(20,0), seat_height VARCHAR(20,0), material VARCHAR(20,0), box_dim VARCHAR(20,0), volume VARCHAR(20,0), weight VARCHAR(20,0), model_set VARCHAR(20,0), load_ability VARCHAR(20,0), default_category VARCHAR(20,0), category VARCHAR(100,0), fabric_content VARCHAR(20,0), assembling VARCHAR(20,0), made_in VARCHAR(20,0), special_remarks VARCHAR(20,0), stockUom integer, fashion VARCHAR(20,0), isnew integer, property_field VARCHAR(20,0), property_display VARCHAR(20,0), selector_field VARCHAR(20,0), selector_display VARCHAR(20,0), product_group VARCHAR(20,0), packaging VARCHAR(20,0), closeout integer ,best_seller integer,alert VARCHAR(20,0),has_bundle integer,is_active integer,item_id integer,more_color integer,seat_dimension text,assembly_instruction text,product_content_writing text);";
  571. NSString* create_catalog=@"CREATE TABLE IF NOT EXISTS catalog ( _id INTEGER PRIMARY KEY, name VARCHAR(20,0), description VARCHAR(20,0), upc_code VARCHAR(42,0), item_id INTEGER,is_active integer,ulength float,uwidth float,uheight float,uweight float,pcs integer,mpack integer,mlength float,mwidth float,mheight float,mweigth float,ipack integer,ilength float,iwidth float,iheight float, iweight float,ucbf float,icbf float, mcbf float,is_single_model integer, is_master_model integer,is_rate integer,is_part integer);";
  572. NSString* create_bundle=@"CREATE TABLE IF NOT EXISTS bundle ( _id INTEGER PRIMARY KEY, product_id integer,product_item_id integer,item_id integer,unit_price double,use_unitprice integer,qty integer);";
  573. NSString* create_price=@"CREATE TABLE IF NOT EXISTS price ( _id INTEGER PRIMARY KEY, name text, type integer, order_by integer,is_show integer,create_time TIMESTAMP DEFAULT(datetime('now','localtime')),modify_time TIMESTAMP DEFAULT(datetime('now','localtime')));";
  574. NSString* create_errlog=@"CREATE TABLE IF NOT EXISTS errlog ( _id INTEGER PRIMARY KEY, errmsg text,module text,params text ,code integer, create_time TIMESTAMP default (datetime('now', 'localtime')));";
  575. NSString* create_image=@"CREATE TABLE IF NOT EXISTS model_image ( _id INTEGER PRIMARY KEY, name VARCHAR(20), url text, type integer, product_id INTEGER,item_id integer, default_img integer,picture_id integer);";
  576. NSString* create_model_price=@"CREATE TABLE IF NOT EXISTS model_price ( _id INTEGER PRIMARY KEY, item_id integer, price text , type integer, price_name text, expire_datetime datetime);";
  577. //NSString* create_model_ext=@"CREATE TABLE IF NOT EXISTS model_ext ( _id INTEGER PRIMARY KEY, product_id INTEGER,carton integer, cuft double, weight double;";
  578. NSString* create_category=@"CREATE TABLE IF NOT EXISTS category ( _id INTEGER PRIMARY KEY, code VARCHAR(20),name VARCHAR(20));";
  579. NSString* create_carrier=@"CREATE TABLE IF NOT EXISTS carrier ( _id INTEGER PRIMARY KEY, code_id integer,name text);";
  580. NSString* create_offline_setting=@"CREATE TABLE IF NOT EXISTS offline_setting ( _id INTEGER PRIMARY KEY, name VARCHAR(20),value VARCHAR(40));";
  581. NSString* create_offline_login=@"CREATE TABLE IF NOT EXISTS offline_login ( _id INTEGER PRIMARY KEY, username VARCHAR(40),password VARCHAR(40), can_show_price integer ,can_see_price integer,contact_id VARCHAR(20),user_type integer,can_cancel_order integer,can_set_cart_price integer,can_create_portfolio integer, can_delete_order integer,can_submit_order integer,can_set_tearsheet_price integer,can_create_order integer, can_update_contact_info integer, mode VARCHAR(20), default_price text, price text, user_id integer,sales_code text,first_name text,last_name text);";
  582. NSString* create_offline_order=@"CREATE TABLE IF NOT EXISTS offline_order ( _id INTEGER PRIMARY KEY,so_id text, order_id text ,status integer, submit_as integer,general_notes TEXT ,internal_notes text,sales_rep TEXT,create_by TEXT, total_price float, erpOrderStatus integer, logist text, lift_gate integer, logistic_note text, paymentType text, credit_card_first_name text, credit_card_last_name text, credit_card_address1 text, credit_card_address2 text, credit_card_zipcode text, credit_card_type text, credit_card_number text, credit_card_security_code text, credit_card_expiration_month text , credit_card_expiration_year text,credit_card_city text, credit_card_state text,customer_cid text,customer_contact text,customer_email text,customer_phone text,customer_fax text,receive_cid text,receive_name text,receive_ext text,receive_contact text, receive_phone text,receive_fax text,receive_email text,sender_cid text,sender_name text,sender_ext text,sender_contact text, sender_phone text,sender_fax text,sender_email text,shipping_billto_cid text,shipping_billto_name text,shipping_billto_ext text,shipping_billto_contact text, shipping_billto_phone text,shipping_billto_fax text,shipping_billto_email text,billing_cid text,billing_name text,billing_ext text,billing_contact text, billing_phone text,billing_fax text,billing_email text,returnto_cid text,returnto_name text,returnto_ext text,returnto_contact text, returnto_phone text,returnto_fax text,returnto_email text, must_call int,poNumber text,comments text,comments_ext text,paymentsAndCredits float,shipping float,lift_gate_value float,handling_fee_value float,sign_picpath text,sync_data text,ship_via text,create_time TIMESTAMP default (datetime('now', 'localtime')),modify_time TIMESTAMP default (datetime('now', 'localtime')),schedule_date TIMESTAMP,vendor_no char,warehouse_name char,terms char,etd TIMESTAMP,carrier char ,sales_terms char,port_destination char);";
  583. NSString* create_offline_cart=@"CREATE TABLE IF NOT EXISTS offline_cart ( _id INTEGER PRIMARY KEY, orderitem_id integer,product_id INTEGER,item_id integer,str_price text , discount float , so_no VARCHAR(40), item_count integer,line_note text,bundle_item text,type integer,create_time TIMESTAMP default (datetime('now', 'localtime')),modify_time TIMESTAMP default (datetime('now', 'localtime')),client_reference char);";
  584. // NSString* create_offline_wish=@"CREATE TABLE IF NOT EXISTS offline_wishlist ( _id INTEGER PRIMARY KEY, product_id INTEGER,qty integer,item_id integer, create_time TIMESTAMP default (datetime('now', 'localtime')));";
  585. NSString* create_wishlist=@"CREATE TABLE IF NOT EXISTS wishlist ( _id INTEGER PRIMARY KEY, user_id INTEGER, product_id integer ,item_id integer , qty integer, is_delete integer, is_dirty integer,create_time TIMESTAMP default (datetime('now', 'localtime')),modify_time TIMESTAMP default (datetime('now', 'localtime')));";
  586. NSString* create_offline_contact=@"CREATE TABLE IF NOT EXISTS offline_contact (_id INTEGER, country VARCHAR(40,0), company_name VARCHAR(40,0), contact_id VARCHAR(20,0), addr_1 text, addr_2 text, addr_3 text, addr_4 text, zipcode varchar(20,0), state VARCHAR(40,0), city VARCHAR(40,0), first_name VARCHAR(40,0), last_name VARCHAR(40,0), phone VARCHAR(40,0), fax VARCHAR(40,0), email VARCHAR(40,0), notes text, price_type VARCHAR(40,0), sales_rep VARCHAR(40,0), type VARCHAR(40,0), create_time timestamp default (datetime('now', 'localtime')), editable integer, contact_name text, addr text, Sales_Order_Customer integer, Sales_Order_Freight_Bill_To integer, Sales_Order_Ship_From integer, Sales_Order_Merchandise_Bill_To integer, Contact_Return_To integer, Sales_Order_Ship_To integer,img_0 TEXT,img_1 TEXT,img_2 TEXT,related_cid VARCHAR(20,0),is_active integer,sync_data text,modify_time TIMESTAMP default (datetime('now', 'localtime')), carrier integer, PRIMARY KEY(_id) );";
  587. // NSString* create_contact_image=@"CREATE TABLE IF NOT EXISTS contact_image ( _id INTEGER PRIMARY KEY, name VARCHAR(20), url VARCHAR(256), contact_id VARCHAR(20));";
  588. NSString* create_login_info=@"CREATE TABLE IF NOT EXISTS login_info ( _id INTEGER PRIMARY KEY, name VARCHAR(256), pwd VARCHAR(256), lastlogin timestamp );";
  589. NSString* create_offline_country=@"CREATE TABLE IF NOT EXISTS offline_country ( _id INTEGER PRIMARY KEY, name text,code VARCHAR(16), countrycode_id integer);";
  590. NSString* create_offline_state=@"CREATE TABLE IF NOT EXISTS offline_state ( _id INTEGER PRIMARY KEY, name text,code VARCHAR(16), country_code VARCHAR(16));";
  591. NSString* create_offline_zipcode=@"CREATE TABLE IF NOT EXISTS offline_zipcode ( _id INTEGER PRIMARY KEY, country text, state text, city text,state_code VARCHAR(16), country_code VARCHAR(16), zipcode VARCHAR(16));";
  592. NSString* create_offline_salesrep=@"CREATE TABLE IF NOT EXISTS offline_salesrep ( _id INTEGER PRIMARY KEY, name text, code text,salesrep_id integer);";
  593. NSString *create_offline_portfolio = @"CREATE TABLE IF NOT EXISTS offline_portfolio (_id integer PRIMARY KEY,product_id integer,name text,description tex,item_id integer,fashion_id integer,available_qty integer,percentage integer,percent double,sheet_price double,sheet_discount double,img text,line_note text,is_delete integer,is_dirty integer,createtime timestamp DEFAULT(datetime('now','localtime')),modify_time timestamp DEFAULT(datetime('now','localtime')));";
  594. NSString *create_offline_pdf = @"create table if not exists offline_pdf (_id integer primary key,tearsheets_id integer,pdf_path text,create_user text,tear_note text,tear_name text,model_info text,configureParams text,is_delete integer,is_dirty integer,is_local integer,off_params text,createtime timestamp default(datetime('now','localtime')),modify_time timestamp DEFAULT(datetime('now','localtime')));";
  595. NSString *create_contact_type = @"create table if not exists contact_type (_id integer primary key,type_name text,is_show integer,create_time TIMESTAMP DEFAULT(datetime('now','localtime')),modify_time TIMESTAMP DEFAULT(datetime('now','localtime')));";
  596. NSString *create_payment_type = @"create table if not exists payment_type (_id integer primary key,type_id text,pay_type text,sort_id int);";
  597. NSString* create_order_trigger=@"CREATE TRIGGER if not exists offline_order_insert after insert on offline_order BEGIN select offline_dirty(); UPDATE offline_order SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_order_update after update on offline_order BEGIN select offline_dirty(); UPDATE offline_order SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_order_delete after delete on offline_order BEGIN select offline_dirty(); END;";
  598. NSString* create_contact_trigger=@"CREATE TRIGGER if not exists offline_contact_insert after insert on offline_contact BEGIN select offline_dirty(); UPDATE offline_contact SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_contact_update after update on offline_contact BEGIN select offline_dirty(); UPDATE offline_contact SET modify_time= datetime('now', 'localtime') WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_contact_delete after delete on offline_contact BEGIN select offline_dirty(); END;";
  599. NSString* create_cart_trigger=@"CREATE TRIGGER if not exists offline_cart_insert after insert on offline_cart BEGIN select offline_dirty(); UPDATE offline_cart SET modify_time= datetime('now', 'localtime') WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_cart_update after update on offline_cart BEGIN select offline_dirty(); UPDATE offline_cart SET modify_time= datetime('now', 'localtime') WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_cart_delete after delete on offline_cart BEGIN select offline_dirty(); END;";
  600. //drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;
  601. NSString* create_wishlist_trigger=@"CREATE TRIGGER if not exists wishlist_insert after insert on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists wishlist_update after update on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists wishlist_delete after DELETE ON wishlist BEGIN select offline_dirty(); END;";
  602. NSString* create_offline_pdf_trigger=@"CREATE TRIGGER if not exists offline_pdf_insert after insert on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_pdf_update after update on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_pdf_delete after DELETE ON offline_pdf BEGIN select offline_dirty(); END;";
  603. NSString* create_offline_portfolio_trigger=@"CREATE TRIGGER if not exists offline_portfolio_insert after insert on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_portfolio_update after update on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_portfolio_delete after DELETE ON offline_portfolio BEGIN select offline_dirty(); END;";
  604. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  605. //if(appDelegate.offline_mode)
  606. {
  607. /*************************ALTER TABLE From V1.4 to V1.5************************************/
  608. [self alterTable:@"model" columns:@"product" rename:YES db:db]; // 需要在创建product之间改名
  609. [self execSql:create_product db:db];
  610. [self execSql:create_wishlist db:db];
  611. [self execSql:create_price db:db];
  612. [self execSql:create_image db:db];
  613. [self execSql:create_model_price db:db];
  614. [self execSql:create_category db:db];
  615. [self execSql:create_carrier db:db];
  616. [self execSql:create_offline_setting db:db];
  617. [self execSql:create_offline_login db:db];
  618. [self execSql:create_offline_cart db:db];
  619. // [self execSql:create_offline_wish db:db];
  620. [self execSql:create_offline_contact db:db];
  621. // [self execSql:create_contact_image db:db];
  622. [self execSql:create_offline_order db:db];
  623. [self execSql:create_offline_country db:db];
  624. [self execSql:create_offline_state db:db];
  625. [self execSql:create_offline_zipcode db:db];
  626. [self execSql:create_offline_salesrep db:db];
  627. [self execSql:create_bundle db:db];
  628. [self execSql:create_catalog db:db];
  629. [self execSql:create_errlog db:db];
  630. [self execSql:create_offline_portfolio db:db];
  631. [self execSql:create_offline_pdf db:db];
  632. [self execSql:create_contact_type db:db];
  633. // v1.90
  634. [self execSql:create_payment_type db:db];
  635. }
  636. [self execSql:create_login_info db:db];
  637. /*************************ALTER TABLE From V1.4 to V1.5************************************/
  638. // [self alterTable:@"model" columns:@"product" rename:YES db:db];
  639. /**
  640. * 2017-06-01 v1.90 add more_color
  641. * 2017-06-30 v1.90 add seat_dimension , assembly_instruction , product_content_writing
  642. */
  643. [self alterTable:@"product" columns:@"has_bundle integer;is_active integer;item_id integer;more_color integer;seat_dimension text;assembly_instruction text;product_content_writing text" rename:NO db:db];
  644. [self alterTable:@"model_image" columns:@"item_id integer;picture_id integer" rename:NO db:db];
  645. [self alterTable:@"model_price" columns:@"item_id integer" rename:NO db:db];
  646. [self alterTable:@"offline_cart" columns:@"orderitem_id integer;item_id integer;str_price text;item_count integer;line_note text;bundle_item text;type integer;create_time timestamp" rename:NO db:db];
  647. [self alterTable:@"offline_cart" columns:@"modify_time TIMESTAMP" rename:NO db:db];
  648. [self alterTable:@"offline_contact" columns:@"is_active integer;sync_data text" rename:NO db:db];
  649. [self alterTable:@"offline_contact" columns:@"modify_time TIMESTAMP" rename:NO db:db];
  650. [self alterTable:@"offline_contact" columns:@"carrier integer " rename:NO db:db];
  651. [self alterTable:@"offline_login" columns:@"can_update_contact_info integer;sales_code text" rename:NO db:db];
  652. [self alterTable:@"wishlist" columns:@"qty integer;item_id integer" rename:NO db:db];
  653. [self alterTable:@"wishlist" columns:@"modify_time TIMESTAMP" rename:NO db:db];
  654. [self alterTable:@"wishlist" columns:@"is_delete integer" rename:NO db:db];
  655. [self alterTable:@"wishlist" columns:@"is_dirty integer" rename:NO db:db];
  656. [self alterTable:@"offline_order" columns:@"modify_time TIMESTAMP;schedule_date TIMESTAMP" rename:NO db:db];
  657. [self alterTable:@"offline_order" columns:@"ship_via text" rename:NO db:db];
  658. [self alterTable:@"offline_order" columns:@"vendor_no char;warehouse_name char;terms char;etd TIMESTAMP;carrier char;sales_terms char;port_destination char" rename:NO db:db];
  659. [self alterTable:@"offline_cart" columns:@"client_reference char" rename:NO db:db];
  660. [self alterTable:@"offline_login" columns:@"first_name text;last_name text" rename:NO db:db];
  661. [self alterTable:@"offline_pdf" columns:@"off_params text" rename:NO db:db];
  662. [self alterTable:@"price" columns:@"is_show integer;create_time TIMESTAMP;modify_time TIMESTAMP" rename:NO db:db];
  663. [self alterTable:@"contact_type" columns:@"is_show integer;create_time TIMESTAMP;modify_time TIMESTAMP" rename:NO db:db];
  664. [self execSql:create_order_trigger db:db];
  665. [self execSql:create_contact_trigger db:db];
  666. [self execSql:create_cart_trigger db:db];
  667. [self execSql:create_wishlist_trigger db:db];
  668. [self execSql:create_offline_pdf_trigger db:db];
  669. [self execSql:create_offline_portfolio_trigger db:db];
  670. // NSString *rename_model_to_product = @"alter model rename to product";
  671. // [self execSql:rename_model_to_product db:db];
  672. //
  673. // if (![self checkForField:@"product" field:@"has_bundle" db:db]) {
  674. //// [self];
  675. // }
  676. //
  677. // if( ![self checkForField:@"offline_login" field:@"sales_code" db:db])
  678. // {
  679. // NSString* alter_search_history = @"ALTER TABLE offline_login ADD sales_code text";
  680. // [self execSql:alter_search_history db:db];
  681. // }
  682. // if( ![self checkForField:@"offline_login" field:@"can_update_contact_info" db:db])
  683. // {
  684. // NSString* alter_search_history = @"ALTER TABLE offline_login ADD can_update_contact_info integer";
  685. // [self execSql:alter_search_history db:db];
  686. // }
  687. // if( ![self checkForField:@"offline_contact" field:@"sync_data" db:db])
  688. // {
  689. // NSString* alter_search_history = @"ALTER TABLE offline_contact ADD sync_data text";
  690. // [self execSql:alter_search_history db:db];
  691. // }
  692. // if( ![self checkForField:@"model_image" field:@"picture_id" db:db])
  693. // {
  694. // NSString* alter_search_history = @"ALTER TABLE model_image ADD picture_id integer";
  695. // [self execSql:alter_search_history db:db];
  696. // }
  697. /**********************************************************************************************/
  698. // NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
  699. // double t = time-2592000; //NSTimeInterval返回的是double类型
  700. // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  701. // [formatter setDateFormat:@"yyyy-MM-dd"];
  702. //
  703. // NSString*timestr=[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:t]];
  704. //
  705. // // [self execSql:[NSString stringWithFormat:@"delete from search_history where h_time<%@",timestr ] db:db];
  706. // [self execSql:@"delete from search_history where julianday('now', 'localtime')-julianday(h_time, 'localtime')>30" db:db];
  707. [iSalesDB close_db:db];
  708. return 0;
  709. // int aaa = 0;
  710. // DebugLog (@"bottom of initializeDb");
  711. }
  712. +(int)execSql:(NSString *)sql db:(sqlite3 *)db
  713. {
  714. int ret=RESULT_TRUE;
  715. char *err;
  716. if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
  717. DebugLog(@"sqlite3_exec failed msg:%s",sqlite3_errmsg(db));
  718. DebugLog(@"sqlite3_exec failed sql:%@",sql);
  719. ret= RESULT_FALSE;
  720. // [iSalesDB close_db:db];
  721. }
  722. // else
  723. // {
  724. // int result=sqlite3_wal_checkpoint(db, NULL);
  725. // }
  726. return ret;
  727. }
  728. + (NSDictionary*) search_pdf:(int) offset limit:(int)limit keywords:(NSString*) keywords
  729. {
  730. sqlite3 *db = [self get_db];
  731. NSMutableDictionary* json = [[NSMutableDictionary alloc] init];
  732. [json setValue:@"1" forKey:@"result"];
  733. NSString *sqlQuery =nil;
  734. if(keywords.length>0)
  735. sqlQuery=[NSString stringWithFormat: @"SELECT _id,name,file_name,send_to,create_params,c_id,c_name,o_id,pdf_type,create_time FROM pdf_cache where lower(name) like '%%%@%%' order by create_time desc limit %d offset %d",keywords,limit,offset];
  736. else
  737. sqlQuery=[NSString stringWithFormat: @"SELECT _id,name,file_name,send_to,create_params,c_id,c_name,o_id,pdf_type,create_time FROM pdf_cache order by create_time desc limit %d offset %d",limit,offset];
  738. sqlite3_stmt * statement;
  739. int count = 0;
  740. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  741. {
  742. while (sqlite3_step(statement) == SQLITE_ROW) {
  743. int _id = sqlite3_column_int(statement, 0);
  744. char *name = (char*)sqlite3_column_text(statement, 1);
  745. NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  746. char *file_name = (char*)sqlite3_column_text(statement, 2);
  747. NSString *nsFileNameStr = [[NSString alloc]initWithUTF8String:file_name];
  748. char *type = (char*)sqlite3_column_text(statement, 8);
  749. NSString *nsTypeStr = [[NSString alloc]initWithUTF8String:type];
  750. char *create_time = (char*)sqlite3_column_text(statement, 9);
  751. NSString *nsTimeStr = [[NSString alloc]initWithUTF8String:create_time];
  752. NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
  753. [item setValue:[NSString stringWithFormat:@"%d",_id] forKey:@"_id"];
  754. [item setValue:nsNameStr forKey:@"name"];
  755. [item setValue:nsTimeStr forKey:@"create_time"];
  756. [item setValue:nsTypeStr forKey:@"type"];
  757. [item setValue:nsFileNameStr forKey:@"file_name"];
  758. [json setObject:item forKey:[NSString stringWithFormat:@"item_%d",count]];
  759. count++;
  760. }
  761. [json setValue:[NSString stringWithFormat:@"%d",count] forKey:@"count"];
  762. [json setValue:@"2" forKey:@"result"];
  763. }
  764. [iSalesDB close_db:db];
  765. return json;
  766. }
  767. +(int)execSql:(NSString *)sql
  768. {
  769. sqlite3 *db = [self get_db];
  770. int ret=[self execSql:sql db:db];
  771. [iSalesDB close_db:db];
  772. return ret;
  773. }
  774. + (int) get_recordid:(NSString*) tablename where:(NSString*) whereclause
  775. {
  776. // [iSalesDB execSql: [NSString stringWithFormat: @"update fields_info set abandon = 1 where user ='%@'",user] db:db];
  777. return [self get_recordid:tablename where:whereclause order:@"_id"];
  778. }
  779. + (int) get_recordcount:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause
  780. {
  781. //sqlite3 *db = [self get_db];
  782. int ret = -1;
  783. NSString *sqlQuery = [NSString stringWithFormat:@"select count(0) from %@ where %@ ;",tablename,whereclause];
  784. DebugLog(@"get_recordcount sql:%@",sqlQuery);
  785. sqlite3_stmt * statement;
  786. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  787. {
  788. if (sqlite3_step(statement) == SQLITE_ROW)
  789. {
  790. // char *name = (char*)sqlite3_column_text(statement, 1);
  791. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  792. ret = sqlite3_column_int(statement, 0);
  793. // char *address = (char*)sqlite3_column_text(statement, 3);
  794. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  795. }
  796. sqlite3_finalize(statement);
  797. }
  798. // [iSalesDB close_db:db];
  799. assert(ret>=0);
  800. return ret;
  801. }
  802. + (int) get_recordid:(NSString*) tablename where:(NSString*) whereclause order:(NSString*) orderby
  803. {
  804. sqlite3 *db = [self get_db];
  805. int ret = -1;
  806. NSString *sqlQuery = [NSString stringWithFormat:@"select _id from %@ where %@ order by %@",tablename,whereclause,orderby];
  807. sqlite3_stmt * statement;
  808. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  809. {
  810. if (sqlite3_step(statement) == SQLITE_ROW)
  811. {
  812. // char *name = (char*)sqlite3_column_text(statement, 1);
  813. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  814. ret = sqlite3_column_int(statement, 0);
  815. // char *address = (char*)sqlite3_column_text(statement, 3);
  816. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  817. }
  818. sqlite3_finalize(statement);
  819. }
  820. [iSalesDB close_db:db];
  821. return ret;
  822. }
  823. + (int) get_insertid:(NSString*) tablename db:(sqlite3*)db
  824. {
  825. // sqlite3 *db = [self get_db];
  826. int ret = -1;
  827. NSString *sqlQuery = [NSString stringWithFormat:@"select last_insert_rowid() from %@ ",tablename];
  828. sqlite3_stmt * statement;
  829. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  830. {
  831. if (sqlite3_step(statement) == SQLITE_ROW)
  832. {
  833. // char *name = (char*)sqlite3_column_text(statement, 1);
  834. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  835. ret = sqlite3_column_int(statement, 0);
  836. // char *address = (char*)sqlite3_column_text(statement, 3);
  837. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  838. }
  839. sqlite3_finalize(statement);
  840. }
  841. // [iSalesDB close_db:db];
  842. return ret;
  843. }
  844. + (int) get_recordid:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause
  845. {
  846. // [iSalesDB execSql: [NSString stringWithFormat: @"update fields_info set abandon = 1 where user ='%@'",user] db:db];
  847. return [self get_recordid:db table:tablename where:whereclause order:@"_id"];
  848. }
  849. + (int) get_recordid:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause order:(NSString*) orderby
  850. {
  851. int ret = -1;
  852. NSString *sqlQuery = [NSString stringWithFormat:@"select _id from %@ where %@ order by %@",tablename,whereclause,orderby];
  853. sqlite3_stmt * statement;
  854. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  855. {
  856. if (sqlite3_step(statement) == SQLITE_ROW)
  857. {
  858. // char *name = (char*)sqlite3_column_text(statement, 1);
  859. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  860. ret = sqlite3_column_int(statement, 0);
  861. // char *address = (char*)sqlite3_column_text(statement, 3);
  862. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  863. }
  864. sqlite3_finalize(statement);
  865. }
  866. return ret;
  867. }
  868. #pragma mark - JK
  869. + (void)alterTable:(NSString *)table columns:(NSString *)column_str_or_new_table_name rename:(BOOL)rename db:(sqlite3 *)db {
  870. if (rename) {
  871. NSString *check_new_table_exist = [NSString stringWithFormat:@"SELECT name FROM sqlite_master WHERE type='table' AND (name='%@' or name = '%@');",table,column_str_or_new_table_name];
  872. __block BOOL new_exist = NO;
  873. __block BOOL old_exist = NO;
  874. [self jk_query:check_new_table_exist db:db close:NO completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  875. const char *name = (char *)sqlite3_column_text(stmt, 0);
  876. if (name == NULL) {
  877. name = "";
  878. }
  879. NSString *nsname = [NSString stringWithUTF8String:name];
  880. if (!old_exist)
  881. old_exist = [nsname isEqualToString:table];
  882. if (!new_exist)
  883. new_exist = [nsname isEqualToString:column_str_or_new_table_name];
  884. }];
  885. if (!new_exist && old_exist) {
  886. NSString *rename_model_to_product = [NSString stringWithFormat:@"alter table %@ rename to %@;",table,column_str_or_new_table_name];
  887. [self execSql:rename_model_to_product db:db];
  888. }
  889. } else {
  890. NSArray *columns = [column_str_or_new_table_name componentsSeparatedByString:@";"];
  891. for (NSString *column in columns) {
  892. NSString *name = [[column componentsSeparatedByString:@" "] firstObject];
  893. // NSString *type = [[column componentsSeparatedByString:@" "] lastObject];
  894. if( ![self checkForField:table field:name db:db])
  895. {
  896. NSString* alter_sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@;",table,column];
  897. [self execSql:alter_sql db:db];
  898. }
  899. }
  900. }
  901. }
  902. + (NSDictionary *)jk_query:(NSString *)sql completion:(queryBlock)block {
  903. return [self jk_query:sql completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  904. if (block) {
  905. block(stmt,container,count);
  906. }
  907. } failure:nil];
  908. }
  909. + (NSDictionary *)jk_query:(NSString *)sql completion:(queryBlock)block failure:(failureBlock)failure {
  910. __block NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  911. sqlite3 *db = [iSalesDB get_db];
  912. NSString *sqlQuery = sql;
  913. sqlite3_stmt * statement;
  914. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  915. long count = 0;
  916. if (block) {
  917. while (sqlite3_step(statement) == SQLITE_ROW) {
  918. block(statement,dic,&count);
  919. }
  920. }
  921. sqlite3_finalize(statement);
  922. } else {
  923. if (failure) {
  924. const char *err = sqlite3_errmsg(db);
  925. if (err == NULL) {
  926. err = "";
  927. }
  928. failure(dic,[NSString stringWithUTF8String:err]);
  929. }
  930. }
  931. [iSalesDB close_db:db];
  932. return [dic copy];
  933. }
  934. + (NSDictionary *)jk_query:(NSString *)sql db:(sqlite3 *)db close:(BOOL)close completion:(queryBlock)block {
  935. __block NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  936. NSString *sqlQuery = sql;
  937. sqlite3_stmt * statement;
  938. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  939. long count = 0;
  940. while (sqlite3_step(statement) == SQLITE_ROW) {
  941. block(statement,dic,&count);
  942. }
  943. [dic setObject:[NSNumber numberWithInteger:RESULT_TRUE] forKey:@"result"];
  944. sqlite3_finalize(statement);
  945. } else {
  946. [dic setObject:[NSNumber numberWithInteger:RESULT_FALSE] forKey:@"result"];
  947. }
  948. if (close) {
  949. [iSalesDB close_db:db];
  950. }
  951. return [dic copy];
  952. }
  953. + (NSString *)jk_queryText:(NSString *)sql{
  954. DebugLog(@"%s sql: %@",__func__,sql);
  955. __block NSString *ret = nil;
  956. sqlite3 *db = [iSalesDB get_db];
  957. NSString *sqlQuery = sql;
  958. sqlite3_stmt * statement;
  959. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  960. while (sqlite3_step(statement) == SQLITE_ROW) {
  961. char *text = (char *)sqlite3_column_text(statement, 0);
  962. if (text == NULL) {
  963. text = "";
  964. }
  965. ret = [NSString stringWithFormat:@"%s",text];
  966. }
  967. sqlite3_finalize(statement);
  968. }
  969. [iSalesDB close_db:db];
  970. return ret;
  971. }
  972. #pragma mark trigger control
  973. +(void) disable_trigger
  974. {
  975. btrigger = false;
  976. }
  977. +(void) enable_trigger
  978. {
  979. btrigger = true;
  980. }
  981. @end