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