iSalesDB.m 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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, discount float);";
  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_order" columns:@"discount float" rename:NO db:db];
  660. [self alterTable:@"offline_cart" columns:@"client_reference char" rename:NO db:db];
  661. [self alterTable:@"offline_login" columns:@"first_name text;last_name text" rename:NO db:db];
  662. [self alterTable:@"offline_pdf" columns:@"off_params text" rename:NO db:db];
  663. [self alterTable:@"price" columns:@"is_show integer;create_time TIMESTAMP;modify_time TIMESTAMP" rename:NO db:db];
  664. [self alterTable:@"contact_type" columns:@"is_show integer;create_time TIMESTAMP;modify_time TIMESTAMP" rename:NO db:db];
  665. [self execSql:create_order_trigger db:db];
  666. [self execSql:create_contact_trigger db:db];
  667. [self execSql:create_cart_trigger db:db];
  668. [self execSql:create_wishlist_trigger db:db];
  669. [self execSql:create_offline_pdf_trigger db:db];
  670. [self execSql:create_offline_portfolio_trigger db:db];
  671. // NSString *rename_model_to_product = @"alter model rename to product";
  672. // [self execSql:rename_model_to_product db:db];
  673. //
  674. // if (![self checkForField:@"product" field:@"has_bundle" db:db]) {
  675. //// [self];
  676. // }
  677. //
  678. // if( ![self checkForField:@"offline_login" field:@"sales_code" db:db])
  679. // {
  680. // NSString* alter_search_history = @"ALTER TABLE offline_login ADD sales_code text";
  681. // [self execSql:alter_search_history db:db];
  682. // }
  683. // if( ![self checkForField:@"offline_login" field:@"can_update_contact_info" db:db])
  684. // {
  685. // NSString* alter_search_history = @"ALTER TABLE offline_login ADD can_update_contact_info integer";
  686. // [self execSql:alter_search_history db:db];
  687. // }
  688. // if( ![self checkForField:@"offline_contact" field:@"sync_data" db:db])
  689. // {
  690. // NSString* alter_search_history = @"ALTER TABLE offline_contact ADD sync_data text";
  691. // [self execSql:alter_search_history db:db];
  692. // }
  693. // if( ![self checkForField:@"model_image" field:@"picture_id" db:db])
  694. // {
  695. // NSString* alter_search_history = @"ALTER TABLE model_image ADD picture_id integer";
  696. // [self execSql:alter_search_history db:db];
  697. // }
  698. /**********************************************************************************************/
  699. // NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
  700. // double t = time-2592000; //NSTimeInterval返回的是double类型
  701. // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  702. // [formatter setDateFormat:@"yyyy-MM-dd"];
  703. //
  704. // NSString*timestr=[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:t]];
  705. //
  706. // // [self execSql:[NSString stringWithFormat:@"delete from search_history where h_time<%@",timestr ] db:db];
  707. // [self execSql:@"delete from search_history where julianday('now', 'localtime')-julianday(h_time, 'localtime')>30" db:db];
  708. [iSalesDB close_db:db];
  709. return 0;
  710. // int aaa = 0;
  711. // DebugLog (@"bottom of initializeDb");
  712. }
  713. +(int)execSql:(NSString *)sql db:(sqlite3 *)db
  714. {
  715. int ret=RESULT_TRUE;
  716. char *err;
  717. if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
  718. DebugLog(@"sqlite3_exec failed msg:%s",sqlite3_errmsg(db));
  719. DebugLog(@"sqlite3_exec failed sql:%@",sql);
  720. ret= RESULT_FALSE;
  721. // [iSalesDB close_db:db];
  722. }
  723. // else
  724. // {
  725. // int result=sqlite3_wal_checkpoint(db, NULL);
  726. // }
  727. return ret;
  728. }
  729. + (NSDictionary*) search_pdf:(int) offset limit:(int)limit keywords:(NSString*) keywords
  730. {
  731. sqlite3 *db = [self get_db];
  732. NSMutableDictionary* json = [[NSMutableDictionary alloc] init];
  733. [json setValue:@"1" forKey:@"result"];
  734. NSString *sqlQuery =nil;
  735. if(keywords.length>0)
  736. 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];
  737. else
  738. 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];
  739. sqlite3_stmt * statement;
  740. int count = 0;
  741. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  742. {
  743. while (sqlite3_step(statement) == SQLITE_ROW) {
  744. int _id = sqlite3_column_int(statement, 0);
  745. char *name = (char*)sqlite3_column_text(statement, 1);
  746. NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  747. char *file_name = (char*)sqlite3_column_text(statement, 2);
  748. NSString *nsFileNameStr = [[NSString alloc]initWithUTF8String:file_name];
  749. char *type = (char*)sqlite3_column_text(statement, 8);
  750. NSString *nsTypeStr = [[NSString alloc]initWithUTF8String:type];
  751. char *create_time = (char*)sqlite3_column_text(statement, 9);
  752. NSString *nsTimeStr = [[NSString alloc]initWithUTF8String:create_time];
  753. NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
  754. [item setValue:[NSString stringWithFormat:@"%d",_id] forKey:@"_id"];
  755. [item setValue:nsNameStr forKey:@"name"];
  756. [item setValue:nsTimeStr forKey:@"create_time"];
  757. [item setValue:nsTypeStr forKey:@"type"];
  758. [item setValue:nsFileNameStr forKey:@"file_name"];
  759. [json setObject:item forKey:[NSString stringWithFormat:@"item_%d",count]];
  760. count++;
  761. }
  762. [json setValue:[NSString stringWithFormat:@"%d",count] forKey:@"count"];
  763. [json setValue:@"2" forKey:@"result"];
  764. }
  765. [iSalesDB close_db:db];
  766. return json;
  767. }
  768. +(int)execSql:(NSString *)sql
  769. {
  770. sqlite3 *db = [self get_db];
  771. int ret=[self execSql:sql db:db];
  772. [iSalesDB close_db:db];
  773. return ret;
  774. }
  775. + (int) get_recordid:(NSString*) tablename where:(NSString*) whereclause
  776. {
  777. // [iSalesDB execSql: [NSString stringWithFormat: @"update fields_info set abandon = 1 where user ='%@'",user] db:db];
  778. return [self get_recordid:tablename where:whereclause order:@"_id"];
  779. }
  780. + (int) get_recordcount:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause
  781. {
  782. //sqlite3 *db = [self get_db];
  783. int ret = -1;
  784. NSString *sqlQuery = [NSString stringWithFormat:@"select count(0) from %@ where %@ ;",tablename,whereclause];
  785. DebugLog(@"get_recordcount sql:%@",sqlQuery);
  786. sqlite3_stmt * statement;
  787. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  788. {
  789. if (sqlite3_step(statement) == SQLITE_ROW)
  790. {
  791. // char *name = (char*)sqlite3_column_text(statement, 1);
  792. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  793. ret = sqlite3_column_int(statement, 0);
  794. // char *address = (char*)sqlite3_column_text(statement, 3);
  795. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  796. }
  797. sqlite3_finalize(statement);
  798. }
  799. // [iSalesDB close_db:db];
  800. assert(ret>=0);
  801. return ret;
  802. }
  803. + (int) get_recordid:(NSString*) tablename where:(NSString*) whereclause order:(NSString*) orderby
  804. {
  805. sqlite3 *db = [self get_db];
  806. int ret = -1;
  807. NSString *sqlQuery = [NSString stringWithFormat:@"select _id from %@ where %@ order by %@",tablename,whereclause,orderby];
  808. sqlite3_stmt * statement;
  809. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  810. {
  811. if (sqlite3_step(statement) == SQLITE_ROW)
  812. {
  813. // char *name = (char*)sqlite3_column_text(statement, 1);
  814. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  815. ret = sqlite3_column_int(statement, 0);
  816. // char *address = (char*)sqlite3_column_text(statement, 3);
  817. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  818. }
  819. sqlite3_finalize(statement);
  820. }
  821. [iSalesDB close_db:db];
  822. return ret;
  823. }
  824. + (int) get_insertid:(NSString*) tablename db:(sqlite3*)db
  825. {
  826. // sqlite3 *db = [self get_db];
  827. int ret = -1;
  828. NSString *sqlQuery = [NSString stringWithFormat:@"select last_insert_rowid() from %@ ",tablename];
  829. sqlite3_stmt * statement;
  830. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  831. {
  832. if (sqlite3_step(statement) == SQLITE_ROW)
  833. {
  834. // char *name = (char*)sqlite3_column_text(statement, 1);
  835. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  836. ret = sqlite3_column_int(statement, 0);
  837. // char *address = (char*)sqlite3_column_text(statement, 3);
  838. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  839. }
  840. sqlite3_finalize(statement);
  841. }
  842. // [iSalesDB close_db:db];
  843. return ret;
  844. }
  845. + (int) get_recordid:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause
  846. {
  847. // [iSalesDB execSql: [NSString stringWithFormat: @"update fields_info set abandon = 1 where user ='%@'",user] db:db];
  848. return [self get_recordid:db table:tablename where:whereclause order:@"_id"];
  849. }
  850. + (int) get_recordid:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause order:(NSString*) orderby
  851. {
  852. int ret = -1;
  853. NSString *sqlQuery = [NSString stringWithFormat:@"select _id from %@ where %@ order by %@",tablename,whereclause,orderby];
  854. sqlite3_stmt * statement;
  855. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  856. {
  857. if (sqlite3_step(statement) == SQLITE_ROW)
  858. {
  859. // char *name = (char*)sqlite3_column_text(statement, 1);
  860. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  861. ret = sqlite3_column_int(statement, 0);
  862. // char *address = (char*)sqlite3_column_text(statement, 3);
  863. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  864. }
  865. sqlite3_finalize(statement);
  866. }
  867. return ret;
  868. }
  869. #pragma mark - JK
  870. + (void)alterTable:(NSString *)table columns:(NSString *)column_str_or_new_table_name rename:(BOOL)rename db:(sqlite3 *)db {
  871. if (rename) {
  872. 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];
  873. __block BOOL new_exist = NO;
  874. __block BOOL old_exist = NO;
  875. [self jk_query:check_new_table_exist db:db close:NO completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  876. const char *name = (char *)sqlite3_column_text(stmt, 0);
  877. if (name == NULL) {
  878. name = "";
  879. }
  880. NSString *nsname = [NSString stringWithUTF8String:name];
  881. if (!old_exist)
  882. old_exist = [nsname isEqualToString:table];
  883. if (!new_exist)
  884. new_exist = [nsname isEqualToString:column_str_or_new_table_name];
  885. }];
  886. if (!new_exist && old_exist) {
  887. NSString *rename_model_to_product = [NSString stringWithFormat:@"alter table %@ rename to %@;",table,column_str_or_new_table_name];
  888. [self execSql:rename_model_to_product db:db];
  889. }
  890. } else {
  891. NSArray *columns = [column_str_or_new_table_name componentsSeparatedByString:@";"];
  892. for (NSString *column in columns) {
  893. NSString *name = [[column componentsSeparatedByString:@" "] firstObject];
  894. // NSString *type = [[column componentsSeparatedByString:@" "] lastObject];
  895. if( ![self checkForField:table field:name db:db])
  896. {
  897. NSString* alter_sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@;",table,column];
  898. [self execSql:alter_sql db:db];
  899. }
  900. }
  901. }
  902. }
  903. + (NSDictionary *)jk_query:(NSString *)sql completion:(queryBlock)block {
  904. return [self jk_query:sql completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  905. if (block) {
  906. block(stmt,container,count);
  907. }
  908. } failure:nil];
  909. }
  910. + (NSDictionary *)jk_query:(NSString *)sql completion:(queryBlock)block failure:(failureBlock)failure {
  911. __block NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  912. sqlite3 *db = [iSalesDB get_db];
  913. NSString *sqlQuery = sql;
  914. sqlite3_stmt * statement;
  915. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  916. long count = 0;
  917. if (block) {
  918. while (sqlite3_step(statement) == SQLITE_ROW) {
  919. block(statement,dic,&count);
  920. }
  921. }
  922. sqlite3_finalize(statement);
  923. } else {
  924. if (failure) {
  925. const char *err = sqlite3_errmsg(db);
  926. if (err == NULL) {
  927. err = "";
  928. }
  929. failure(dic,[NSString stringWithUTF8String:err]);
  930. }
  931. }
  932. [iSalesDB close_db:db];
  933. return [dic copy];
  934. }
  935. + (NSDictionary *)jk_query:(NSString *)sql db:(sqlite3 *)db close:(BOOL)close completion:(queryBlock)block {
  936. __block NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  937. NSString *sqlQuery = sql;
  938. sqlite3_stmt * statement;
  939. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  940. long count = 0;
  941. while (sqlite3_step(statement) == SQLITE_ROW) {
  942. block(statement,dic,&count);
  943. }
  944. [dic setObject:[NSNumber numberWithInteger:RESULT_TRUE] forKey:@"result"];
  945. sqlite3_finalize(statement);
  946. } else {
  947. [dic setObject:[NSNumber numberWithInteger:RESULT_FALSE] forKey:@"result"];
  948. }
  949. if (close) {
  950. [iSalesDB close_db:db];
  951. }
  952. return [dic copy];
  953. }
  954. + (NSString *)jk_queryText:(NSString *)sql{
  955. DebugLog(@"%s sql: %@",__func__,sql);
  956. __block NSString *ret = nil;
  957. sqlite3 *db = [iSalesDB get_db];
  958. NSString *sqlQuery = sql;
  959. sqlite3_stmt * statement;
  960. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  961. while (sqlite3_step(statement) == SQLITE_ROW) {
  962. char *text = (char *)sqlite3_column_text(statement, 0);
  963. if (text == NULL) {
  964. text = "";
  965. }
  966. ret = [NSString stringWithFormat:@"%s",text];
  967. }
  968. sqlite3_finalize(statement);
  969. }
  970. [iSalesDB close_db:db];
  971. return ret;
  972. }
  973. #pragma mark trigger control
  974. +(void) disable_trigger
  975. {
  976. btrigger = false;
  977. }
  978. +(void) enable_trigger
  979. {
  980. btrigger = true;
  981. }
  982. @end