iSalesDB.m 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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), 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_offline_setting=@"CREATE TABLE IF NOT EXISTS offline_setting ( _id INTEGER PRIMARY KEY, name VARCHAR(20),value VARCHAR(40));";
  580. 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);";
  581. 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')),vendor_no char,warehouse_name char,terms char,etd TIMESTAMP,carrier char ,sales_terms char,port_destination char);";
  582. 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);";
  583. // 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')));";
  584. 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')));";
  585. 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')), PRIMARY KEY(_id) );";
  586. // 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));";
  587. NSString* create_login_info=@"CREATE TABLE IF NOT EXISTS login_info ( _id INTEGER PRIMARY KEY, name VARCHAR(256), pwd VARCHAR(256), lastlogin timestamp );";
  588. NSString* create_offline_country=@"CREATE TABLE IF NOT EXISTS offline_country ( _id INTEGER PRIMARY KEY, name text,code VARCHAR(16), countrycode_id integer);";
  589. NSString* create_offline_state=@"CREATE TABLE IF NOT EXISTS offline_state ( _id INTEGER PRIMARY KEY, name text,code VARCHAR(16), country_code VARCHAR(16));";
  590. 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));";
  591. NSString* create_offline_salesrep=@"CREATE TABLE IF NOT EXISTS offline_salesrep ( _id INTEGER PRIMARY KEY, name text, code text,salesrep_id integer);";
  592. 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')));";
  593. 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')));";
  594. 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')));";
  595. NSString *create_payment_type = @"create table if not exists payment_type (_id integer primary key,type_id text,pay_type text,sort_id int);";
  596. 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;";
  597. 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;";
  598. 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;";
  599. //drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;
  600. 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;";
  601. 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;";
  602. 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;";
  603. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  604. //if(appDelegate.offline_mode)
  605. {
  606. /*************************ALTER TABLE From V1.4 to V1.5************************************/
  607. [self alterTable:@"model" columns:@"product" rename:YES db:db]; // 需要在创建product之间改名
  608. [self execSql:create_product db:db];
  609. [self execSql:create_wishlist db:db];
  610. [self execSql:create_price db:db];
  611. [self execSql:create_image db:db];
  612. [self execSql:create_model_price db:db];
  613. [self execSql:create_category db:db];
  614. [self execSql:create_offline_setting db:db];
  615. [self execSql:create_offline_login db:db];
  616. [self execSql:create_offline_cart db:db];
  617. // [self execSql:create_offline_wish db:db];
  618. [self execSql:create_offline_contact db:db];
  619. // [self execSql:create_contact_image db:db];
  620. [self execSql:create_offline_order db:db];
  621. [self execSql:create_offline_country db:db];
  622. [self execSql:create_offline_state db:db];
  623. [self execSql:create_offline_zipcode db:db];
  624. [self execSql:create_offline_salesrep db:db];
  625. [self execSql:create_bundle db:db];
  626. [self execSql:create_catalog db:db];
  627. [self execSql:create_errlog db:db];
  628. [self execSql:create_offline_portfolio db:db];
  629. [self execSql:create_offline_pdf db:db];
  630. [self execSql:create_contact_type db:db];
  631. // v1.90
  632. [self execSql:create_payment_type db:db];
  633. }
  634. [self execSql:create_login_info db:db];
  635. /*************************ALTER TABLE From V1.4 to V1.5************************************/
  636. // [self alterTable:@"model" columns:@"product" rename:YES db:db];
  637. /**
  638. * 2017-06-01 v1.90 add more_color
  639. * 2017-06-30 v1.90 add seat_dimension , assembly_instruction , product_content_writing
  640. */
  641. [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];
  642. [self alterTable:@"model_image" columns:@"item_id integer;picture_id integer" rename:NO db:db];
  643. [self alterTable:@"model_price" columns:@"item_id integer" rename:NO db:db];
  644. [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];
  645. [self alterTable:@"offline_cart" columns:@"modify_time TIMESTAMP" rename:NO db:db];
  646. [self alterTable:@"offline_contact" columns:@"is_active integer;sync_data text" rename:NO db:db];
  647. [self alterTable:@"offline_contact" columns:@"modify_time TIMESTAMP" rename:NO db:db];
  648. [self alterTable:@"offline_login" columns:@"can_update_contact_info integer;sales_code text" rename:NO db:db];
  649. [self alterTable:@"wishlist" columns:@"qty integer;item_id integer" rename:NO db:db];
  650. [self alterTable:@"wishlist" columns:@"modify_time TIMESTAMP" rename:NO db:db];
  651. [self alterTable:@"wishlist" columns:@"is_delete integer" rename:NO db:db];
  652. [self alterTable:@"wishlist" columns:@"is_dirty integer" rename:NO db:db];
  653. [self alterTable:@"offline_order" columns:@"modify_time TIMESTAMP" rename:NO db:db];
  654. [self alterTable:@"offline_order" columns:@"ship_via text" rename:NO db:db];
  655. [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];
  656. [self alterTable:@"offline_cart" columns:@"client_reference char" rename:NO db:db];
  657. [self alterTable:@"offline_login" columns:@"first_name text;last_name text" rename:NO db:db];
  658. [self alterTable:@"offline_pdf" columns:@"off_params text" rename:NO db:db];
  659. [self alterTable:@"price" columns:@"is_show integer;create_time TIMESTAMP;modify_time TIMESTAMP" rename:NO db:db];
  660. [self alterTable:@"contact_type" columns:@"is_show integer;create_time TIMESTAMP;modify_time TIMESTAMP" rename:NO db:db];
  661. [self execSql:create_order_trigger db:db];
  662. [self execSql:create_contact_trigger db:db];
  663. [self execSql:create_cart_trigger db:db];
  664. [self execSql:create_wishlist_trigger db:db];
  665. [self execSql:create_offline_pdf_trigger db:db];
  666. [self execSql:create_offline_portfolio_trigger db:db];
  667. // NSString *rename_model_to_product = @"alter model rename to product";
  668. // [self execSql:rename_model_to_product db:db];
  669. //
  670. // if (![self checkForField:@"product" field:@"has_bundle" db:db]) {
  671. //// [self];
  672. // }
  673. //
  674. // if( ![self checkForField:@"offline_login" field:@"sales_code" db:db])
  675. // {
  676. // NSString* alter_search_history = @"ALTER TABLE offline_login ADD sales_code text";
  677. // [self execSql:alter_search_history db:db];
  678. // }
  679. // if( ![self checkForField:@"offline_login" field:@"can_update_contact_info" db:db])
  680. // {
  681. // NSString* alter_search_history = @"ALTER TABLE offline_login ADD can_update_contact_info integer";
  682. // [self execSql:alter_search_history db:db];
  683. // }
  684. // if( ![self checkForField:@"offline_contact" field:@"sync_data" db:db])
  685. // {
  686. // NSString* alter_search_history = @"ALTER TABLE offline_contact ADD sync_data text";
  687. // [self execSql:alter_search_history db:db];
  688. // }
  689. // if( ![self checkForField:@"model_image" field:@"picture_id" db:db])
  690. // {
  691. // NSString* alter_search_history = @"ALTER TABLE model_image ADD picture_id integer";
  692. // [self execSql:alter_search_history db:db];
  693. // }
  694. /**********************************************************************************************/
  695. // NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
  696. // double t = time-2592000; //NSTimeInterval返回的是double类型
  697. // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  698. // [formatter setDateFormat:@"yyyy-MM-dd"];
  699. //
  700. // NSString*timestr=[formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:t]];
  701. //
  702. // // [self execSql:[NSString stringWithFormat:@"delete from search_history where h_time<%@",timestr ] db:db];
  703. // [self execSql:@"delete from search_history where julianday('now', 'localtime')-julianday(h_time, 'localtime')>30" db:db];
  704. [iSalesDB close_db:db];
  705. return 0;
  706. // int aaa = 0;
  707. // DebugLog (@"bottom of initializeDb");
  708. }
  709. +(int)execSql:(NSString *)sql db:(sqlite3 *)db
  710. {
  711. int ret=RESULT_TRUE;
  712. char *err;
  713. if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
  714. DebugLog(@"sqlite3_exec failed msg:%s",sqlite3_errmsg(db));
  715. DebugLog(@"sqlite3_exec failed sql:%@",sql);
  716. ret= RESULT_FALSE;
  717. // [iSalesDB close_db:db];
  718. }
  719. // else
  720. // {
  721. // int result=sqlite3_wal_checkpoint(db, NULL);
  722. // }
  723. return ret;
  724. }
  725. + (NSDictionary*) search_pdf:(int) offset limit:(int)limit keywords:(NSString*) keywords
  726. {
  727. sqlite3 *db = [self get_db];
  728. NSMutableDictionary* json = [[NSMutableDictionary alloc] init];
  729. [json setValue:@"1" forKey:@"result"];
  730. NSString *sqlQuery =nil;
  731. if(keywords.length>0)
  732. 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];
  733. else
  734. 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];
  735. sqlite3_stmt * statement;
  736. int count = 0;
  737. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  738. {
  739. while (sqlite3_step(statement) == SQLITE_ROW) {
  740. int _id = sqlite3_column_int(statement, 0);
  741. char *name = (char*)sqlite3_column_text(statement, 1);
  742. NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  743. char *file_name = (char*)sqlite3_column_text(statement, 2);
  744. NSString *nsFileNameStr = [[NSString alloc]initWithUTF8String:file_name];
  745. char *type = (char*)sqlite3_column_text(statement, 8);
  746. NSString *nsTypeStr = [[NSString alloc]initWithUTF8String:type];
  747. char *create_time = (char*)sqlite3_column_text(statement, 9);
  748. NSString *nsTimeStr = [[NSString alloc]initWithUTF8String:create_time];
  749. NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
  750. [item setValue:[NSString stringWithFormat:@"%d",_id] forKey:@"_id"];
  751. [item setValue:nsNameStr forKey:@"name"];
  752. [item setValue:nsTimeStr forKey:@"create_time"];
  753. [item setValue:nsTypeStr forKey:@"type"];
  754. [item setValue:nsFileNameStr forKey:@"file_name"];
  755. [json setObject:item forKey:[NSString stringWithFormat:@"item_%d",count]];
  756. count++;
  757. }
  758. [json setValue:[NSString stringWithFormat:@"%d",count] forKey:@"count"];
  759. [json setValue:@"2" forKey:@"result"];
  760. }
  761. [iSalesDB close_db:db];
  762. return json;
  763. }
  764. +(int)execSql:(NSString *)sql
  765. {
  766. sqlite3 *db = [self get_db];
  767. int ret=[self execSql:sql db:db];
  768. [iSalesDB close_db:db];
  769. return ret;
  770. }
  771. + (int) get_recordid:(NSString*) tablename where:(NSString*) whereclause
  772. {
  773. // [iSalesDB execSql: [NSString stringWithFormat: @"update fields_info set abandon = 1 where user ='%@'",user] db:db];
  774. return [self get_recordid:tablename where:whereclause order:@"_id"];
  775. }
  776. + (int) get_recordcount:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause
  777. {
  778. //sqlite3 *db = [self get_db];
  779. int ret = -1;
  780. NSString *sqlQuery = [NSString stringWithFormat:@"select count(0) from %@ where %@ ;",tablename,whereclause];
  781. DebugLog(@"get_recordcount sql:%@",sqlQuery);
  782. sqlite3_stmt * statement;
  783. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  784. {
  785. if (sqlite3_step(statement) == SQLITE_ROW)
  786. {
  787. // char *name = (char*)sqlite3_column_text(statement, 1);
  788. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  789. ret = sqlite3_column_int(statement, 0);
  790. // char *address = (char*)sqlite3_column_text(statement, 3);
  791. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  792. }
  793. sqlite3_finalize(statement);
  794. }
  795. // [iSalesDB close_db:db];
  796. assert(ret>=0);
  797. return ret;
  798. }
  799. + (int) get_recordid:(NSString*) tablename where:(NSString*) whereclause order:(NSString*) orderby
  800. {
  801. sqlite3 *db = [self get_db];
  802. int ret = -1;
  803. NSString *sqlQuery = [NSString stringWithFormat:@"select _id from %@ where %@ order by %@",tablename,whereclause,orderby];
  804. sqlite3_stmt * statement;
  805. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  806. {
  807. if (sqlite3_step(statement) == SQLITE_ROW)
  808. {
  809. // char *name = (char*)sqlite3_column_text(statement, 1);
  810. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  811. ret = sqlite3_column_int(statement, 0);
  812. // char *address = (char*)sqlite3_column_text(statement, 3);
  813. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  814. }
  815. sqlite3_finalize(statement);
  816. }
  817. [iSalesDB close_db:db];
  818. return ret;
  819. }
  820. + (int) get_insertid:(NSString*) tablename db:(sqlite3*)db
  821. {
  822. // sqlite3 *db = [self get_db];
  823. int ret = -1;
  824. NSString *sqlQuery = [NSString stringWithFormat:@"select last_insert_rowid() from %@ ",tablename];
  825. sqlite3_stmt * statement;
  826. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  827. {
  828. if (sqlite3_step(statement) == SQLITE_ROW)
  829. {
  830. // char *name = (char*)sqlite3_column_text(statement, 1);
  831. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  832. ret = sqlite3_column_int(statement, 0);
  833. // char *address = (char*)sqlite3_column_text(statement, 3);
  834. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  835. }
  836. sqlite3_finalize(statement);
  837. }
  838. // [iSalesDB close_db:db];
  839. return ret;
  840. }
  841. + (int) get_recordid:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause
  842. {
  843. // [iSalesDB execSql: [NSString stringWithFormat: @"update fields_info set abandon = 1 where user ='%@'",user] db:db];
  844. return [self get_recordid:db table:tablename where:whereclause order:@"_id"];
  845. }
  846. + (int) get_recordid:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause order:(NSString*) orderby
  847. {
  848. int ret = -1;
  849. NSString *sqlQuery = [NSString stringWithFormat:@"select _id from %@ where %@ order by %@",tablename,whereclause,orderby];
  850. sqlite3_stmt * statement;
  851. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  852. {
  853. if (sqlite3_step(statement) == SQLITE_ROW)
  854. {
  855. // char *name = (char*)sqlite3_column_text(statement, 1);
  856. // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
  857. ret = sqlite3_column_int(statement, 0);
  858. // char *address = (char*)sqlite3_column_text(statement, 3);
  859. // NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
  860. }
  861. sqlite3_finalize(statement);
  862. }
  863. return ret;
  864. }
  865. #pragma mark - JK
  866. + (void)alterTable:(NSString *)table columns:(NSString *)column_str_or_new_table_name rename:(BOOL)rename db:(sqlite3 *)db {
  867. if (rename) {
  868. 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];
  869. __block BOOL new_exist = NO;
  870. __block BOOL old_exist = NO;
  871. [self jk_query:check_new_table_exist db:db close:NO completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  872. const char *name = (char *)sqlite3_column_text(stmt, 0);
  873. if (name == NULL) {
  874. name = "";
  875. }
  876. NSString *nsname = [NSString stringWithUTF8String:name];
  877. if (!old_exist)
  878. old_exist = [nsname isEqualToString:table];
  879. if (!new_exist)
  880. new_exist = [nsname isEqualToString:column_str_or_new_table_name];
  881. }];
  882. if (!new_exist && old_exist) {
  883. NSString *rename_model_to_product = [NSString stringWithFormat:@"alter table %@ rename to %@;",table,column_str_or_new_table_name];
  884. [self execSql:rename_model_to_product db:db];
  885. }
  886. } else {
  887. NSArray *columns = [column_str_or_new_table_name componentsSeparatedByString:@";"];
  888. for (NSString *column in columns) {
  889. NSString *name = [[column componentsSeparatedByString:@" "] firstObject];
  890. // NSString *type = [[column componentsSeparatedByString:@" "] lastObject];
  891. if( ![self checkForField:table field:name db:db])
  892. {
  893. NSString* alter_sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@;",table,column];
  894. [self execSql:alter_sql db:db];
  895. }
  896. }
  897. }
  898. }
  899. + (NSDictionary *)jk_query:(NSString *)sql completion:(queryBlock)block {
  900. return [self jk_query:sql completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  901. if (block) {
  902. block(stmt,container,count);
  903. }
  904. } failure:nil];
  905. }
  906. + (NSDictionary *)jk_query:(NSString *)sql completion:(queryBlock)block failure:(failureBlock)failure {
  907. __block NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  908. sqlite3 *db = [iSalesDB get_db];
  909. NSString *sqlQuery = sql;
  910. sqlite3_stmt * statement;
  911. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  912. long count = 0;
  913. if (block) {
  914. while (sqlite3_step(statement) == SQLITE_ROW) {
  915. block(statement,dic,&count);
  916. }
  917. }
  918. sqlite3_finalize(statement);
  919. } else {
  920. if (failure) {
  921. const char *err = sqlite3_errmsg(db);
  922. if (err == NULL) {
  923. err = "";
  924. }
  925. failure(dic,[NSString stringWithUTF8String:err]);
  926. }
  927. }
  928. [iSalesDB close_db:db];
  929. return [dic copy];
  930. }
  931. + (NSDictionary *)jk_query:(NSString *)sql db:(sqlite3 *)db close:(BOOL)close completion:(queryBlock)block {
  932. __block NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  933. NSString *sqlQuery = sql;
  934. sqlite3_stmt * statement;
  935. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  936. long count = 0;
  937. while (sqlite3_step(statement) == SQLITE_ROW) {
  938. block(statement,dic,&count);
  939. }
  940. [dic setObject:[NSNumber numberWithInteger:RESULT_TRUE] forKey:@"result"];
  941. sqlite3_finalize(statement);
  942. } else {
  943. [dic setObject:[NSNumber numberWithInteger:RESULT_FALSE] forKey:@"result"];
  944. }
  945. if (close) {
  946. [iSalesDB close_db:db];
  947. }
  948. return [dic copy];
  949. }
  950. + (NSString *)jk_queryText:(NSString *)sql{
  951. DebugLog(@"%s sql: %@",__func__,sql);
  952. __block NSString *ret = nil;
  953. sqlite3 *db = [iSalesDB get_db];
  954. NSString *sqlQuery = sql;
  955. sqlite3_stmt * statement;
  956. if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
  957. while (sqlite3_step(statement) == SQLITE_ROW) {
  958. char *text = (char *)sqlite3_column_text(statement, 0);
  959. if (text == NULL) {
  960. text = "";
  961. }
  962. ret = [NSString stringWithFormat:@"%s",text];
  963. }
  964. sqlite3_finalize(statement);
  965. }
  966. [iSalesDB close_db:db];
  967. return ret;
  968. }
  969. #pragma mark trigger control
  970. +(void) disable_trigger
  971. {
  972. btrigger = false;
  973. }
  974. +(void) enable_trigger
  975. {
  976. btrigger = true;
  977. }
  978. @end