Răsfoiți Sursa

160726 add offline mode

Ray Zhang 9 ani în urmă
părinte
comite
da9ea0a3cf
41 a modificat fișierele cu 4485 adăugiri și 546 ștergeri
  1. 2 1
      RedAnt ERP Mobile/common/AES/AESCrypt.h
  2. 26 1
      RedAnt ERP Mobile/common/AES/AESCrypt.m
  3. 3 2
      RedAnt ERP Mobile/common/AutoScrollImage/SliderPage.m
  4. 22 13
      RedAnt ERP Mobile/common/CommonEditor/CommonEditorViewController.m
  5. 31 5
      RedAnt ERP Mobile/common/Functions/MainViewController.m
  6. 2 2
      RedAnt ERP Mobile/common/Functions/PDF+Web/PDFViewController.m
  7. 106 72
      RedAnt ERP Mobile/common/Functions/cart/CartViewController.m
  8. 18 6
      RedAnt ERP Mobile/common/Functions/category/CategoryViewController.m
  9. 3 2
      RedAnt ERP Mobile/common/Functions/home/HomeTableViewCellTopic.m
  10. 6 4
      RedAnt ERP Mobile/common/Functions/home/HomeViewController.m
  11. 3 0
      RedAnt ERP Mobile/common/Functions/modelDetail/DetailHeaderCell.h
  12. 7 0
      RedAnt ERP Mobile/common/Functions/modelDetail/DetailHeaderCell.m
  13. 3 2
      RedAnt ERP Mobile/common/Functions/modelDetail/DetailTopicCell.m
  14. 61 50
      RedAnt ERP Mobile/common/Functions/modelDetail/DetailViewController.m
  15. 40 0
      RedAnt ERP Mobile/common/Functions/offline/OLDataProvider.h
  16. 2478 0
      RedAnt ERP Mobile/common/Functions/offline/OLDataProvider.m
  17. 26 0
      RedAnt ERP Mobile/common/Functions/offline/OfflineSettingViewController.h
  18. 535 0
      RedAnt ERP Mobile/common/Functions/offline/OfflineSettingViewController.m
  19. 22 0
      RedAnt ERP Mobile/common/Functions/offline/SyncControlPanelViewController.h
  20. 188 0
      RedAnt ERP Mobile/common/Functions/offline/SyncControlPanelViewController.m
  21. 7 5
      RedAnt ERP Mobile/common/Functions/order/OrderDetailViewController.m
  22. 1 1
      RedAnt ERP Mobile/common/Functions/order/OrderListViewController.m
  23. 1 1
      RedAnt ERP Mobile/common/Functions/portfolio/PDFListViewController.m
  24. 1 0
      RedAnt ERP Mobile/common/Functions/portfolio/PortfolioEditQTYViewController.h
  25. 2 1
      RedAnt ERP Mobile/common/Functions/portfolio/PortfolioEditQTYViewController.m
  26. 5 4
      RedAnt ERP Mobile/common/Functions/portfolio/PortfolioViewController.m
  27. 23 7
      RedAnt ERP Mobile/common/Functions/search+itemsearch/ItemSearchViewController.m
  28. 10 7
      RedAnt ERP Mobile/common/Functions/search+itemsearch/SearchViewController.m
  29. 4 4
      RedAnt ERP Mobile/common/Functions/sidemenu/FunctionTestViewController.m
  30. 1 0
      RedAnt ERP Mobile/common/Functions/sidemenu/LoginViewController.h
  31. 51 2
      RedAnt ERP Mobile/common/Functions/sidemenu/LoginViewController.m
  32. 4 3
      RedAnt ERP Mobile/common/Functions/watchlist/WatchListViewController.m
  33. 8 1
      RedAnt ERP Mobile/common/RAUtils.h
  34. 253 157
      RedAnt ERP Mobile/common/RAUtils.m
  35. 7 3
      RedAnt ERP Mobile/common/const.h
  36. 3 2
      RedAnt ERP Mobile/common/customUI/ImageScrollerView.m
  37. 3 2
      RedAnt ERP Mobile/common/customUI/NIDropDown.m
  38. 6 3
      RedAnt ERP Mobile/common/data_provider/iSalesDB.h
  39. 198 61
      RedAnt ERP Mobile/common/data_provider/iSalesDB.m
  40. 2 2
      RedAnt ERP Mobile/common/data_provider/iSalesNetwork.h
  41. 313 120
      RedAnt ERP Mobile/common/data_provider/iSalesNetwork.m

+ 2 - 1
RedAnt ERP Mobile/common/AES/AESCrypt.h

@@ -34,5 +34,6 @@
 
 + (NSString *)encrypt:(NSString *)message password:(NSString *)password;
 + (NSString *)decrypt:(NSString *)base64EncodedString password:(NSString *)password;
-
++ (NSString *)fastdecrypt:(NSString *)base64EncodedString ;
++ (NSString *)fastencrypt:(NSString *)message;
 @end

+ 26 - 1
RedAnt ERP Mobile/common/AES/AESCrypt.m

@@ -36,15 +36,40 @@
 @implementation AESCrypt
 
 + (NSString *)encrypt:(NSString *)message password:(NSString *)password {
-  NSData *encryptedData = [[message dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptedDataUsingKey:[[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:nil];
+    
+//    message=@"NEW PACIFIC DIRECT";
+//    NSData* msgdata=[message dataUsingEncoding:NSUTF8StringEncoding];
+//    NSData* passdata=[password dataUsingEncoding:NSUTF8StringEncoding];
+//    NSData* SHA256Hash = [passdata SHA256Hash];
+//    NSString *SHA256Hashresult = [[NSString alloc] initWithData:SHA256Hash  encoding:NSUTF8StringEncoding];
+  //  message=@"NEW PACIFIC DIRECT";
+  NSData *encryptedData = [[message dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptedDataUsingKey:[[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash]  error:nil];
   NSString *base64EncodedString = [NSString base64StringFromData:encryptedData length:[encryptedData length]];
   return base64EncodedString;
 }
 
 + (NSString *)decrypt:(NSString *)base64EncodedString password:(NSString *)password {
+    if(base64EncodedString==nil)
+        return nil;
+    if(base64EncodedString.length==0)
+        return @"";
   NSData *encryptedData = [NSData base64DataFromString:base64EncodedString];
   NSData *decryptedData = [encryptedData decryptedAES256DataUsingKey:[[password dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:nil];
   return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
 }
 
++ (NSString *)fastdecrypt:(NSString *)base64EncodedString
+{
+    NSString* ret=[self decrypt:base64EncodedString password:@"usai"];
+    if(ret==nil)
+        ret= @"";
+    return ret;
+}
+
++ (NSString *)fastencrypt:(NSString *)message
+{
+    
+    return [self encrypt:message password:@"usai"];
+}
+
 @end

+ 3 - 2
RedAnt ERP Mobile/common/AutoScrollImage/SliderPage.m

@@ -23,7 +23,7 @@
     if(self.image==nil)
     {
         NSString* file_name=[self.img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:self.img_url];
         if(img_data!=nil)
         {
             
@@ -43,7 +43,8 @@
 
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:self.img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         self.image = img;

+ 22 - 13
RedAnt ERP Mobile/common/CommonEditor/CommonEditorViewController.m

@@ -32,7 +32,8 @@
 #import "CustomIOSAlertView.h"
 #import "DefaultAppearance.h"
 #import "DefaultTableHeaderView.h"
-#define NUMBERS @"0123456789\n"
+#define INTNUMBERS @"0123456789\n"
+#define NUMBERS @"0123456789.\n"
 
 
 
@@ -3135,7 +3136,7 @@
                         img_url_up=@"";
                     cell.imgs[0]=img_url_up;
                     NSString* file_name=[img_url0 lastPathComponent];
-                    NSData* img_data=[iSalesDB load_cached_img:file_name];
+                    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url0];
                     if(img_data!=nil)
                     {
                         
@@ -3159,7 +3160,8 @@
                                 
                                 if(downloadimg_data!=nil)
                                 {
-                                    [iSalesDB cache_img:downloadimg_data :file_name ];
+                                    
+                                    [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url0];
                                     
                                     UIImage * img =[UIImage imageWithData:downloadimg_data];
                                     cell.touchImageView0.image=img;
@@ -3195,7 +3197,7 @@
                     
                     cell.imgs[1]=img_url_up;
                     NSString* file_name=[img_url1 lastPathComponent];
-                    NSData* img_data=[iSalesDB load_cached_img:file_name];
+                    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url1];
                     if(img_data!=nil)
                     {
                         
@@ -3220,7 +3222,8 @@
                                 
                                 if(downloadimg_data!=nil)
                                 {
-                                    [iSalesDB cache_img:downloadimg_data :file_name ];
+                                    
+                                    [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url1];
                                     
                                     UIImage * img =[UIImage imageWithData:downloadimg_data];
                                     cell.touchImageView1.image=img;
@@ -3253,7 +3256,7 @@
                         img_url_up=@"";
                     cell.imgs[2]=img_url_up;
                     NSString* file_name=[img_url2 lastPathComponent];
-                    NSData* img_data=[iSalesDB load_cached_img:file_name];
+                    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url2];
                     if(img_data!=nil)
                     {
                         
@@ -3277,7 +3280,8 @@
                                 
                                 if(downloadimg_data!=nil)
                                 {
-                                    [iSalesDB cache_img:downloadimg_data :file_name ];
+                                    
+                                    [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url2];
                                     
                                     UIImage * img =[UIImage imageWithData:downloadimg_data];
                                     cell.touchImageView2.image=img;
@@ -3942,7 +3946,7 @@
             cell.imgModel.image = [UIImage imageNamed:@"loading_s"];
             
             NSString* file_name=[img_url lastPathComponent];
-            NSData* img_data=[iSalesDB load_cached_img:file_name];
+            NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
             if(img_data!=nil)
             {
                 
@@ -3962,7 +3966,8 @@
                         
                         if(downloadimg_data!=nil)
                         {
-                            [iSalesDB cache_img:downloadimg_data :file_name ];
+                            
+                            [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                             
                             UIImage * img =[UIImage imageWithData:downloadimg_data];
                             cell.imgModel.image = img;
@@ -4136,7 +4141,7 @@
             
             
             NSString* file_name=[img_url lastPathComponent];
-            NSData* img_data=[iSalesDB load_cached_img:file_name];
+            NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
             if(img_data!=nil)
             {
                 
@@ -4156,7 +4161,8 @@
                         
                         if(downloadimg_data!=nil)
                         {
-                            [iSalesDB cache_img:downloadimg_data :file_name ];
+                            
+                            [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                             
                             UIImage * img =[UIImage imageWithData:downloadimg_data];
                             cell.imageviewSignature.image=img ;
@@ -5341,7 +5347,10 @@
     if(![keyboard isEqualToString:@"number"] && ![keyboard isEqualToString:@"int"])
         return TRUE;
     NSCharacterSet *cs;
-    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
+    if([keyboard isEqualToString:@"number"])
+        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
+    else
+        cs = [[NSCharacterSet characterSetWithCharactersInString:INTNUMBERS]invertedSet];
     
     NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
     
@@ -5352,7 +5361,7 @@
         return canChange;
     else
     {
-        return canChange&& lenth>textField.text.length;
+        return canChange&& (lenth>textField.text.length ||[string isEqualToString:@""]);
     }
 }
 - (void)textFieldDidEndEditing:(UITextField *)textField

+ 31 - 5
RedAnt ERP Mobile/common/Functions/MainViewController.m

@@ -1243,7 +1243,7 @@
                             msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
                             
                         }
-                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Switch To Cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Switch to pending order", nil),NSLocalizedString(@"Switch to new order", nil), nil];
+                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Switch To Cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil),NSLocalizedString(@"Create new order", nil), nil];
                         
                         
                         
@@ -1252,7 +1252,7 @@
                     }
                     else
                     {
-                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Switch To Cart", nil) message:NSLocalizedString(@"Do you want to switch to a pending order?", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Switch to pending order", nil), nil];
+                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Switch To Cart", nil) message:NSLocalizedString(@"Do you want to switch to a pending order?", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil), nil];
                         
                         // alert.
                         [alert show];
@@ -1308,7 +1308,7 @@
                     
                 }
                 
-                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Switch to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Switch to pending order", nil),NSLocalizedString(@"Switch to new order", nil), nil];
+                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Switch to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil),NSLocalizedString(@"Create new order", nil), nil];
                 
                 // alert.
                 [alert show];
@@ -1689,8 +1689,8 @@
     [map setValue:@"rect_change_password" forKey:@"img"];
     [self.sideMenuItems addObject:map.copy];
 
-    
-    if(false&&appDelegate.user_type==USER_ROLE_EMPLOYEE)
+    #ifdef BUILD_NPD
+    if(appDelegate.user_type==USER_ROLE_EMPLOYEE)
     {
         [map setValue:@"Offline Setting" forKey:@"title"];
         [map setValue:@"rect_market_news" forKey:@"img"];
@@ -1699,6 +1699,7 @@
 
         
     }
+# endif
     
 //    if([[appDelegate.user lowercaseString] isEqualToString:@"larryl"]||[[appDelegate.user lowercaseString] isEqualToString:@"arpithat"])
 //    {
@@ -1721,6 +1722,9 @@
     
     
 #ifdef BUILD_HMLG
+    [map setValue:@"Homelegance Website" forKey:@"title"];
+    [map setValue:@"rect_change_password" forKey:@"img"];
+    [self.sideMenuItems addObject:map.copy];
 #endif
     
 #ifdef BUILD_NPD
@@ -2052,6 +2056,28 @@
         
         
         
+        [self.navigationController pushViewController:ViewController animated:YES];
+        
+    }
+    else if([title isEqualToString:@"Homelegance Website"])
+    {
+        
+        NSString* url = @"http://207.140.24.83";//@"https://www.newpacificdirect.com/general.htm?websiteId=1";//
+        
+        
+        NSString* title = @"Homelegance";
+        //        UIApplication * app = [UIApplication sharedApplication];
+        //        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+        //        MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
+        //
+        //
+        
+        WebViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
+        ViewController.url = url;
+        ViewController.title = title;
+        
+        
+        
         [self.navigationController pushViewController:ViewController animated:YES];
         
     }

+ 2 - 2
RedAnt ERP Mobile/common/Functions/PDF+Web/PDFViewController.m

@@ -152,7 +152,7 @@
         
         NSHTTPURLResponse* urlResponse = nil;
         
-        NSError *error = [[NSError alloc] init];
+        NSError *error = nil;
         
         self.content= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
         
@@ -174,7 +174,7 @@
                // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                 NSString *path = NSTemporaryDirectory();
                 NSString *filePath = [path stringByAppendingPathComponent:self.filename];
-                //    NSError *error = [[NSError alloc] init];
+                //    NSError *error = nil;
                 //    BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
                 //    NSAssert(bo,@"创建目录失败");
                 [self.content writeToFile:filePath atomically:YES];

+ 106 - 72
RedAnt ERP Mobile/common/Functions/cart/CartViewController.m

@@ -344,7 +344,7 @@
 //    
 //    
 //        return;
-//    
+    
     
     [self begin_edit];
 }
@@ -1503,7 +1503,7 @@
     [cell set_Count:count];
     [cell.btnImage setBackgroundImage:[UIImage imageNamed:@"loading_s"] forState:UIControlStateNormal];
     NSString* file_name=[img_url lastPathComponent];
-    NSData* img_data=[iSalesDB load_cached_img:file_name];
+    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
     if(img_data!=nil)
     {
         
@@ -1523,7 +1523,8 @@
                 
                 if(downloadimg_data!=nil)
                 {
-                    [iSalesDB cache_img:downloadimg_data :file_name ];
+                    
+                    [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                     
                     UIImage * img =[UIImage imageWithData:downloadimg_data];
                     [cell.btnImage setBackgroundImage:img forState:UIControlStateNormal];
@@ -1596,73 +1597,73 @@
     
     return;
     
-    ModelItemCell* cell = (ModelItemCell*)[tableView cellForRowAtIndexPath:indexPath];
-    
-    
-    cell.selected = false;
-    //    self.dirty = true;
-    
-    
-    bool check = [[item_json valueForKey:@"check"] boolValue];
-    if(check)
-    {
-        [item_json setValue:@"false" forKey:@"check"];
-        cell.img_checkmark.hidden=true;
-        [self.btnselect setTitle: @"Select all" forState: UIControlStateNormal];
-        //        double totalprice =[[item_json valueForKey:@"subtotal_price"] doubleValue];
-        //        self.total-=totalprice;
-    }
-    else
-    {
-        [item_json setValue:@"true" forKey:@"check"];
-        cell.img_checkmark.hidden=false;
-        //        double totalprice =[[item_json valueForKey:@"subtotal_price"] doubleValue];
-        //        self.total+=totalprice;
-    }
-    
-    
-    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-        
-        
-        NSString *ids=[NSString stringWithFormat:@"%d",[[item_json valueForKey:@"cart_item_id"] intValue]];
-        
-        NSDictionary* check_json = [iSalesNetwork cart_check:ids];
-        
-        dispatch_async(dispatch_get_main_queue(), ^{
-            
-            
-            
-            if([[check_json valueForKey:@"result"] intValue]==2)
-            {
-                
-                
-                if([item_json[@"check"] boolValue]==false)
-                    item_json[@"check"]= @"false";
-                else
-                    item_json[@"check"]= @"true";
-                
-                self.content_arr[indexPath.row] = item_json;
-                //[self.content_data setObject:item_json forKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
-                
-                
-                [self reload_container_getdata:false];
-                
-                
-            }
-            else
-            {
-                [RAUtils message_alert:[check_json valueForKey:@"err_msg"] title:nil controller:self] ;
-            }
-            
-            
-            
-        });
-    });
-    
-    //debug
-    //[self.content_data setObject:item_json forKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
-    
-    [self refresh_total];
+//    ModelItemCell* cell = (ModelItemCell*)[tableView cellForRowAtIndexPath:indexPath];
+//    
+//    
+//    cell.selected = false;
+//    //    self.dirty = true;
+//    
+//    
+//    bool check = [[item_json valueForKey:@"check"] boolValue];
+//    if(check)
+//    {
+//        [item_json setValue:@"false" forKey:@"check"];
+//        cell.img_checkmark.hidden=true;
+//        [self.btnselect setTitle: @"Select all" forState: UIControlStateNormal];
+//        //        double totalprice =[[item_json valueForKey:@"subtotal_price"] doubleValue];
+//        //        self.total-=totalprice;
+//    }
+//    else
+//    {
+//        [item_json setValue:@"true" forKey:@"check"];
+//        cell.img_checkmark.hidden=false;
+//        //        double totalprice =[[item_json valueForKey:@"subtotal_price"] doubleValue];
+//        //        self.total+=totalprice;
+//    }
+//    
+//    
+//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+//        
+//        
+//        NSString *ids=[NSString stringWithFormat:@"%d",[[item_json valueForKey:@"cart_item_id"] intValue]];
+//        
+//        NSDictionary* check_json = [iSalesNetwork cart_check:ids];
+//        
+//        dispatch_async(dispatch_get_main_queue(), ^{
+//            
+//            
+//            
+//            if([[check_json valueForKey:@"result"] intValue]==2)
+//            {
+//                
+//                
+//                if([item_json[@"check"] boolValue]==false)
+//                    item_json[@"check"]= @"false";
+//                else
+//                    item_json[@"check"]= @"true";
+//                
+//                self.content_arr[indexPath.row] = item_json;
+//                //[self.content_data setObject:item_json forKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
+//                
+//                
+//                [self reload_container_getdata:false];
+//                
+//                
+//            }
+//            else
+//            {
+//                [RAUtils message_alert:[check_json valueForKey:@"err_msg"] title:nil controller:self] ;
+//            }
+//            
+//            
+//            
+//        });
+//    });
+//    
+//    //debug
+//    //[self.content_data setObject:item_json forKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
+//    
+//    [self refresh_total];
     //self.labelTotal.text=[NSString stringWithFormat:@"$%.2f",self.total];
 }
 
@@ -2255,9 +2256,42 @@ commitEditingStyle:(UITableViewCellEditingStyle)editingStyle  forRowAtIndexPath:
 #pragma mark - Support scanner
 -(void) onDecodedData:(NSString*) value
 {
-    //   return;
-    
+    int cqty=0;
     
+    for(int i=0;i<self.content_arr.count;i++)
+    {
+        NSDictionary* item= self.content_arr[i];
+        if([item[@"model"] isEqualToString:value])
+            cqty=[item[@"count"]intValue];
+    }
+    if(cqty>0)
+    {
+        
+        
+        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"QTY: %d of this model already in cart. Continue ?",cqty] message:nil preferredStyle:UIAlertControllerStyleAlert];
+        //block代码块取代了delegate
+        
+        
+        
+        UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+            [self addtocart:value];
+        }];
+        
+        UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+            NSLog(@"No");
+        }];
+        [alertControl addAction:actionOne];
+        
+        [alertControl addAction:alertthree];
+        
+        //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
+        
+        
+        [self presentViewController:alertControl animated:YES completion:nil];
+        
+        
+    }
+    else
     [self addtocart:value];
     
     

+ 18 - 6
RedAnt ERP Mobile/common/Functions/category/CategoryViewController.m

@@ -143,6 +143,15 @@
     UIApplication * app = [UIApplication sharedApplication];
     
     AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    
+    if(appDelegate.offline_mode)
+    {
+        [RAUtils message_alert:@"offline mode does not support this function." title:@"Category Filter" controller:self] ;
+        
+        return;
+    }
+    
     NSMutableDictionary* menu =             [appDelegate.categoryMenu mutableCopy];
     
     
@@ -1467,7 +1476,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1487,7 +1496,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;
@@ -1566,7 +1576,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1586,7 +1596,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;
@@ -1662,7 +1673,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1682,7 +1693,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;

+ 3 - 2
RedAnt ERP Mobile/common/Functions/home/HomeTableViewCellTopic.m

@@ -60,7 +60,7 @@
     //        cell.Price.text = price;
     cell.cellImageView.image = [UIImage imageNamed:@"loading_s"];
     NSString* file_name=[img_url lastPathComponent];
-    NSData* img_data=[iSalesDB load_cached_img:file_name];
+    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
     if(img_data!=nil)
     {
         
@@ -80,7 +80,8 @@
                 
                 if(downloadimg_data!=nil)
                 {
-                    [iSalesDB cache_img:downloadimg_data :file_name ];
+                    
+                    [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                     
                     UIImage * img =[UIImage imageWithData:downloadimg_data];
                     cell.cellImageView.image = img;

+ 6 - 4
RedAnt ERP Mobile/common/Functions/home/HomeViewController.m

@@ -506,7 +506,7 @@
         HomeTableViewCellBanner * bannercell=cell;
         NSString* img_url =[view_json valueForKeyPath:@"img"];
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -526,7 +526,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         bannercell.BannerImageView.image = img;
@@ -591,7 +592,7 @@
             [cell.contentView addSubview:btn_item];
             NSString* img_url =[item_json valueForKeyPath:@"img"];
             NSString* file_name=[img_url lastPathComponent];
-            NSData* img_data=[iSalesDB load_cached_img:file_name];
+            NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
             if(img_data!=nil)
             {
                 
@@ -611,7 +612,8 @@
                         
                         if(downloadimg_data!=nil)
                         {
-                            [iSalesDB cache_img:downloadimg_data :file_name ];
+                            
+                            [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                             
                             UIImage * img =[UIImage imageWithData:downloadimg_data];
                             [btn_item setBackgroundImage:img forState:UIControlStateNormal];

+ 3 - 0
RedAnt ERP Mobile/common/Functions/modelDetail/DetailHeaderCell.h

@@ -52,6 +52,7 @@
 
 @property (strong, nonatomic) IBOutlet UILabel *selector_nameLabel;
 //@property (strong, nonatomic) IBOutlet UIButton *selector_valLabel;
+@property (strong, nonatomic) IBOutlet UIImageView *selector_dorpdown;
 @property (strong, nonatomic) IBOutlet UILabel *selector_valLabel;
 @property (strong, nonatomic) IBOutlet UIImageView *selector_imageView;
 @property (strong, nonatomic) IBOutlet UILabel *count_Label;
@@ -83,6 +84,8 @@
 - (void)AddPhoto :(UIImage*)photo ;
 @property (strong, nonatomic) IBOutlet UILabel *selector_label;
 
+-(void)Hide_selector:(bool) bhide;
+
 -(void)ClearPhotos;
 @property int cqty;
 @property int step;

+ 7 - 0
RedAnt ERP Mobile/common/Functions/modelDetail/DetailHeaderCell.m

@@ -509,6 +509,13 @@
     
     [self addtocart:count];
 }
+-(void)Hide_selector:(bool) bhide
+{
+    self.selector_Button.hidden=bhide;
+    self.selector_dorpdown.hidden=bhide;
+    self.selector_imageView.hidden=bhide;
+    
+}
 -(void) addtocart:(int) count
 {
     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

+ 3 - 2
RedAnt ERP Mobile/common/Functions/modelDetail/DetailTopicCell.m

@@ -93,7 +93,7 @@
 //        cell.Price.text = price;
     cell.cellImageView.image = [UIImage imageNamed:@"loading_s"];
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -113,7 +113,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;

+ 61 - 50
RedAnt ERP Mobile/common/Functions/modelDetail/DetailViewController.m

@@ -1074,67 +1074,76 @@ self.isrefreshing=false;
         }
         self.selector = [section_json objectForKey:@"selector"];
         
-        cell.selector_nameLabel.text =[self.selector valueForKey:@"name"];
-        
-        int selector_count = [[self.selector valueForKey:@"count"] intValue];
-        
-        cell.selector_imageView.image = [UIImage imageNamed:@"loading_s"];
-        
-        for(int i=0;i<selector_count;i++)
+        if(self.selector!=nil)
         {
-            NSDictionary* params_json=[[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] objectForKey:@"params"] ;
             
-  //          NSString* aaa=[[[params_json objectForKey:@"param_0"] valueForKey:@"val"] stringValue];
+            [cell Hide_selector:false];
+            cell.selector_nameLabel.text =[self.selector valueForKey:@"name"];
             
+            int selector_count = [[self.selector valueForKey:@"count"] intValue];
             
+            cell.selector_imageView.image = [UIImage imageNamed:@"loading_s"];
             
-            if([[[[params_json objectForKey:@"param_0"] valueForKey:@"val"] stringValue] isEqualToString:self.product_id])
+            for(int i=0;i<selector_count;i++)
             {
-                cell.selector_valLabel.text=[[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] valueForKey:@"title"];
+                NSDictionary* params_json=[[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] objectForKey:@"params"] ;
                 
-                NSString* selectstr=[NSString stringWithFormat:@"%@: %@",[self.selector valueForKey:@"name"],[[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] valueForKey:@"title"]];
+                //          NSString* aaa=[[[params_json objectForKey:@"param_0"] valueForKey:@"val"] stringValue];
                 
-                cell.selector_label.text = selectstr;
                 
-                NSString* img_url = [[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] valueForKey:@"pic_url"];
-                
-
                 
-                NSString* file_name=[img_url lastPathComponent];
-                NSData* img_data=[iSalesDB load_cached_img:file_name];
-                if(img_data!=nil)
+                if([[[[params_json objectForKey:@"param_0"] valueForKey:@"val"] stringValue] isEqualToString:self.product_id])
                 {
-                    dispatch_async(dispatch_get_main_queue(), ^{
-                        UIImage * img =[UIImage imageWithData:img_data];
-                        cell.selector_imageView.image=img;
-                        
-                        
-                        
-                    });
-                }
-                else
-                {
-                    NSData*  downloadimg_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:img_url]];
-                    dispatch_async(dispatch_get_main_queue(), ^{
-                        
-                        
-                        
-                        if(downloadimg_data!=nil)
-                        {
-                            [iSalesDB cache_img:downloadimg_data :file_name ];
-                            
-                            UIImage * img =[UIImage imageWithData:downloadimg_data];
+                    cell.selector_valLabel.text=[[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] valueForKey:@"title"];
+                    
+                    NSString* selectstr=[NSString stringWithFormat:@"%@: %@",[self.selector valueForKey:@"name"],[[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] valueForKey:@"title"]];
+                    
+                    cell.selector_label.text = selectstr;
+                    
+                    NSString* img_url = [[self.selector objectForKey:[NSString stringWithFormat:@"item_%d",i]] valueForKey:@"pic_url"];
+                    
+                    
+                    
+                    NSString* file_name=[img_url lastPathComponent];
+                    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
+                    if(img_data!=nil)
+                    {
+                        dispatch_async(dispatch_get_main_queue(), ^{
+                            UIImage * img =[UIImage imageWithData:img_data];
                             cell.selector_imageView.image=img;
-                        }
-                        else
-                        cell.selector_imageView.image = [UIImage imageNamed:@"notfound_s"];
-                        
-                    });
+                            
+                            
+                            
+                        });
+                    }
+                    else
+                    {
+                        NSData*  downloadimg_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:img_url]];
+                        dispatch_async(dispatch_get_main_queue(), ^{
+                            
+                            
+                            
+                            if(downloadimg_data!=nil)
+                            {
+                                
+                                [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
+                                
+                                UIImage * img =[UIImage imageWithData:downloadimg_data];
+                                cell.selector_imageView.image=img;
+                            }
+                            else
+                                cell.selector_imageView.image = [UIImage imageNamed:@"notfound_s"];
+                            
+                        });
+                    }
+                    
                 }
-                
             }
         }
-        
+        else
+        {
+            [cell Hide_selector:true];
+        }
 //        cell.selector_valLabel.text =[[section_json objectForKey:@"selector"] valueForKey:@"name"];
         
         
@@ -1171,7 +1180,7 @@ self.isrefreshing=false;
             //    if(img_url_l.length>0)
              //      [urls addObject:img_url_l];
                 NSString* file_name=[img_url lastPathComponent];
-                NSData* img_data=[iSalesDB load_cached_img:file_name];
+                NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
                 if(img_data!=nil)
                 {
                     dispatch_async(dispatch_get_main_queue(), ^{
@@ -1198,7 +1207,8 @@ self.isrefreshing=false;
                         
                         if(downloadimg_data!=nil)
                         {
-                            [iSalesDB cache_img:downloadimg_data :file_name ];
+                            
+                            [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                             
                             UIImage * img =[UIImage imageWithData:downloadimg_data];
                             [cell AddPhoto:img];
@@ -1408,7 +1418,7 @@ self.isrefreshing=false;
                 NSString* img_url = [img_json valueForKey:@"img_url"];
                 posy+=height*tableView.bounds.size.width / width;
                 NSString* file_name=[img_url lastPathComponent];
-                NSData* img_data=[iSalesDB load_cached_img:file_name];
+                NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
                 if(img_data!=nil)
                 {
                     
@@ -1429,7 +1439,8 @@ self.isrefreshing=false;
                             
                             if(downloadimg_data!=nil)
                             {
-                                [iSalesDB cache_img:downloadimg_data :file_name ];
+                                
+                                [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                                 
                                 UIImage * img =[UIImage imageWithData:downloadimg_data];
                                 imgview.image = img;

+ 40 - 0
RedAnt ERP Mobile/common/Functions/offline/OLDataProvider.h

@@ -0,0 +1,40 @@
+//
+//  OLDataProvider.h
+//  iSales-NPD
+//
+//  Created by Ray on 2/2/16.
+//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface OLDataProvider : NSObject
++(NSDictionary*) offline_category :(NSMutableDictionary *) params;
++(NSDictionary*) offline_search :(NSMutableDictionary *) params;
++(NSDictionary*) offline_itemsearch :(NSMutableDictionary *) params;
++(NSDictionary*) offline_model :(NSMutableDictionary *) params;
+
++(NSDictionary*) offline_contactlist :(NSMutableDictionary *) params;
++(NSDictionary*) offline_contactinfo :(NSMutableDictionary *) params;
++(NSDictionary*) offline_commoneditor_partialrefresh :(NSMutableDictionary *) params;
++(NSDictionary*) offline_wishlist :(NSMutableDictionary *) params;
++(NSDictionary*) offline_add2wishlist :(NSMutableDictionary *) params;
++(NSDictionary*) offline_deletewishlist :(NSMutableDictionary *) params;
+
+
++(NSDictionary*) offline_login :(NSMutableDictionary *) params;
++(NSDictionary*) offline_logout :(NSMutableDictionary *) params;
+
++(NSDictionary*) offline_category_menu ;
++(NSDictionary*) offline_home ;
+
++(NSDictionary*) offline_notimpl;
+
+
++(bool) check_offlinedata ;
+
+//  category filter, contact advanced search, item search, search,wishlist,
+
+//+(NSDictionary*) model_img :(int)product_id;
+//+(NSDictionary*) model_property :(int)product_id field:(NSString*) value ;
+@end

+ 2478 - 0
RedAnt ERP Mobile/common/Functions/offline/OLDataProvider.m

@@ -0,0 +1,2478 @@
+//
+//  OLDataProvider.m
+//  iSales-NPD
+//
+//  Created by Ray on 2/2/16.
+//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
+//
+
+#import "OLDataProvider.h"
+#import "iSalesDB.h"
+#import "RAUtils.h"
+#import "AESCrypt.h"
+#import "AppDelegate.h"
+
+
+@interface OLDataProvider ()
+
+@end
+
+@implementation OLDataProvider
++(bool) check_offlinedata
+{
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    sqlite3 *db = [iSalesDB get_db];
+    NSString * where=@"1=1";
+//    if(appDelegate.user!=nil)
+//        where=[NSString stringWithFormat:@"lower(username)='%@'",appDelegate.user.lowercaseString];
+    int count = [iSalesDB get_recordcount:db table:@"offline_login" where:where];
+    if(count==0)
+    {
+        return false;
+    }
+    return true;
+//
+    sqlite3_close(db);
+}
++(NSDictionary*) offline_deletewishlist :(NSMutableDictionary *) params
+{
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    NSMutableDictionary* ret=[[NSMutableDictionary alloc]init];
+    sqlite3 *db = [iSalesDB get_db];
+    NSString* collectId=params[@"collectId"];
+    
+    
+    
+    
+    NSString* sqlQuery = [NSString stringWithFormat:@"delete from wishlist where _id in (%@);",collectId];
+    [iSalesDB execSql:sqlQuery];
+    int count=[iSalesDB get_recordcount:db table:@"wishlist" where:@"1=1"];
+    sqlite3_close(db);
+    
+    appDelegate.wish_count =count;
+    
+    [appDelegate update_count_mark];
+    ret[@"result"]= [NSNumber numberWithInt:2];
+    return ret;
+}
++(NSDictionary*) offline_add2wishlist :(NSMutableDictionary *) params
+{
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    NSMutableDictionary* ret=[[NSMutableDictionary alloc]init];
+    sqlite3 *db = [iSalesDB get_db];
+    NSString* product_id=params[@"product_id"];
+    
+    
+    NSArray* arr=[RAUtils string2arr:product_id separator:@","];
+    
+    
+    for(int i=0;i<arr.count;i++)
+    {
+        NSString* where=[NSString stringWithFormat:@"product_id=%@",arr[i]];
+        int count=[iSalesDB get_recordcount:db table:@"wishlist" where:where];
+        if(count==0)
+        {
+            NSString* sqlQuery = [NSString stringWithFormat:@"insert into wishlist(product_id) values('%@');",arr[i]];
+            [iSalesDB execSql:sqlQuery];
+        }
+    }
+    int count=[iSalesDB get_recordcount:db table:@"wishlist" where:@"1=1"];
+    sqlite3_close(db);
+    
+    appDelegate.wish_count =count;
+    
+    [appDelegate update_count_mark];
+    ret[@"result"]= [NSNumber numberWithInt:2];
+    return ret;
+    //
+    //return ret;
+}
++(NSDictionary*) offline_wishlist :(NSMutableDictionary *) params
+{
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    
+    
+    NSString* user = appDelegate.user;
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    NSString* sqlQuery = @"select w.product_id,m.name||'\n'||m.description,w._id from wishlist as w  left join model as m on w.product_id=m.product_id order by w.create_time;";
+    sqlite3_stmt * statement;
+    
+    
+    NSMutableDictionary* ret=[[NSMutableDictionary alloc]init];
+    int count=0;
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            
+            
+            NSMutableDictionary* item=[[NSMutableDictionary alloc]init];
+            
+            int product_id = sqlite3_column_double(statement, 0);
+            
+            
+            
+            
+            
+            char *description = (char*)sqlite3_column_text(statement, 1);
+            if(description==nil)
+                description= "";
+            NSString *nsdescription= [[NSString alloc]initWithUTF8String:description];
+            
+            int item_id = sqlite3_column_double(statement, 2);
+            
+            
+            NSString *nsurl=[self model_category_img:[NSString stringWithFormat:@"%@",[NSNumber numberWithInt:product_id]] model_name:nil];
+            
+//            char *url = (char*)sqlite3_column_text(statement, 3);
+//            if(url==nil)
+//                url="";
+//            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
+            
+            
+            
+            item[@"product_id"]= [NSString stringWithFormat:@"%d",product_id];
+            item[@"item_id"]= [NSString stringWithFormat:@"%d",item_id];
+            item[@"description"]= nsdescription;
+            item[@"img"]= nsurl;
+            
+            
+            
+            ret[[NSString stringWithFormat:@"item_%d",count]]= item;
+            count++;
+            
+        }
+        
+        ret[@"count"]= [NSNumber numberWithInt:count];
+        ret[@"total_count"]= [NSNumber numberWithInt:count];
+        // ret[@"wish_count"]= [NSNumber numberWithInt:count];
+        ret[@"result"]= [NSNumber numberWithInt:2];
+        
+        
+        appDelegate.wish_count =count;
+        
+        [appDelegate update_count_mark];
+        sqlite3_finalize(statement);
+        
+        
+        
+        
+    }
+    
+    sqlite3_close(db);
+    
+    return ret;
+}
++(NSDictionary*) offline_notimpl
+{
+    
+    NSMutableDictionary* ret=[[NSMutableDictionary alloc]init];
+    ret[@"result"]=@"8";
+    ret[@"err_msg"]=@"offline mode does not support this function.";
+    return ret;
+}
++(NSDictionary*) offline_home
+{
+    
+    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
+    NSString *cachefolder = [paths objectAtIndex:0];
+    NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"offline_data/home.json"];
+    
+    
+    NSData* json =nil;
+    json=[NSData dataWithContentsOfFile:img_cache];
+    NSError *error=nil;
+    NSMutableDictionary* menu = [[NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error] mutableCopy];
+    
+    return menu;
+}
++(NSDictionary*) offline_category_menu
+{
+    
+    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
+    NSString *cachefolder = [paths objectAtIndex:0];
+    NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"offline_data/category_menu.json"];
+    
+    
+    NSData* json =nil;
+    json=[NSData dataWithContentsOfFile:img_cache];
+    NSError *error=nil;
+    NSMutableDictionary* menu = [[NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error] mutableCopy];
+    
+    return menu;
+}
++(NSDictionary*) offline_commoneditor_partialrefresh :(NSMutableDictionary *) params
+{
+    NSString* offline_command=params[@"offline_Command"];
+    NSDictionary* ret=nil;
+    if([offline_command isEqualToString:@"model_NIYMAL"])
+    {
+        NSString* category = params[@"category"];
+        ret = [self refresh_model_NIYMAL:category];
+    }
+    return ret;
+}
++(NSDictionary*) refresh_model_NIYMAL :(NSString *) category
+{
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    [ret setValue:@"2" forKey:@"result"];
+    [ret setValue:@"Regular Mode" forKey:@"mode"];
+    NSMutableDictionary* detail1_section = [[self model_NIYMAL:category] mutableCopy];
+    
+    [ret setObject:detail1_section forKey:@"detail_1"];
+    return ret;
+}
+
++(NSMutableDictionary*) get_model_all_price:(NSString*) contact_id product_id:(int) product_id
+{
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+//    NSArray* arr1 = [self get_user_all_price_type];
+    NSArray* arr2 = [self get_contact_default_price_type:contact_id];
+    
+//    NSSet *set1 = [NSSet setWithArray:arr1];
+//    NSMutableSet *set2 = [[NSSet setWithArray:arr2] mutableCopy];
+    
+//    if(appDelegate.contact_id==nil)
+//        set2=[set1 mutableCopy];
+//    else
+//        [set2 intersectsSet:set1];
+    
+    
+//    NSArray *retarr = [set2  allObjects];
+    
+    NSString* whereprice=[RAUtils arr2string:arr2 separator:@"," trim:true brackets:@"'"];
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    NSString* sqlQuery = nil;
+    if(appDelegate.contact_id==nil)
+        sqlQuery=[NSString stringWithFormat:@"select a.name,b.price from price as a left join model_price as b on a.name=b.price_name and b.product_id=%d  order by a.order_by;",product_id];
+    else
+        sqlQuery=[NSString stringWithFormat:@"select a.name,b.price from price as a left join model_price as b on a.name=b.price_name and b.product_id=%d and b.price_name in(%@) order by a.order_by;",product_id,whereprice];
+    sqlite3_stmt * statement;
+    
+    
+    NSMutableDictionary* ret=[[NSMutableDictionary alloc]init];
+    int count=0;
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            
+            
+            NSMutableDictionary* item=[[NSMutableDictionary alloc]init];
+            
+            char *name = (char*)sqlite3_column_text(statement, 0);
+            if(name==nil)
+                name="";
+            NSString *nsname = [[NSString alloc]initWithUTF8String:name];
+            
+           // double price = sqlite3_column_double(statement, 1);
+            
+//            char *isnull = (char*)sqlite3_column_text(statement, 1);
+//            if(isnull==nil)
+//                item[nsname]= @"No Price";
+//            else
+//                item[nsname]= [NSString stringWithFormat:@"%.2f",price];
+
+            
+            char *price = (char*)sqlite3_column_text(statement, 1);
+            if(price!=nil)
+            {
+                NSString* nsprice = [[NSString alloc]initWithUTF8String:price];
+                nsprice=[AESCrypt fastdecrypt:nsprice];
+                if(nsprice.length>0)
+                {
+                    double dp= [nsprice doubleValue];
+                    item[nsname]= [NSString stringWithFormat:@"%.2f",dp];
+                }
+            }
+            else
+            {
+                item[nsname]= @"No Price";
+            }
+            
+            
+            // item[nsname]= nsprice;
+            
+            ret[[NSString stringWithFormat:@"item_%d",count]]= item;
+            count++;
+            
+        }
+        
+        ret[@"count"]= [NSNumber numberWithInt:count];
+        
+        
+        
+        sqlite3_finalize(statement);
+        
+        
+        
+        
+    }
+    
+    sqlite3_close(db);
+    
+    return ret;
+}
+
++(NSNumber*) get_model_default_price:(NSString*) contact_id product_id:(int) product_id
+{
+    NSArray* arr1 = [self get_user_all_price_type];
+    NSArray* arr2 = [self get_contact_default_price_type:contact_id];
+    
+//    NSSet *set1 = [NSSet setWithArray:arr1];
+//    NSMutableSet *set2 = [[NSSet setWithArray:arr2] mutableCopy];
+//    [set2 intersectsSet:set1];
+//    
+//    
+//    NSArray *retarr = [set2  allObjects];
+    
+    NSString* whereprice=nil;
+    if(contact_id==nil)
+        whereprice=[RAUtils arr2string:arr1 separator:@"," trim:true brackets:@"'"];
+    else
+        whereprice=[RAUtils arr2string:arr2 separator:@"," trim:true brackets:@"'"];
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    NSString* sqlQuery = [NSString stringWithFormat:@"select price from model_price where product_id='%d' and price_name in(%@);",product_id,whereprice];
+    sqlite3_stmt * statement;
+    
+    
+    NSNumber* ret = nil;
+    double dprice=DBL_MAX;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+           // double val = sqlite3_column_double(statement, 0);
+            char *price = (char*)sqlite3_column_text(statement, 0);
+            if(price!=nil)
+            {
+                NSString* nsprice = [[NSString alloc]initWithUTF8String:price];
+                nsprice=[AESCrypt fastdecrypt:nsprice];
+                if(nsprice.length>0)
+                {
+                    double dp= [nsprice doubleValue];
+                    if(dp<dprice)
+                        dprice=dp;
+                }
+            }
+        }
+        
+        
+        
+        
+        sqlite3_finalize(statement);
+        
+        
+        
+        
+    }
+    
+    sqlite3_close(db);
+    
+    if(dprice==DBL_MAX)
+        ret= nil;
+    else
+        ret= [NSNumber numberWithDouble:dprice];
+    return ret;
+}
+
++(NSArray*) get_user_all_price_type
+{
+    
+    NSArray* ret=nil;
+    
+    sqlite3 *db = [iSalesDB get_db];
+    // no customer assigned , use login user contact_id
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    NSString* sqlQuery = [NSString stringWithFormat:@"select price from offline_login where username='%@';",appDelegate.user];
+    sqlite3_stmt * statement;
+    
+    
+    
+    
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            char *val = (char*)sqlite3_column_text(statement, 0);
+            if(val==nil)
+                val="";
+            NSString* price = [[NSString alloc]initWithUTF8String:val];
+            
+            ret=[RAUtils string2arr:price separator:OFFLINE_ARRAY_SEPARATOR];
+            
+        }
+        
+        
+        
+        
+        sqlite3_finalize(statement);
+        
+        
+        
+        
+    }
+    
+    sqlite3_close(db);
+    
+    return ret;
+    
+    
+    
+}
++(NSArray*) get_contact_default_price_type:(NSString*) contact_id
+{
+    
+    sqlite3 *db = [iSalesDB get_db];
+    if(contact_id==nil)
+    {
+        // no customer assigned , use login user contact_id
+        
+        UIApplication * app = [UIApplication sharedApplication];
+        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+        NSString* sqlQuery = [NSString stringWithFormat:@"select contact_id from offline_login where username='%@';",appDelegate.user];
+        sqlite3_stmt * statement;
+        
+        
+        
+        
+        //    int count=0;
+        if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+        {
+            
+            
+            if (sqlite3_step(statement) == SQLITE_ROW)
+            {
+                
+                char *val = (char*)sqlite3_column_text(statement, 0);
+                if(val==nil)
+                    val="";
+                contact_id = [[NSString alloc]initWithUTF8String:val];
+                
+                
+                
+            }
+            
+            
+            
+            
+            sqlite3_finalize(statement);
+            
+            
+            
+            
+        }
+        
+        if(contact_id.length<=0)
+        {
+            sqlite3_close(db);
+            return nil;
+        }
+        
+    }
+    
+    NSString* sqlQuery = [NSString stringWithFormat:@"select price_type from offline_contact where contact_id='%@';",contact_id];
+    sqlite3_stmt * statement;
+    
+    
+    
+    NSArray* ret=nil;
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            char *price_type = (char*)sqlite3_column_text(statement, 0);
+            if(price_type==nil)
+                price_type="";
+            NSString *nsprice_type = [[NSString alloc]initWithUTF8String:price_type];
+            if(nsprice_type.length>0)
+                ret=[RAUtils string2arr:nsprice_type separator:OFFLINE_ARRAY_SEPARATOR];
+            else
+                ret=nil;
+            
+            
+        }
+        
+        
+        
+        
+        sqlite3_finalize(statement);
+    }
+    
+    sqlite3_close(db);
+    
+    return ret;
+    
+    
+}
++(NSString*) model_category_img :(NSString *) product_id model_name:(NSString *) model_name
+{
+    
+    
+    NSString* ret= nil;
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    NSString *sqlQuery = nil;
+    //select url,type from model_image where product_id=%d and type=1 order by default_img desc , _id asc limit 1;",product_id
+    
+    if(product_id==nil)
+        sqlQuery = [NSString stringWithFormat:@"select i.url from model m LEFT join model_image i on m.product_id = i.product_id  where m.name=%@ order by i.default_img desc, i._id asc limit 1;",model_name];
+    else
+        sqlQuery = [NSString stringWithFormat:@"select i.url from model m LEFT join model_image i on m.product_id = i.product_id  where m.product_id=%@ order by i.default_img desc, i._id asc limit 1;",product_id];
+    
+    sqlite3_stmt * statement;
+    
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            
+            char *imgurl = (char*)sqlite3_column_text(statement, 0);
+            if(imgurl==nil)
+                imgurl="";
+            NSString *nsimgurl = [[NSString alloc]initWithUTF8String:imgurl];
+            
+            
+            ret=nsimgurl;
+            
+            
+        }
+        
+        sqlite3_finalize(statement);
+    }
+    else
+    {
+        [ret setValue:@"8" forKey:@"result"];
+    }
+    
+    
+    
+    sqlite3_close(db);
+    DebugLog(@"data string: %@",ret );
+    
+    
+    return ret;
+}
++(NSString*) model_default_category :(NSString *) product_id model_name:(NSString *) model_name
+{
+    
+    
+    NSString* ret= nil;
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    NSString *sqlQuery = nil;
+    
+    if(product_id==nil)
+        sqlQuery = [NSString stringWithFormat:@"select default_category from model where name='%@';",model_name];
+    else
+        sqlQuery = [NSString stringWithFormat:@"select default_category from model where product_id=%@;",product_id];
+    
+    sqlite3_stmt * statement;
+    
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            
+            char *default_category = (char*)sqlite3_column_text(statement, 0);
+            if(default_category==nil)
+                default_category="";
+            NSString *nsdefault_category = [[NSString alloc]initWithUTF8String:default_category];
+            nsdefault_category=[nsdefault_category stringByReplacingOccurrencesOfString:@"%#" withString:@""];
+            nsdefault_category=[nsdefault_category stringByReplacingOccurrencesOfString:@"#%" withString:@""];
+            
+            ret=nsdefault_category;
+            
+            
+        }
+        
+        sqlite3_finalize(statement);
+    }
+    else
+    {
+        [ret setValue:@"8" forKey:@"result"];
+    }
+    
+    
+    
+    sqlite3_close(db);
+    DebugLog(@"data string: %@",ret );
+    
+    
+    return ret;
+}
++(NSDictionary*) offline_model :(NSMutableDictionary *) params
+{
+    
+    
+    
+    
+    
+    
+    NSString* model_name = [params valueForKey:@"product_name"];
+    
+    NSString* product_id = [params valueForKey:@"product_id"];
+    
+    NSString* category = [params valueForKey:@"category"];
+    
+    
+    if(category==nil)
+        category = [self model_default_category:product_id model_name:model_name];
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    int count = [iSalesDB get_recordcount:db table:@"model" where:[NSString stringWithFormat:@"category like'#%%%@%%#'",category]];
+    
+    
+    NSString *sqlQuery = nil;
+    
+    if(product_id==nil)
+        sqlQuery = [NSString stringWithFormat:@"select name,description,product_id,color,legcolor,availability,incoming_stock,demension,seat_height,material,box_dim,volume,weight,model_set,load_ability,default_category,fabric_content,assembling,made_in,special_remarks,stockUom,product_group,selector_field,property_field,packaging from model where name='%@';",model_name];
+    else
+        sqlQuery = [NSString stringWithFormat:@"select name,description,product_id,color,legcolor,availability,incoming_stock,demension,seat_height,material,box_dim,volume,weight,model_set,load_ability,default_category,fabric_content,assembling,made_in,special_remarks,stockUom,product_group,selector_field,property_field,packaging from model where product_id=%@;",product_id];
+    
+    sqlite3_stmt * statement;
+    [ret setValue:@"2" forKey:@"result"];
+    [ret setValue:@"3" forKey:@"detail_section_count"];
+    
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            //  NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            
+            char *name = (char*)sqlite3_column_text(statement, 0);
+            if(name==nil)
+                name="";
+            NSString *nsname = [[NSString alloc]initWithUTF8String:name];
+            
+            char *description = (char*)sqlite3_column_text(statement, 1);
+            if(description==nil)
+                description="";
+            NSString *nsdescription = [[NSString alloc]initWithUTF8String:description];
+            
+            
+            int product_id = sqlite3_column_int(statement, 2);
+            
+            
+            char *color = (char*)sqlite3_column_text(statement, 3);
+            if(color==nil)
+                color="";
+            //            NSString *nscolor = [[NSString alloc]initWithUTF8String:color];
+            //
+            //            char *legcolor = (char*)sqlite3_column_text(statement, 4);
+            //            if(legcolor==nil)
+            //                legcolor="";
+            //            NSString *nslegcolor = [[NSString alloc]initWithUTF8String:legcolor];
+            //
+            //
+            int availability = sqlite3_column_int(statement, 5);
+            //
+            //            int incoming_stock = sqlite3_column_int(statement, 6);
+            
+            
+            char *demension = (char*)sqlite3_column_text(statement, 7);
+            if(demension==nil)
+                demension="";
+            NSString *nsdemension = [[NSString alloc]initWithUTF8String:demension];
+            
+            
+            
+            //          ,,,,,,,,,
+            
+            
+            char *seat_height = (char*)sqlite3_column_text(statement, 8);
+            if(seat_height==nil)
+                seat_height="";
+            NSString *nsseat_height = [[NSString alloc]initWithUTF8String:seat_height];
+            
+            
+            char *material = (char*)sqlite3_column_text(statement, 9);
+            if(material==nil)
+                material="";
+            NSString *nsmaterial = [[NSString alloc]initWithUTF8String:material];
+            
+            char *box_dim = (char*)sqlite3_column_text(statement, 10);
+            if(box_dim==nil)
+                box_dim="";
+            NSString *nsbox_dim = [[NSString alloc]initWithUTF8String:box_dim];
+            
+            char *volume = (char*)sqlite3_column_text(statement, 11);
+            if(volume==nil)
+                volume="";
+            NSString *nsvolume = [[NSString alloc]initWithUTF8String:volume];
+            
+            double weight = sqlite3_column_double(statement, 12);
+            
+            char *model_set = (char*)sqlite3_column_text(statement, 13);
+            if(model_set==nil)
+                model_set="";
+            NSString *nsmodel_set = [[NSString alloc]initWithUTF8String:model_set];
+            
+            char *load_ability = (char*)sqlite3_column_text(statement, 14);
+            if(load_ability==nil)
+                load_ability="";
+            NSString *nsload_ability = [[NSString alloc]initWithUTF8String:load_ability];
+            
+            char *default_category = (char*)sqlite3_column_text(statement, 15);
+            if(default_category==nil)
+                default_category="";
+            NSString *nsdefault_category = [[NSString alloc]initWithUTF8String:default_category];
+            
+            
+            char *fabric_content = (char*)sqlite3_column_text(statement, 16);
+            if(fabric_content==nil)
+                fabric_content="";
+            NSString *nsfabric_content = [[NSString alloc]initWithUTF8String:fabric_content];
+            
+            char *assembling = (char*)sqlite3_column_text(statement, 17);
+            if(assembling==nil)
+                assembling="";
+            NSString *nsassembling = [[NSString alloc]initWithUTF8String:assembling];
+            
+            char *made_in = (char*)sqlite3_column_text(statement, 18);
+            if(made_in==nil)
+                made_in="";
+            NSString *nsmade_in = [[NSString alloc]initWithUTF8String:made_in];
+            
+            
+            char *special_remarks = (char*)sqlite3_column_text(statement, 19);
+            if(special_remarks==nil)
+                special_remarks="";
+            NSString *nsspecial_remarks = [[NSString alloc]initWithUTF8String:special_remarks];
+            
+            
+            int stockUcom = sqlite3_column_double(statement, 20);
+            
+            char *product_group = (char*)sqlite3_column_text(statement, 21);
+            if(product_group==nil)
+                product_group="";
+            NSString *nsproduct_group = [[NSString alloc]initWithUTF8String:product_group];
+            
+            //            char *fashion_selector = (char*)sqlite3_column_text(statement, 22);
+            //            if(fashion_selector==nil)
+            //                fashion_selector="";
+            //            NSString *nsfashion_selector = [[NSString alloc]initWithUTF8String:fashion_selector];
+            
+            char *selector_field = (char*)sqlite3_column_text(statement, 22);
+            if(selector_field==nil)
+                selector_field="";
+            NSString *nsselector_field = [[NSString alloc]initWithUTF8String:selector_field];
+            
+            char *property_field = (char*)sqlite3_column_text(statement, 23);
+            if(property_field==nil)
+                property_field="";
+            NSString *nsproperty_field = [[NSString alloc]initWithUTF8String:property_field];
+            
+            
+            
+            char *packaging = (char*)sqlite3_column_text(statement, 24);
+            if(packaging==nil)
+                packaging="";
+            NSString *nspackaging = [[NSString alloc]initWithUTF8String:packaging];
+            
+            [ret setValue:[NSString stringWithFormat:@"%d",product_id] forKey:@"product_id"];
+            
+            NSMutableDictionary* img_section = [[NSMutableDictionary alloc] init];
+            
+            NSString* model_s_img = [self model_category_img:[NSString stringWithFormat:@"%d",product_id] model_name:model_name];
+            
+            [img_section setValue:model_s_img forKey:@"model_s_img"];
+            [img_section setObject:[self model_img:product_id] forKey:@"images"];
+            [img_section setObject:[self model_property:product_id field:nsproperty_field] forKey:@"property"];
+            [img_section setObject:[self model_selector:nsproduct_group field:nsselector_field] forKey:@"selector"];
+            
+            
+            NSString* Availability=nil;
+            if(availability>0)
+                Availability=[NSString stringWithFormat:@"%d",availability];
+            else
+                Availability = @"In Production";
+            
+            [img_section setValue:Availability forKey:@"Availability"];
+            [img_section setValue:[NSString stringWithFormat:@"%d",stockUcom] forKey:@"stockUom"];
+            
+            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
+            
+            
+            NSString* Price=nil;
+            if(appDelegate.bLogin==false)
+                Price=@"Must Sign in.";
+            else
+            {
+                NSNumber* price= [self get_model_default_price:appDelegate.contact_id product_id:product_id];
+                if(price==nil)
+                    Price=@"No Price.";
+                else
+                    Price=[NSString stringWithFormat:@"%.2f",price.floatValue];
+            }
+            
+            [img_section setValue:Price forKey:@"price"];
+            [img_section setValue:nsname forKey:@"model_name"];
+            [img_section setValue:nsdescription forKey:@"model_descrition"];
+            
+            [ret setObject:img_section forKey:@"img_section"];
+            
+            NSMutableDictionary* detail0_section = [[NSMutableDictionary alloc] init];
+            int detail0_item_count=0;
+            
+            [detail0_section setObject:[self model_kvItem:@"Dimension" value:nsdemension] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Seat Height" value:nsseat_height] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Material" value:nsmaterial] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Box dimension" value:nsbox_dim] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Volume" value:nsvolume] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Weight" value:[NSString stringWithFormat:@"%0.2f",weight]] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Set" value:nsmodel_set] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Load ability" value:nsload_ability] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Fabric Content" value:nsfabric_content] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Assembling" value:nsassembling] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Made in" value:nsmade_in] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Special Remarks" value:nsspecial_remarks] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            [detail0_section setObject:[self model_kvItem:@"Packaging" value:nspackaging] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            
+            
+            NSDictionary* pricejson=[self get_model_all_price:appDelegate.contact_id product_id:product_id];
+            for(int l=0;l<[pricejson[@"count"] intValue];l++)
+            {
+                NSDictionary* price_item = pricejson[[NSString stringWithFormat:@"item_%d",l]];
+                [detail0_section setObject:[self model_kvItem:price_item.allKeys[0] value:price_item.allValues[0]] forKey:[NSString stringWithFormat:@"item_%d",detail0_item_count++]];
+            }
+            
+            
+            
+            
+            [detail0_section setValue:[NSString stringWithFormat:@"%d",detail0_item_count] forKey:@"count"];
+            [detail0_section setValue:@"kv" forKey:@"type"];
+            [detail0_section setValue:@"Product Information" forKey:@"title"];
+            
+            [ret setObject:detail0_section forKey:@"detail_0"];
+            
+            
+            NSMutableDictionary* detail1_section = [[self model_NIYMAL:category] mutableCopy];
+            //            [detail1_section setValue:@"detail" forKey:@"target"];
+            //            [detail1_section setValue:@"popup" forKey:@"action"];
+            //            [detail1_section setValue:@"content" forKey:@"type"];
+            //            [detail1_section setValue:@"New Items You May Also Like" forKey:@"title"];
+            //            [detail1_section setValue:@"model_NIYMAL" forKey:@"data_interface"];
+            //            [detail1_section setValue:@"true" forKey:@"single_row"];
+            //            [detail1_section setValue:@"true" forKey:@"partial_refresh"];
+            [ret setObject:detail1_section forKey:@"detail_1"];
+            
+            
+            
+            
+            NSMutableDictionary* detail2_section = [[NSMutableDictionary alloc]init];
+            [detail2_section setValue:@"detail" forKey:@"target"];
+            [detail2_section setValue:@"popup" forKey:@"action"];
+            [detail2_section setValue:@"content" forKey:@"type"];
+            [detail2_section setValue:@"Recently Viewed" forKey:@"title"];
+            [detail2_section setValue:@"true" forKey:@"single_row"];
+            [detail2_section setValue:@"local" forKey:@"data"];
+            [ret setObject:detail2_section forKey:@"detail_2"];
+        }
+        
+        
+        
+        
+        sqlite3_finalize(statement);
+    }
+    else
+    {
+        [ret setValue:@"8" forKey:@"result"];
+    }
+    NSLog(@"count:%d",count);
+    
+    
+    sqlite3_close(db);
+    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
++(NSDictionary*) offline_category :(NSMutableDictionary *) params
+{
+    NSString* orderCode = [params valueForKey:@"orderCode"];
+    
+    NSString* category = [params valueForKey:@"category"];
+    
+    int limit = [[params valueForKey:@"limit"] intValue];
+    int offset = [[params valueForKey:@"offset"] intValue];
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    int count = [iSalesDB get_recordcount:db table:@"model" where:[NSString stringWithFormat:@"category like'%%#%@#%%'",category]];
+    
+    
+    NSString *sqlQuery = [NSString stringWithFormat:@"select m.name,m.description,m.product_id,w._id,m.closeout from model m left join wishlist w on m.product_id=w.product_id where m.category like'%%#%@#%%' order by m.name limit %d offset %d ;",category,limit, offset];
+    
+    DebugLog(@"offline_category sql:%@",sqlQuery);
+    sqlite3_stmt * statement;
+    [ret setValue:@"2" forKey:@"result"];
+    [ret setValue:[NSString stringWithFormat:@"%d",count] forKey:@"item_total_count"];
+    NSMutableDictionary* items = [[NSMutableDictionary alloc] init];
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i=0;
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            //            char *name = (char*)sqlite3_column_text(statement, 1);
+            //            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
+            
+            char *name = (char*)sqlite3_column_text(statement, 0);
+            if(name==nil)
+                name="";
+            NSString *nsname = [[NSString alloc]initWithUTF8String:name];
+            
+            char *description = (char*)sqlite3_column_text(statement, 1);
+            if(description==nil)
+                description="";
+            NSString *nsdescription = [[NSString alloc]initWithUTF8String:description];
+            
+            
+            
+            int product_id = sqlite3_column_int(statement, 2);
+            
+            
+            //            char *url = (char*)sqlite3_column_text(statement, 3);
+            //            if(url==nil)
+            //                url="";
+            //            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
+            
+            int wid = sqlite3_column_int(statement, 3);
+            int closeout = sqlite3_column_int(statement, 4);
+            
+            NSMutableDictionary* imgjson=[self category_img:product_id];
+            
+            if(wid==0)
+                [item setValue:@"false" forKey:@"wish_exists"];
+            else
+                [item setValue:@"true" forKey:@"wish_exists"];
+            
+            if(closeout==0)
+                [item setValue:@"false" forKey:@"is_closeout"];
+            else
+                [item setValue:@"true" forKey:@"is_closeout"];
+            
+            [item addEntriesFromDictionary:imgjson];
+            
+            
+            // [item setValue:nsurl forKey:@"img"];
+            [item setValue:nsname forKey:@"name"];
+            [item setValue:nsdescription forKey:@"description"];
+            [item setValue:[NSString stringWithFormat:@"%d",product_id] forKey:@"product_id"];
+            [items setObject:item forKey:[NSString stringWithFormat:@"item_%d",i]];
+            i++;
+            
+        }
+        [items setValue:[NSString stringWithFormat:@"%d",i] forKey:@"count"];
+        [ret setObject:items forKey:@"items"];
+        sqlite3_finalize(statement);
+    }
+    NSLog(@"count:%d",count);
+    
+    
+    sqlite3_close(db);
+    
+    
+    
+    
+    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
++(NSDictionary*)  offline_search:(NSMutableDictionary *) params
+{
+    
+    
+    
+    
+    
+    
+    NSString* orderCode = [params valueForKey:@"orderCode"];
+    
+    NSString* keyword = [params valueForKey:@"keyword"];
+    keyword=keyword.lowercaseString;
+    
+    bool exactMatch = [[params valueForKey:@"exactMatch"] boolValue];
+    
+    
+    int limit = [[params valueForKey:@"limit"] intValue];
+    int offset = [[params valueForKey:@"offset"] intValue];
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    int count = [iSalesDB get_recordcount:db table:@"model" where:[NSString stringWithFormat:@"lower(name) like'%%%@%%' or lower(description) like'%%%@%%'",keyword,keyword]];
+    
+    
+    NSString *sqlQuery = nil;
+    if(exactMatch )
+        sqlQuery=[NSString stringWithFormat:@"select m.name,m.description,m.product_id,w._id,m.closeout from model m left join wishlist w on m.product_id=w.product_id where lower(name) like'%@%%' order by m.name limit %d offset %d ;",keyword,limit, offset];
+    else
+        sqlQuery=[NSString stringWithFormat:@"select m.name,m.description,m.product_id,w._id,m.closeout from model m left join wishlist w on m.product_id=w.product_id where lower(name) like'%%%@%%' or lower(description) like'%%%@%%' order by m.name limit %d offset %d ;",keyword,keyword,limit, offset];
+    
+    DebugLog(@"offline_search sql:%@",sqlQuery);
+    sqlite3_stmt * statement;
+    [ret setValue:@"2" forKey:@"result"];
+    [ret setValue:[NSString stringWithFormat:@"%d",count] forKey:@"item_total_count"];
+    NSMutableDictionary* items = [[NSMutableDictionary alloc] init];
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i=0;
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            //            char *name = (char*)sqlite3_column_text(statement, 1);
+            //            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
+            
+            char *name = (char*)sqlite3_column_text(statement, 0);
+            NSString *nsname = [[NSString alloc]initWithUTF8String:name];
+            
+            char *description = (char*)sqlite3_column_text(statement, 1);
+            NSString *nsdescription = [[NSString alloc]initWithUTF8String:description];
+            
+            
+            
+            int product_id = sqlite3_column_int(statement, 2);
+            
+            
+            //            char *url = (char*)sqlite3_column_text(statement, 3);
+            //            if(url==nil)
+            //                url="";
+            //            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
+            
+            int wid = sqlite3_column_int(statement, 3);
+            int closeout = sqlite3_column_int(statement, 4);
+            
+            NSMutableDictionary* imgjson=[self category_img:product_id];
+            
+            if(wid==0)
+                [item setValue:@"false" forKey:@"wish_exists"];
+            else
+                [item setValue:@"true" forKey:@"wish_exists"];
+            
+            if(closeout==0)
+                [item setValue:@"false" forKey:@"is_closeout"];
+            else
+                [item setValue:@"true" forKey:@"is_closeout"];
+            
+            [item addEntriesFromDictionary:imgjson];
+            
+            
+            // [item setValue:nsurl forKey:@"img"];
+            [item setValue:nsname forKey:@"fash_name"];
+            [item setValue:nsdescription forKey:@"description"];
+            [item setValue:[NSString stringWithFormat:@"%d",product_id] forKey:@"product_id"];
+            [items setObject:item forKey:[NSString stringWithFormat:@"item_%d",i]];
+            i++;
+            
+        }
+        [items setValue:[NSString stringWithFormat:@"%d",i] forKey:@"count"];
+        [ret setObject:items forKey:@"items"];
+        sqlite3_finalize(statement);
+    }
+    NSLog(@"count:%d",count);
+    
+    
+    sqlite3_close(db);
+    
+    
+    
+    
+    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
++(NSDictionary*)  offline_itemsearch:(NSMutableDictionary *) params
+{
+    
+    
+    
+    //    [params setValue:covertype forKey:@"covertype"];
+    //    [params setValue:ctgid forKey:@"ctgId"];
+    //    [params setValue:modelname forKey:@"modelName"];
+    //    [params setValue:modeldescrip forKey:@"modelDescription"];
+    //    [params setValue:alert forKey:@"alert"];
+    //    [params setValue:qty forKey:@"sold_by_qty"];
+    //    [params setValue:available forKey:@"available"];
+    //    [params setValue:price forKey:@"price"];
+    //    [params setValue:bestseller forKey:@"bestseller"];
+    
+    NSString* orderCode = [params valueForKey:@"orderCode"];
+    int covertype = [[params valueForKey:@"covertype"] intValue];
+    
+    NSString* where= nil;
+    NSString* orderby= @"m.name";
+    switch (covertype) {
+        case 0:
+        {
+            where=@"m.category like'%%#005#%%'";
+            break;
+        }
+        case 1:
+        {
+            where=@"m.alert like '%QS%'";
+            break;
+        }
+        case 2:
+        {
+            where=@"m.availability>0";
+            break;
+        }
+        case 3:
+        {
+            where=@"m.best_seller>0";
+            orderby=@"m.best_seller desc";
+            break;
+        }
+        default:
+            where=@"1=1";
+            break;
+    }
+    //   NSString* keyword = [params valueForKey:@"keyword"];
+    
+    //    bool exactMatch = [[params valueForKey:@"exactMatch"] boolValue];
+    
+    
+    int limit = [[params valueForKey:@"limit"] intValue];
+    int offset = [[params valueForKey:@"offset"] intValue];
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    int count = [iSalesDB get_recordcount:db table:@"model" where:where];
+    
+    
+    NSString *sqlQuery = nil;
+    sqlQuery=[NSString stringWithFormat:@"select m.name,m.description,m.product_id,w._id,m.closeout from model m left join wishlist w on m.product_id=w.product_id where %@ order by %@ limit %d offset %d ;",where,orderby,limit, offset];
+    
+    DebugLog(@"offline_itemsearch sql:%@",sqlQuery);
+    sqlite3_stmt * statement;
+    [ret setValue:@"2" forKey:@"result"];
+    [ret setValue:[NSString stringWithFormat:@"%d",count] forKey:@"item_total_count"];
+    NSMutableDictionary* items = [[NSMutableDictionary alloc] init];
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i=0;
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            //            char *name = (char*)sqlite3_column_text(statement, 1);
+            //            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
+            
+            char *name = (char*)sqlite3_column_text(statement, 0);
+            NSString *nsname = [[NSString alloc]initWithUTF8String:name];
+            
+            char *description = (char*)sqlite3_column_text(statement, 1);
+            NSString *nsdescription = [[NSString alloc]initWithUTF8String:description];
+            
+            
+            
+            int product_id = sqlite3_column_int(statement, 2);
+            
+            
+            //            char *url = (char*)sqlite3_column_text(statement, 3);
+            //            if(url==nil)
+            //                url="";
+            //            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
+            
+            int wid = sqlite3_column_int(statement, 3);
+            int closeout = sqlite3_column_int(statement, 4);
+            
+            NSMutableDictionary* imgjson=[self category_img:product_id];
+            
+            if(wid==0)
+                [item setValue:@"false" forKey:@"wish_exists"];
+            else
+                [item setValue:@"true" forKey:@"wish_exists"];
+            
+            if(closeout==0)
+                [item setValue:@"false" forKey:@"is_closeout"];
+            else
+                [item setValue:@"true" forKey:@"is_closeout"];
+            
+            [item addEntriesFromDictionary:imgjson];
+            
+            
+            // [item setValue:nsurl forKey:@"img"];
+            [item setValue:nsname forKey:@"fash_name"];
+            [item setValue:nsdescription forKey:@"description"];
+            [item setValue:[NSString stringWithFormat:@"%d",product_id] forKey:@"product_id"];
+            [items setObject:item forKey:[NSString stringWithFormat:@"item_%d",i]];
+            i++;
+            
+        }
+        [items setValue:[NSString stringWithFormat:@"%d",i] forKey:@"count"];
+        [ret setObject:items forKey:@"items"];
+        sqlite3_finalize(statement);
+    }
+    NSLog(@"count:%d",count);
+    
+    
+    sqlite3_close(db);
+    
+    
+    
+    
+    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
++(NSDictionary*) offline_logout :(NSMutableDictionary *) params
+{
+    
+    
+//    
+//    NSString* user = [params valueForKey:@"user"];
+//    
+//    NSString* password = [params valueForKey:@"password"];
+    
+    
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    ret[@"result"]=[NSNumber numberWithInt:2 ];
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    appDelegate.cart_count = 0;//[[jsobj valueForKey:@"cart_count"] intValue];
+    appDelegate.wish_count =0;//[[jsobj valueForKey:@"wish_count"] intValue];
+    appDelegate.port_count =0;//[[jsobj valueForKey:@"portfolio_count"] intValue];
+    
+    [appDelegate update_count_mark];
+    
+    
+    appDelegate.can_show_price =false;
+    appDelegate.can_see_price =false;
+    appDelegate.can_create_portfolio =false;
+    appDelegate.can_create_order =false;
+    
+    
+    appDelegate.can_cancel_order =false;
+    appDelegate.can_set_cart_price =false;
+    appDelegate.can_delete_order =false;
+    appDelegate.can_submit_order =false;
+    appDelegate.can_set_tearsheet_price =false;
+    appDelegate.can_update_contact_info = false;
+    
+    appDelegate.save_order_logout = false;
+    appDelegate.submit_order_logout = false;
+    appDelegate.alert_sold_in_quantities = false;
+    
+    appDelegate.ipad_perm =nil ;
+    appDelegate.user_type = USER_ROLE_UNKNOWN;
+    appDelegate.OrderFilter= nil;
+    [appDelegate SetSo:nil];
+    [appDelegate set_main_button_panel];
+    
+    
+//    sqlite3 *db = [iSalesDB get_db];
+//
+//
+//
+//
+//
+//    NSString *sqlQuery = [NSString stringWithFormat:@"select 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 from offline_login where lower(username)='%@' and password='%@'",user.lowercaseString ,[AESCrypt encrypt:password password:@"usai"]];
+//    
+//    
+//    
+//    
+//    DebugLog(@"offline_login sql:%@",sqlQuery);
+//    sqlite3_stmt * statement;
+//    
+//    
+//    [ret setValue:[NSNumber numberWithInt:AP_USER_NOT_AUTH ] forKey:@"result"];
+//    
+//    
+//    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+//    {
+//        
+//        
+//        if (sqlite3_step(statement) == SQLITE_ROW)
+//        {
+//            
+//            [ret setValue:[NSNumber numberWithInt:AP_USER_AUTH ] forKey:@"result"];
+//            NSMutableDictionary* header = [[NSMutableDictionary alloc] init];
+//            
+//            
+//            
+//            int can_show_price = sqlite3_column_int(statement, 0);
+//            int can_see_price = sqlite3_column_int(statement, 1);
+//            
+//            char *contact_id = (char*)sqlite3_column_text(statement, 2);
+//            if(contact_id==nil)
+//                contact_id="";
+//            NSString *nscontact_id= [[NSString alloc]initWithUTF8String:contact_id];
+//            
+//            int user_type = sqlite3_column_int(statement, 3);
+//            
+//            int can_cancel_order = sqlite3_column_int(statement, 4);
+//            int can_set_cart_price = sqlite3_column_int(statement, 5);
+//            int can_create_portfolio = sqlite3_column_int(statement, 6);
+//            int can_delete_order = sqlite3_column_int(statement, 7);
+//            int can_submit_order = sqlite3_column_int(statement, 8);
+//            int can_set_tearsheet_price = sqlite3_column_int(statement, 9);
+//            int can_create_order = sqlite3_column_int(statement, 10);
+//            
+//            
+//            char *mode = (char*)sqlite3_column_text(statement, 11);
+//            if(mode==nil)
+//                mode="";
+//            NSString *nsmode= [[NSString alloc]initWithUTF8String:mode];
+//            
+//            
+//            char *username = (char*)sqlite3_column_text(statement, 12);
+//            if(username==nil)
+//                username="";
+//            NSString *nsusername= [[NSString alloc]initWithUTF8String:username];
+//            
+//            
+//            [header setValue:[NSNumber numberWithBool:can_show_price]   forKey:@"can_show_price"];
+//            [header setValue:[NSNumber numberWithBool:can_see_price]   forKey:@"can_see_price"];
+//            [header setValue:nscontact_id   forKey:@"contact_id"];
+//            [header setValue:[NSNumber numberWithBool:user_type]   forKey:@"user_type"];
+//            [header setValue:[NSNumber numberWithBool:can_cancel_order]   forKey:@"can_cancel_order"];
+//            [header setValue:[NSNumber numberWithBool:can_set_cart_price]   forKey:@"can_set_cart_price"];
+//            [header setValue:[NSNumber numberWithBool:can_create_portfolio]   forKey:@"can_create_portfolio"];
+//            [header setValue:[NSNumber numberWithBool:can_delete_order]   forKey:@"can_delete_order"];
+//            [header setValue:[NSNumber numberWithBool:can_submit_order]   forKey:@"can_submit_order"];
+//            [header setValue:[NSNumber numberWithBool:can_set_tearsheet_price]   forKey:@"can_set_tearsheet_price"];
+//            [header setValue:[NSNumber numberWithBool:can_create_order]   forKey:@"can_create_order"];
+//            
+//            [header setValue:nsusername   forKey:@"username"];
+//            
+//            
+//            [ret setObject:header forKey:@"header"];
+//            [ret setValue:nsmode   forKey:@"mode"];
+//            
+//            
+//        }
+//        
+//        
+//        
+//        sqlite3_finalize(statement);
+//    }
+//    
+//    
+//    
+//    sqlite3_close(db);
+//    
+//    
+//    
+//    
+//    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
+
++(NSDictionary*) offline_login :(NSMutableDictionary *) params
+{
+    
+    
+    
+    NSString* user = [params valueForKey:@"user"];
+    
+    NSString* password = [params valueForKey:@"password"];
+    
+    
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    
+    
+    
+    NSString *sqlQuery = [NSString stringWithFormat:@"select 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 from offline_login where lower(username)='%@' and password='%@'",user.lowercaseString ,[AESCrypt encrypt:password password:@"usai"]];
+    
+    
+    
+    
+    DebugLog(@"offline_login sql:%@",sqlQuery);
+    sqlite3_stmt * statement;
+    
+    
+    [ret setValue:[NSNumber numberWithInt:AP_USER_NOT_AUTH ] forKey:@"result"];
+    
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            [ret setValue:[NSNumber numberWithInt:AP_USER_AUTH ] forKey:@"result"];
+            NSMutableDictionary* header = [[NSMutableDictionary alloc] init];
+            
+            
+            
+            int can_show_price = sqlite3_column_int(statement, 0);
+            int can_see_price = sqlite3_column_int(statement, 1);
+            
+            char *contact_id = (char*)sqlite3_column_text(statement, 2);
+            if(contact_id==nil)
+                contact_id="";
+            NSString *nscontact_id= [[NSString alloc]initWithUTF8String:contact_id];
+            
+            int user_type = sqlite3_column_int(statement, 3);
+            
+            int can_cancel_order = sqlite3_column_int(statement, 4);
+            int can_set_cart_price = sqlite3_column_int(statement, 5);
+            int can_create_portfolio = sqlite3_column_int(statement, 6);
+            int can_delete_order = sqlite3_column_int(statement, 7);
+            int can_submit_order = sqlite3_column_int(statement, 8);
+            int can_set_tearsheet_price = sqlite3_column_int(statement, 9);
+            int can_create_order = sqlite3_column_int(statement, 10);
+            
+            
+            char *mode = (char*)sqlite3_column_text(statement, 11);
+            if(mode==nil)
+                mode="";
+            NSString *nsmode= [[NSString alloc]initWithUTF8String:mode];
+            
+            
+            char *username = (char*)sqlite3_column_text(statement, 12);
+            if(username==nil)
+                username="";
+            NSString *nsusername= [[NSString alloc]initWithUTF8String:username];
+            
+            
+            [header setValue:[NSNumber numberWithBool:can_show_price]   forKey:@"can_show_price"];
+            [header setValue:[NSNumber numberWithBool:can_see_price]   forKey:@"can_see_price"];
+            [header setValue:nscontact_id   forKey:@"contact_id"];
+            [header setValue:[NSNumber numberWithBool:user_type]   forKey:@"user_type"];
+            [header setValue:[NSNumber numberWithBool:can_cancel_order]   forKey:@"can_cancel_order"];
+            [header setValue:[NSNumber numberWithBool:can_set_cart_price]   forKey:@"can_set_cart_price"];
+            [header setValue:[NSNumber numberWithBool:can_create_portfolio]   forKey:@"can_create_portfolio"];
+            [header setValue:[NSNumber numberWithBool:can_delete_order]   forKey:@"can_delete_order"];
+            [header setValue:[NSNumber numberWithBool:can_submit_order]   forKey:@"can_submit_order"];
+            [header setValue:[NSNumber numberWithBool:can_set_tearsheet_price]   forKey:@"can_set_tearsheet_price"];
+            [header setValue:[NSNumber numberWithBool:can_create_order]   forKey:@"can_create_order"];
+            
+            [header setValue:nsusername   forKey:@"username"];
+            
+            
+            [ret setObject:header forKey:@"header"];
+            [ret setValue:nsmode   forKey:@"mode"];
+            
+            
+        }
+        
+        
+        
+        sqlite3_finalize(statement);
+    }
+    
+    
+    
+    sqlite3_close(db);
+    
+    
+    
+    
+    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
++(NSDictionary*) offline_contactinfo :(NSMutableDictionary *) params
+{
+    NSString* contactId = [params valueForKey:@"contactId"];
+    
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    
+    
+    
+    NSString *sqlQuery = nil;
+    
+    
+    {
+        sqlQuery=[NSString stringWithFormat:@"select editable,company_name,country,addr,zipcode,state,city,contact_name,phone,contact_id,addr_1,addr_2,addr_3,addr_4,first_name,last_name,fax,email,img_0,img_1,img_2,price_type,notes,sales_rep from offline_contact where contact_id='%@'",contactId];
+        
+    }
+    
+    
+    DebugLog(@"offline_contactlist sql:%@",sqlQuery);
+    sqlite3_stmt * statement;
+    
+    
+    [ret setValue:@"2" forKey:@"result"];
+    
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        //int i = 0;
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            [ret setValue:[NSNumber numberWithInt:AP_USER_AUTH ] forKey:@"result"];
+            
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            
+            //            int editable  = sqlite3_column_int(statement, 0);
+            
+            
+            char *company_name = (char*)sqlite3_column_text(statement, 1);
+            NSString *nscompany_name =nil;
+            if(company_name==nil)
+                nscompany_name=@"";
+            else
+                nscompany_name=[[NSString alloc]initWithUTF8String:company_name] ;
+            
+            
+            char *country = (char*)sqlite3_column_text(statement, 2);
+            if(country==nil)
+                country="";
+            NSString *nscountry= [[NSString alloc]initWithUTF8String:country];
+            
+            
+            //            char *addr = (char*)sqlite3_column_text(statement, 3);
+            //            if(addr==nil)
+            //                addr="";
+            //            NSString *nsaddr= [[NSString alloc]initWithUTF8String:addr];
+            
+            
+            char *zipcode = (char*)sqlite3_column_text(statement, 4);
+            if(zipcode==nil)
+                zipcode="";
+            NSString *nszipcode= [[NSString alloc]initWithUTF8String:zipcode];
+            
+            
+            char *state = (char*)sqlite3_column_text(statement, 5);
+            if(state==nil)
+                state="";
+            NSString *nsstate= [[NSString alloc]initWithUTF8String:state];
+            
+            char *city = (char*)sqlite3_column_text(statement, 6);
+            if(city==nil)
+                city="";
+            NSString *nscity= [[NSString alloc]initWithUTF8String:city];
+            
+            //            char *contact_name = (char*)sqlite3_column_text(statement, 7);
+            //            NSString *nscontact_name = nil;
+            //            if(contact_name==nil)
+            //                nscontact_name=@"";
+            //            else
+            //                nscontact_name= [[NSString alloc]initWithUTF8String:contact_name];
+            
+            char *phone = (char*)sqlite3_column_text(statement, 8);
+            NSString *nsphone = nil;
+            if(phone==nil)
+                nsphone=@"";
+            else
+                nsphone= [[NSString alloc]initWithUTF8String:phone];
+            
+            
+            char *contact_id = (char*)sqlite3_column_text(statement, 9);
+            if(contact_id==nil)
+                contact_id="";
+            NSString *nscontact_id= [[NSString alloc]initWithUTF8String:contact_id];
+            
+            char *addr_1 = (char*)sqlite3_column_text(statement, 10);
+            if(addr_1==nil)
+                addr_1="";
+            NSString *nsaddr_1= [[NSString alloc]initWithUTF8String:addr_1];
+            
+            char *addr_2 = (char*)sqlite3_column_text(statement, 11);
+            if(addr_2==nil)
+                addr_2="";
+            NSString *nsaddr_2= [[NSString alloc]initWithUTF8String:addr_2];
+            
+            
+            char *addr_3 = (char*)sqlite3_column_text(statement, 12);
+            if(addr_3==nil)
+                addr_3="";
+            NSString *nsaddr_3= [[NSString alloc]initWithUTF8String:addr_3];
+            
+            
+            char *addr_4 = (char*)sqlite3_column_text(statement, 13);
+            if(addr_4==nil)
+                addr_4="";
+            NSString *nsaddr_4= [[NSString alloc]initWithUTF8String:addr_4];
+            
+            
+            char *first_name = (char*)sqlite3_column_text(statement, 14);
+            if(first_name==nil)
+                first_name="";
+            NSString *nsfirst_name= [[NSString alloc]initWithUTF8String:first_name];
+            
+            
+            char *last_name = (char*)sqlite3_column_text(statement, 15);
+            if(last_name==nil)
+                last_name="";
+            NSString *nslast_name= [[NSString alloc]initWithUTF8String:last_name];
+            
+            char *fax = (char*)sqlite3_column_text(statement, 16);
+            NSString *nsfax = nil;
+            if(fax==nil)
+                nsfax=@"";
+            else
+                nsfax= [[NSString alloc]initWithUTF8String:fax];
+            
+            char *email = (char*)sqlite3_column_text(statement, 17);
+            NSString *nsemail = nil;
+            if(email==nil)
+                nsemail=@"";
+            else
+                nsemail= [[NSString alloc]initWithUTF8String:email];
+            
+            char *img_0 = (char*)sqlite3_column_text(statement, 18);
+            NSString *nsimg_0 = nil;
+            if(img_0==nil)
+                nsimg_0=@"";
+            else
+                nsimg_0= [[NSString alloc]initWithUTF8String:img_0];
+            
+            char *img_1 = (char*)sqlite3_column_text(statement, 19);
+            NSString *nsimg_1 = nil;
+            if(img_1==nil)
+                nsimg_1=@"";
+            else
+                nsimg_1= [[NSString alloc]initWithUTF8String:img_1];
+            
+            char *img_2 = (char*)sqlite3_column_text(statement, 20);
+            NSString *nsimg_2 = nil;
+            if(img_2==nil)
+                nsimg_2=@"";
+            else
+                nsimg_2= [[NSString alloc]initWithUTF8String:img_2];
+            
+            char *price_type = (char*)sqlite3_column_text(statement, 21);
+            NSString *nsprice_type = nil;
+            if(price_type==nil)
+                nsprice_type=@"";
+            else
+                nsprice_type= [[NSString alloc]initWithUTF8String:price_type];
+            
+            
+            char *notes = (char*)sqlite3_column_text(statement, 22);
+            NSString *nsnotes = nil;
+            if(notes==nil)
+                nsnotes=@"";
+            else
+                nsnotes= [[NSString alloc]initWithUTF8String:notes];
+            
+            
+            char *salesrep = (char*)sqlite3_column_text(statement, 23);
+            NSString *nssalesrep = nil;
+            if(salesrep==nil)
+                nssalesrep=@"";
+            else
+                nssalesrep= [[NSString alloc]initWithUTF8String:salesrep];
+            
+            
+            {
+                // decrypt
+                
+                nscompany_name=[AESCrypt fastdecrypt:nscompany_name];
+                
+//                nscompany_name=[NSString stringWithFormat:@"<b>%@</b>",nscompany_name];
+                
+                nsphone=[AESCrypt fastdecrypt:nsphone];
+//                nsphone=[NSString stringWithFormat:@"TEL:%@",nsphone];
+                
+                nsaddr_1=[AESCrypt fastdecrypt:nsaddr_1];
+                //                nsaddr_1=[NSString stringWithFormat:@"TEL:%@",nsphone];
+                
+            }
+            
+            NSMutableArray* arr_name= [[NSMutableArray alloc] init];
+            
+            [arr_name addObject:nsfirst_name];
+            [arr_name addObject:nslast_name];
+            
+            NSString *nscontact_name=[RAUtils arr2string:arr_name separator:@" " trim:true];
+            
+            
+            NSMutableArray* arr_ext= [[NSMutableArray alloc] init];
+            
+            [arr_ext addObject:nsaddr_1];
+            [arr_ext addObject:nsaddr_2];
+            [arr_ext addObject:nsaddr_3];
+            [arr_ext addObject:nsaddr_4];
+            [arr_ext addObject:@"\r\n"];
+            
+            [arr_ext addObject:nscity];
+            [arr_ext addObject:nsstate];
+            [arr_ext addObject:nszipcode];
+            [arr_ext addObject:nscountry];
+            
+            NSString *nsext=[RAUtils arr2string:arr_ext separator:@", " trim:true];
+            
+            
+            nsext=[nsext stringByReplacingOccurrencesOfString:@", \r\n," withString:@"\r\n"];
+            
+            
+            [item setValue:nsimg_2   forKey:@"business_card_2"];
+            [item setValue:nsimg_0   forKey:@"business_card_0"];
+            [item setValue:nscountry   forKey:@"customer_country"];
+            [item setValue:nsphone   forKey:@"customer_phone"];
+            [item setValue:nsimg_1   forKey:@"business_card_1"];
+            [item setValue:nscompany_name   forKey:@"customer_name"];
+            [item setValue:nsprice_type   forKey:@"customer_price_type"];
+            [item setValue:nsfirst_name   forKey:@"customer_first_name"];
+            [item setValue:nsext   forKey:@"customer_contact_ext"];
+            [item setValue:nszipcode   forKey:@"customer_zipcode"];
+            [item setValue:nsaddr_1   forKey:@"customer_address1"];
+            [item setValue:nsaddr_2   forKey:@"customer_address2"];
+            [item setValue:nsaddr_3   forKey:@"customer_address3"];
+            [item setValue:nsaddr_4   forKey:@"customer_address4"];
+            [item setValue:nsnotes   forKey:@"customer_contact_notes"];
+            [item setValue:nslast_name   forKey:@"customer_last_name"];
+            [item setValue:nscity   forKey:@"customer_city"];
+            [item setValue:nsstate   forKey:@"customer_state"];
+            [item setValue:nssalesrep   forKey:@"customer_sales_rep"];
+            [item setValue:contactId   forKey:@"customer_cid"];
+            [item setValue:nscontact_name   forKey:@"customer_contact"];
+            [item setValue:nsfax   forKey:@"customer_fax"];
+            [item setValue:nsemail   forKey:@"customer_email"];
+            
+            
+            
+            [ret setObject:item forKey:@"customerInfo"];
+            // i++;
+            
+            
+            
+        }
+        UIApplication * app = [UIApplication sharedApplication];
+        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+        [ret setValue:appDelegate.mode   forKey:@"mode"];
+        [ret setValue:[NSNumber numberWithInt:1 ]    forKey:@"count"];
+        
+        
+        
+        sqlite3_finalize(statement);
+    }
+    
+    
+    
+    sqlite3_close(db);
+    
+    
+    
+    
+    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
++(NSDictionary*) offline_contactlist :(NSMutableDictionary *) params
+{
+    
+    
+    
+    
+    
+    NSString* contactType = [params valueForKey:@"contactType"];
+    
+    NSString* keyword = [params valueForKey:@"keyword"];
+    
+    
+    // advanced search
+    
+//    NSString* contact_name = [params valueForKey:@"contact_name"];
+//    NSString* customer_phone = [params valueForKey:@"customer_phone"];
+//    NSString* customer_fax = [params valueForKey:@"customer_fax"];
+//    NSString* customer_zipcode = [params valueForKey:@"customer_zipcode"];
+//    NSString* sales_rep = [params valueForKey:@"sales_rep"];
+//    NSString* customer_state = [params valueForKey:@"customer_state"];
+//    NSString* customer_name = [params valueForKey:@"customer_name"];
+//    NSString* customer_country = [params valueForKey:@"customer_country"];
+//    NSString* customer_cid = [params valueForKey:@"customer_cid"];
+//    NSString* customer_city = [params valueForKey:@"customer_city"];
+//    NSString* customer_address = [params valueForKey:@"customer_address"];
+//    NSString* customer_email = [params valueForKey:@"customer_email"];
+    
+    
+    int limit = [[params valueForKey:@"limit"] intValue];
+    int offset = [[params valueForKey:@"offset"] intValue];
+    
+    
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    
+    
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+       int result= [iSalesDB AddExFunction:db];
+    
+    int count =0;
+    
+    
+    
+    NSString *sqlQuery = nil;
+    
+    if(keyword.length==0)
+    {
+        sqlQuery=[NSString stringWithFormat:@"select editable,company_name,country,addr,zipcode,state,city,contact_name,phone,contact_id,addr_1,addr_2,addr_3,addr_4,first_name,last_name,fax,email from offline_contact where %@=1 order by create_time limit %d offset %d",contactType , limit, offset];
+        count=[iSalesDB get_recordcount:db table:@"offline_contact" where:[NSString stringWithFormat:@"%@='1",contactType]];
+    }
+    else
+    {
+       // NSString* encrypt_keyword= [AESCrypt fastencrypt:keyword];
+        
+        keyword = keyword.lowercaseString;
+        
+        
+        sqlQuery=[NSString stringWithFormat:@"select editable,company_name,country,addr,zipcode,state,city,contact_name,phone,contact_id,addr_1,addr_2,addr_3,addr_4,first_name,last_name,fax,email from offline_contact where %@=1 and (lower(contact_id ) like'%%%@%%' or lower(decrypt(company_name)) like '%%%@%%') order by create_time limit %d offset %d",contactType , keyword,keyword,limit, offset];
+        
+        count=[iSalesDB get_recordcount:db table:@"offline_contact" where:[NSString stringWithFormat:@"%@=1 and (lower(contact_id ) like'%@' or lower(company_name) like'%@')",contactType,keyword,keyword]];
+    }
+    
+    
+    DebugLog(@"offline_contactlist sql:%@",sqlQuery);
+    sqlite3_stmt * statement;
+    
+    
+    [ret setValue:@"2" forKey:@"result"];
+    [ret setValue:[NSNumber numberWithInt:count ]  forKey:@"total"];
+    
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i = 0;
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            
+            [ret setValue:[NSNumber numberWithInt:AP_USER_AUTH ] forKey:@"result"];
+            
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            
+            //            int editable  = sqlite3_column_int(statement, 0);
+            
+            
+            char *company_name = (char*)sqlite3_column_text(statement, 1);
+            NSString *nscompany_name =nil;
+            if(company_name==nil)
+                nscompany_name=@"";
+            else
+                nscompany_name= [[NSString alloc]initWithUTF8String:company_name] ;
+            
+            
+            char *country = (char*)sqlite3_column_text(statement, 2);
+            if(country==nil)
+                country="";
+            NSString *nscountry= [[NSString alloc]initWithUTF8String:country];
+            
+            
+            //            char *addr = (char*)sqlite3_column_text(statement, 3);
+            //            if(addr==nil)
+            //                addr="";
+            //            NSString *nsaddr= [[NSString alloc]initWithUTF8String:addr];
+            
+            
+            char *zipcode = (char*)sqlite3_column_text(statement, 4);
+            if(zipcode==nil)
+                zipcode="";
+            NSString *nszipcode= [[NSString alloc]initWithUTF8String:zipcode];
+            
+            
+            char *state = (char*)sqlite3_column_text(statement, 5);
+            if(state==nil)
+                state="";
+            NSString *nsstate= [[NSString alloc]initWithUTF8String:state];
+            
+            char *city = (char*)sqlite3_column_text(statement, 6);
+            if(city==nil)
+                city="";
+            NSString *nscity= [[NSString alloc]initWithUTF8String:city];
+            
+            //            char *contact_name = (char*)sqlite3_column_text(statement, 7);
+            //            NSString *nscontact_name = nil;
+            //            if(contact_name==nil)
+            //                nscontact_name=@"";
+            //            else
+            //                nscontact_name= [[NSString alloc]initWithUTF8String:contact_name];
+            
+            char *phone = (char*)sqlite3_column_text(statement, 8);
+            NSString *nsphone = nil;
+            if(phone==nil)
+                nsphone=@"";
+            else
+                nsphone= [[NSString alloc]initWithUTF8String:phone];
+            
+            
+            char *contact_id = (char*)sqlite3_column_text(statement, 9);
+            if(contact_id==nil)
+                contact_id="";
+            NSString *nscontact_id= [[NSString alloc]initWithUTF8String:contact_id];
+            
+            char *addr_1 = (char*)sqlite3_column_text(statement, 10);
+            if(addr_1==nil)
+                addr_1="";
+            NSString *nsaddr_1= [[NSString alloc]initWithUTF8String:addr_1];
+            
+            char *addr_2 = (char*)sqlite3_column_text(statement, 11);
+            if(addr_2==nil)
+                addr_2="";
+            NSString *nsaddr_2= [[NSString alloc]initWithUTF8String:addr_2];
+            
+            
+            char *addr_3 = (char*)sqlite3_column_text(statement, 12);
+            if(addr_3==nil)
+                addr_3="";
+            NSString *nsaddr_3= [[NSString alloc]initWithUTF8String:addr_3];
+            
+            
+            char *addr_4 = (char*)sqlite3_column_text(statement, 13);
+            if(addr_4==nil)
+                addr_4="";
+            NSString *nsaddr_4= [[NSString alloc]initWithUTF8String:addr_4];
+            
+            
+            char *first_name = (char*)sqlite3_column_text(statement, 14);
+            if(first_name==nil)
+                first_name="";
+            NSString *nsfirst_name= [[NSString alloc]initWithUTF8String:first_name];
+            
+            
+            char *last_name = (char*)sqlite3_column_text(statement, 15);
+            if(last_name==nil)
+                last_name="";
+            NSString *nslast_name= [[NSString alloc]initWithUTF8String:last_name];
+            
+            char *fax = (char*)sqlite3_column_text(statement, 16);
+            NSString *nsfax = nil;
+            if(fax==nil)
+                nsfax=@"";
+            else
+                nsfax= [NSString stringWithFormat:@"FAX:%@",[[NSString alloc]initWithUTF8String:fax]];
+            
+            char *email = (char*)sqlite3_column_text(statement, 17);
+            NSString *nsemail = nil;
+            if(email==nil)
+                nsemail=@"";
+            else
+                nsemail= [NSString stringWithFormat:@"EMAIL:%@",[[NSString alloc]initWithUTF8String:email]];
+            
+            
+            
+            NSMutableArray* arr_name= [[NSMutableArray alloc] init];
+            
+            [arr_name addObject:nsfirst_name];
+            [arr_name addObject:nslast_name];
+            
+            NSString *nscontact_name=[RAUtils arr2string:arr_name separator:@" " trim:true];
+            
+            NSMutableArray* arr_addr = [[NSMutableArray alloc] init];
+            
+            {
+                // decrypt
+                
+                nscompany_name=[AESCrypt fastdecrypt:nscompany_name];
+                
+                nscompany_name=[NSString stringWithFormat:@"<b>%@</b>",nscompany_name];
+                
+                nsphone=[AESCrypt fastdecrypt:nsphone];
+                nsphone=[NSString stringWithFormat:@"TEL:%@",nsphone];
+                
+                nsaddr_1=[AESCrypt fastdecrypt:nsaddr_1];
+//                nsaddr_1=[NSString stringWithFormat:@"TEL:%@",nsphone];
+                
+            }
+            
+            
+            [arr_addr addObject:nscompany_name];
+            [arr_addr addObject:nscontact_name];
+            [arr_addr addObject:@"<br>"];
+            
+            [arr_addr addObject:nsaddr_1];
+            [arr_addr addObject:nsaddr_2];
+            [arr_addr addObject:nsaddr_3];
+            [arr_addr addObject:nsaddr_4];
+            //[arr_addr addObject:nsaddr];
+            [arr_addr addObject:nszipcode];
+            [arr_addr addObject:nscity];
+            [arr_addr addObject:nsstate];
+            [arr_addr addObject:nscountry];
+            [arr_addr addObject:@"<br>"];
+            [arr_addr addObject:nsphone];
+            [arr_addr addObject:nsfax];
+            [arr_addr addObject:nsemail];
+            
+            NSString * name = [RAUtils arr2string:arr_addr separator:@", " trim:true];
+            
+            name=[name stringByReplacingOccurrencesOfString:@", <br>," withString:@"<br>"];
+            
+            
+            [item setValue:name   forKey:@"name"];
+            [item setValue:nscontact_id   forKey:@"contact_id"];
+            
+            [ret setObject:item forKey:[NSString stringWithFormat:@"item_%d",i]];
+            i++;
+            
+            
+            
+        }
+        UIApplication * app = [UIApplication sharedApplication];
+        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+        [ret setValue:appDelegate.mode   forKey:@"mode"];
+        [ret setValue:[NSNumber numberWithInt:i ]    forKey:@"count"];
+        
+        
+        
+        sqlite3_finalize(statement);
+    }
+    
+    
+    
+    sqlite3_close(db);
+    
+    
+    
+    
+    DebugLog(@"data string: %@",[RAUtils dict2string:ret] );
+    
+    return ret;
+}
++(NSDictionary*) model_NIYMAL:(NSString*) category
+{
+    // MODEL DETAIL NEW ITEM YOU MAY ALSO LIKE
+    
+    
+    category = [category substringToIndex:3];
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
+    
+    params[@"category"]= category;
+    
+    ret[@"params"]= params;
+    [ret setValue:@"detail" forKey:@"target"];
+    [ret setValue:@"popup" forKey:@"action"];
+    [ret setValue:@"content" forKey:@"type"];
+    [ret setValue:@"New Items You May Also Like" forKey:@"title"];
+    [ret setValue:@"model_NIYMAL" forKey:@"data_interface"];
+    [ret setValue:@"true" forKey:@"single_row"];
+    [ret setValue:@"true" forKey:@"partial_refresh"];
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    //  int count = [iSalesDB get_recordcount:db table:@"model" where:[NSString stringWithFormat:@"category like'#%%%@%%#'",category]];
+    
+    
+    NSString *sqlQuery = [NSString stringWithFormat:@"select m.name,m.product_id,i.url,random() as aa from model m LEFT join model_image i on m.product_id = i.product_id where m.category like'%%#%@#%%' and m.category like'%%#005#%%' and i.default_img = %d order by aa limit 10 ;",category,OFFLINE_IMG_TYPE_CATEGORY];
+    sqlite3_stmt * statement;
+    int count = 0;
+    [ret setValue:[NSString stringWithFormat:@"%d",count] forKey:@"count"];
+    
+    //    int count=0;
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i=0;
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            //            char *name = (char*)sqlite3_column_text(statement, 1);
+            //            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
+            
+            char *name = (char*)sqlite3_column_text(statement, 0);
+            NSString *nsname = [[NSString alloc]initWithUTF8String:name];
+            
+            
+            
+            
+            int product_id = sqlite3_column_int(statement, 1);
+            
+            
+            char *url = (char*)sqlite3_column_text(statement, 2);
+            if(url==nil)
+                url="";
+            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
+            
+            [item setValue:nsurl forKey:@"picture_path"];
+            [item setValue:nsname forKey:@"fash_name"];
+            [item setValue:[NSString stringWithFormat:@"%d",product_id] forKey:@"product_id"];
+            [item setValue:category forKey:@"category"];
+            [ret setObject:item forKey:[NSString stringWithFormat:@"item_%d",i]];
+            i++;
+            
+        }
+        [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"count"];
+        
+        
+        sqlite3_finalize(statement);
+    }
+    NSLog(@"count:%d",count);
+    
+    
+    sqlite3_close(db);
+    
+    
+    return ret;
+    
+    
+}
++(NSDictionary*) model_kvItem:(NSString*) key value:(NSString*)value
+{
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    [ret setValue:key forKey:@"key"];
+    [ret setValue:value forKey:@"val"];
+    return ret;
+}
++(NSDictionary*) model_property :(int)product_id field:(NSString*) field
+{
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    [ret setValue:@"0" forKey:@"img_count"];
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    
+    
+    NSString *sqlQuery = [NSString stringWithFormat:@"select %@,property_display from model where product_id=%d ;",field,product_id];
+    sqlite3_stmt * statement;
+    
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i=0;
+        if (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            //            char *name = (char*)sqlite3_column_text(statement, 1);
+            //            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
+            
+            char *value = (char*)sqlite3_column_text(statement, 0);
+            if(value==nil)
+                value="";
+            NSString *nsvalue = [[NSString alloc]initWithUTF8String:value];
+            
+            char *key = (char*)sqlite3_column_text(statement, 1);
+            if(key==nil)
+                key="";
+            NSString *nskey = [[NSString alloc]initWithUTF8String:key];
+            
+            [item setValue:nsvalue forKey:@"val"];
+            [item setValue:nskey forKey:@"key"];
+            
+            
+            [ret setObject:item forKey:[NSString stringWithFormat:@"item_%d",i]];
+            [ret setValue:@"1" forKey:@"count"];
+            i++;
+            
+        }
+        
+        
+        
+        sqlite3_finalize(statement);
+    }
+    
+    
+    
+    sqlite3_close(db);
+    
+    return ret;
+}
++(NSDictionary*) model_selector :(NSString*)product_group field:(NSString*) field
+{
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    [ret setValue:@"0" forKey:@"count"];
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    
+    
+    NSString *sqlQuery = [NSString stringWithFormat:@"select %@,selector_display,product_id,category from model where product_group='%@'  order by name;",field,product_group];
+    sqlite3_stmt * statement;
+    
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i=0;
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            //            char *name = (char*)sqlite3_column_text(statement, 1);
+            //            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
+            
+            char *value = (char*)sqlite3_column_text(statement, 0);
+            if(value==nil)
+                value="";
+            NSString *nsvalue = [[NSString alloc]initWithUTF8String:value];
+            
+            char *selector_display = (char*)sqlite3_column_text(statement, 1);
+            if(selector_display==nil)
+                selector_display="";
+            NSString *nsselector_display = [[NSString alloc]initWithUTF8String:selector_display];
+            
+            
+            int product_id = sqlite3_column_int(statement, 2);
+            
+            
+            
+            
+            char *category = (char*)sqlite3_column_text(statement, 3);
+            if(category==nil)
+                category="";
+            NSString *nscategory = [[NSString alloc]initWithUTF8String:category];
+            
+            NSString* url = [self model_category_img:[NSNumber numberWithInt:product_id].stringValue model_name:nil];//[self category_img:product_id];
+            
+            [item setValue:nsvalue forKey:@"title"];
+            [item setValue:url forKey:@"pic_url"];
+            
+            NSMutableDictionary* params=[[NSMutableDictionary alloc] init];
+            [params setValue:@"2" forKey:@"count"];
+            NSMutableDictionary* param0=[[NSMutableDictionary alloc] init];
+            [param0 setValue:[NSNumber numberWithInt:product_id ] forKey:@"val"];
+            [param0 setValue:@"product_id" forKey:@"name"];
+            
+            
+            NSMutableDictionary* param1=[[NSMutableDictionary alloc] init];
+            [param1 setValue:nscategory forKey:@"val"];
+            [param1 setValue:@"category" forKey:@"name"];
+            
+            [params setObject:param0 forKey:@"param_0"];
+            [params setObject:param1 forKey:@"param_1"];
+            
+            
+            [item setObject:params forKey:@"params"];
+            
+            
+            
+            [ret setValue:nsselector_display forKey:@"name"];
+            
+            [ret setObject:item forKey:[NSString stringWithFormat:@"item_%d",i]];
+            i++;
+            
+        }
+        [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"count"];
+        [ret setValue:@"switch" forKey:@"action"];
+        
+        sqlite3_finalize(statement);
+    }
+    
+    
+    
+    sqlite3_close(db);
+    
+    return ret;
+}
++(NSMutableDictionary*) category_img :(int)product_id
+{
+    // model 在 category search 显示的图片。
+    NSMutableDictionary* ret =[[NSMutableDictionary alloc]init];
+    
+    
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    NSString *sqlQuery = [NSString stringWithFormat:@"select url,type from model_image where product_id=%d and type<2 order by default_img desc , _id asc limit 2;",product_id];
+    sqlite3_stmt * statement;
+    
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            char *url = (char*)sqlite3_column_text(statement, 0);
+            if(url==nil)
+                url="";
+            int type = sqlite3_column_int(statement, 1);
+            if(type==0)
+                [ret setValue:[[NSString alloc]initWithUTF8String:url] forKey:@"img"];
+            else
+                [ret setValue:[[NSString alloc]initWithUTF8String:url] forKey:@"img_big"];
+            
+        }
+        
+        
+        
+        sqlite3_finalize(statement);
+    }
+    
+    
+    
+    sqlite3_close(db);
+    
+    return ret;
+}
++(NSDictionary*) model_img :(int)product_id
+{
+    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
+    
+    [ret setValue:@"0" forKey:@"img_count"];
+    
+    sqlite3 *db = [iSalesDB get_db];
+    
+    
+    
+    NSString *sqlQuery = [NSString stringWithFormat:@"select url from model_image where product_id=%d and type=1;",product_id];
+    sqlite3_stmt * statement;
+    
+    
+    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
+    {
+        
+        int i=0;
+        while (sqlite3_step(statement) == SQLITE_ROW)
+        {
+            NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+            
+            //            char *name = (char*)sqlite3_column_text(statement, 1);
+            //            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
+            
+            char *url = (char*)sqlite3_column_text(statement, 0);
+            if(url==nil)
+                url="";
+            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
+            
+            
+            
+            [item setValue:nsurl forKey:@"s"];
+            [item setValue:nsurl forKey:@"l"];
+            
+            
+            [ret setObject:item forKey:[NSString stringWithFormat:@"img_%d",i]];
+            i++;
+            
+        }
+        [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
+        
+        
+        sqlite3_finalize(statement);
+    }
+    
+    
+    
+    sqlite3_close(db);
+    
+    return ret;
+}
+
+@end

+ 26 - 0
RedAnt ERP Mobile/common/Functions/offline/OfflineSettingViewController.h

@@ -0,0 +1,26 @@
+//
+//  OfflineSettingViewController.h
+//  iSales-NPD
+//
+//  Created by Ray on 5/11/16.
+//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface OfflineSettingViewController : UIViewController
+
+@property (strong, nonatomic) IBOutlet UISwitch *switch_offline;
+@property (strong, nonatomic) IBOutlet UILabel *label_ver;
+@property (strong, nonatomic) IBOutlet UILabel *label_cachesize;
+@property (strong, nonatomic) IBOutlet UIButton *btn_checkupdate;
+@property (strong, nonatomic) IBOutlet UIButton *btn_submitlocal;
+@property (strong, nonatomic) IBOutlet UISwitch *switch_internal_address;
+@property (strong, nonatomic) IBOutlet UILabel *label_sync;
+
+
+@property (strong, nonatomic) IBOutlet UIButton *btn_clearcache;
+
+//-(void) onLogUpdate;
+//-(void) onProgressUpdate;
+@end

+ 535 - 0
RedAnt ERP Mobile/common/Functions/offline/OfflineSettingViewController.m

@@ -0,0 +1,535 @@
+//
+//  OfflineSettingViewController.m
+//  iSales-NPD
+//
+//  Created by Ray on 5/11/16.
+//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
+//
+
+#import "OfflineSettingViewController.h"
+#import "iSalesNetwork.h"
+#import "MainViewController.h"
+#import "LoginViewController.h"
+#import "OLDataProvider.h"
+#import "SyncControlPanelViewController.h"
+
+@interface OfflineSettingViewController ()
+
+@end
+
+@implementation OfflineSettingViewController
+
+- (void)viewDidLoad {
+    [super viewDidLoad];
+    // Do any additional setup after loading the view.
+    
+    
+    
+    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+    bool  offline = [defaults boolForKey:@"EnableOfflineMode"] ;
+    
+    NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
+    NSString*  lastsync = [defaults stringForKey:@"LastSync"] ;
+    if(lastsync!=nil)
+        self.label_sync.text = lastsync;
+    
+    if(ver==nil)
+        self.label_ver.text=@"No offline data";
+    else
+        self.label_ver.text=ver;
+    self.switch_offline.on = offline;
+    
+    
+    
+    self.edgesForExtendedLayout = UIRectEdgeNone ;
+    
+    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
+                                                                    style:UIBarButtonItemStylePlain
+                                                                   target:self
+                                                                   action:@selector( onCloseClick:)];
+    self.navigationItem.rightBarButtonItem = closeButton;
+    
+    
+    
+    
+}
+- (IBAction)OnCheckUpdate:(id)sender {
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    
+    if(appDelegate.bLogin==false)
+    {
+        
+        LoginViewController * loginvc =[ [UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginViewController"];
+        loginvc.returnValue = ^(bool blogin){
+            
+            
+            if(blogin)
+            {
+                if(appDelegate.user_type==USER_ROLE_EMPLOYEE)
+                {
+                    
+                    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+                    
+                    
+                    NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
+                    
+                    if(sender==nil)
+                    {
+                        [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn];
+                        SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
+                        syncVC.action_string=@"Download";
+                        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
+                        
+                        
+                        
+                        
+                        
+                        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
+                        
+                        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
+                        [self presentViewController:navi animated:YES completion:^{
+                            
+                            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
+                            
+                            NSLog(@"about present.........");
+                            
+                            //   self.btop = false;
+                            //  <#code#>
+                        }];
+                    }
+                    else
+                    {
+                        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Check offline update?" message:@"Please connect to WIFI network and plug charging cable, KEEP SCREEN ON AND KEEP APP RUNNING FOREGROUND, download data will take a while." preferredStyle:UIAlertControllerStyleAlert];
+                        //block代码块取代了delegate
+                        
+                        
+                        UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
+                            [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn];
+                            
+                            
+                            SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
+                            syncVC.action_string=@"Download";
+                            UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
+                            
+                            
+                            
+                            
+                            
+                            //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
+                            
+                            navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
+                            [self presentViewController:navi animated:YES completion:^{
+                                
+                                //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
+                                
+                                NSLog(@"about present.........");
+                                
+                                //   self.btop = false;
+                                //  <#code#>
+                            }];
+                            
+                            
+                            
+                            
+                        }];
+                        
+                        UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+                        }];
+                        
+                        [alertControl addAction:actionTwo];
+                        [alertControl addAction:alertthree];
+                        
+                        
+                        
+                        [self presentViewController:alertControl animated:YES completion:nil];
+                    }
+
+                    
+                    
+                }
+                else
+                {
+                    
+                }
+            }
+            else
+            {
+                [RAUtils alert_view:@"Must login" title:@"Data sync"];
+            }
+            
+            
+            
+        };
+        
+        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
+        
+        
+        
+        
+        
+        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
+        
+        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
+        [self presentViewController:navi animated:YES completion:^{
+            
+            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
+            
+            NSLog(@"LoginViewController present.........");
+            
+            //   self.btop = false;
+            //  <#code#>
+        }];
+    }
+    else
+    {
+        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+        
+        NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
+        
+        if(sender==nil)
+        {
+            [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn];
+            SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
+            syncVC.action_string=@"Download";
+            UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
+            
+            
+            
+            
+            
+            //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
+            
+            navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
+            [self presentViewController:navi animated:YES completion:^{
+                
+                //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
+                
+                NSLog(@"about present.........");
+                
+                //   self.btop = false;
+                //  <#code#>
+            }];
+        }
+        else
+        {
+            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Check offline update?" message:@"Please connect to WIFI network and plug charging cable, KEEP SCREEN ON AND KEEP APP RUNNING FOREGROUND, download data will take a while." preferredStyle:UIAlertControllerStyleAlert];
+            //block代码块取代了delegate
+            
+            
+            UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
+                [appDelegate check_offline:ver useInternalAddress:self.switch_internal_address.isOn];
+                
+                
+                SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
+                syncVC.action_string=@"Download";
+                UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
+                
+                
+                
+                
+                
+                //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
+                
+                navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
+                [self presentViewController:navi animated:YES completion:^{
+                    
+                    //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
+                    
+                    NSLog(@"about present.........");
+                    
+                    //   self.btop = false;
+                    //  <#code#>
+                }];
+                
+                
+            }];
+            
+            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+            }];
+            
+            [alertControl addAction:actionTwo];
+            [alertControl addAction:alertthree];
+            
+            
+            
+            [self presentViewController:alertControl animated:YES completion:nil];
+        }
+
+        
+        
+        
+    }
+    
+    
+    
+    
+    
+    
+    
+    
+    
+}
+
+- (void)onCloseClick:(UIButton *)sender {
+    
+    //    if(self.onDismissVC)
+    //        self.onDismissVC();
+    [self dismissViewControllerAnimated:true completion:nil];
+}
+
+- (void)didReceiveMemoryWarning {
+    [super didReceiveMemoryWarning];
+    // Dispose of any resources that can be recreated.
+}
+- (IBAction)onChangeOfflineSwitch:(id)sender {
+    
+    
+    
+
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+
+    
+    
+    
+    
+    
+    
+    if(self.switch_offline.isOn==false)
+    {
+        //disable offline
+        
+        
+        if(appDelegate.bLogin)
+        {
+            UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Sign out"];
+            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+                
+                NSDictionary* return_json = [iSalesNetwork logout];
+                
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
+                    
+                    
+                    if([[return_json valueForKey:@"result"] intValue]==2)
+                    {
+
+                        [appDelegate Logout];
+                        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+                        [defaults removeObjectForKey:@"EnableOfflineMode"];
+                        [defaults setBool:self.switch_offline.isOn forKey:@"EnableOfflineMode"];
+                        
+                        [defaults synchronize];
+                        appDelegate.offline_mode =self.switch_offline.isOn;
+                        
+                        [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadContact:true immediately:false];
+                        [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+                        
+                        
+                        [((MainViewController*)appDelegate.main_vc) switchToHome];
+                    }
+                    else
+                    {
+                       // [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Sign Out" controller:self] ;
+                    }
+                    
+                    
+                    
+                    
+                });
+            });
+        }
+        else
+        {
+            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+            [defaults removeObjectForKey:@"EnableOfflineMode"];
+            [defaults setBool:self.switch_offline.isOn forKey:@"EnableOfflineMode"];
+            
+            [defaults synchronize];
+            appDelegate.offline_mode =self.switch_offline.isOn;
+            
+            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadContact:true immediately:false];
+            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+            
+            
+            [((MainViewController*)appDelegate.main_vc) switchToHome];
+        }
+    }
+    else
+    {
+        bool haveofflineData=[OLDataProvider check_offlinedata];
+        if(haveofflineData)
+        {
+            // have offline data
+            if(appDelegate.bLogin)
+            {
+                UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Sign out"];
+                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+                    
+                    NSDictionary* return_json = [iSalesNetwork logout];
+                    
+                    dispatch_async(dispatch_get_main_queue(), ^{
+                        [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
+                        
+                        
+                        if([[return_json valueForKey:@"result"] intValue]==2)
+                        {
+                            
+                            [appDelegate Logout];
+                            
+                            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+                            [defaults removeObjectForKey:@"EnableOfflineMode"];
+                            [defaults setBool:self.switch_offline.isOn forKey:@"EnableOfflineMode"];
+                            
+                            [defaults synchronize];
+                            appDelegate.offline_mode =self.switch_offline.isOn;
+                            
+                            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadWish:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadOrder:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadContact:true immediately:false];
+                            [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
+                            
+                            
+                            [((MainViewController*)appDelegate.main_vc) switchToHome];
+                        }
+                        else
+                        {
+                            // [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Sign Out" controller:self] ;
+                        }
+                        
+                        
+                        
+                        
+                    });
+                });
+            }
+        }
+        else
+        {
+            //no offline data download form server first.
+            // restore switch state.
+            
+            [self.switch_offline setOn:!self.switch_offline.isOn];
+            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Offline data not found, download it from server?" message:@"Please connect to WIFI network and plug charging cable, KEEP SCREEN ON AND KEEP APP RUNNING FOREGROUND, download data will take a while." preferredStyle:UIAlertControllerStyleAlert];
+            //block代码块取代了delegate
+            
+            
+            UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
+                
+                [self OnCheckUpdate:nil];
+                
+                
+            }];
+            
+            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+                //                [self.switch_offline setOn:false];
+                //[RAUtils message_alert:@"No item in the cart" title:@"Offline" controller:self] ;
+            }];
+            
+            [alertControl addAction:actionTwo];
+            [alertControl addAction:alertthree];
+            
+            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
+            
+            
+            [self presentViewController:alertControl animated:YES completion:nil];
+        }
+        
+        //
+        //        UIApplication * app = [UIApplication sharedApplication];
+        //        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+        //
+        //        NSString*  ver = [defaults stringForKey:@"OfflineVer"] ;
+        //        //
+        //        //        [appDelegate check_offline:ver];
+        //        //        return;
+        //
+        //        //        if(ver.length==0)
+        //        {
+        //
+        //            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Check offline update?" message:nil preferredStyle:UIAlertControllerStyleAlert];
+        //            //block代码块取代了delegate
+        //
+        //
+        //            UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
+        //                //   UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Checking offline data"];
+        //                //init offline mode
+        //                //                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+        //                //
+        //                //
+        //                //                  //  [self check_offline];
+        //                //                });
+        //                [appDelegate check_offline:ver];
+        //
+        //
+        //
+        //            }];
+        //
+        //            UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+        //                //                [self.switch_offline setOn:false];
+        //                //[RAUtils message_alert:@"No item in the cart" title:@"Offline" controller:self] ;
+        //            }];
+        //
+        //            [alertControl addAction:actionTwo];
+        //            [alertControl addAction:alertthree];
+        //
+        //            //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
+        //
+        //
+        //            [self presentViewController:alertControl animated:YES completion:nil];
+        //
+        //
+        //
+        //
+        //
+        //
+        //
+        //
+        //        }
+        //        else
+        //        {
+        //
+        //        }
+    }
+}
+
+-(void) download_file:(NSString*)url type:(NSString*)type
+{
+    
+}
+
+
+/*
+ #pragma mark - Navigation
+ 
+ // In a storyboard-based application, you will often want to do a little preparation before navigation
+ - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
+ // Get the new view controller using [segue destinationViewController].
+ // Pass the selected object to the new view controller.
+ }
+ */
+
+@end

+ 22 - 0
RedAnt ERP Mobile/common/Functions/offline/SyncControlPanelViewController.h

@@ -0,0 +1,22 @@
+//
+//  SyncControlPanelViewController.h
+//  iSales-NPD
+//
+//  Created by Ray on 7/8/16.
+//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+#import <MessageUI/MessageUI.h>
+
+@interface SyncControlPanelViewController : UIViewController<MFMailComposeViewControllerDelegate>
+@property (strong, nonatomic) IBOutlet UIProgressView *progress_current;
+
+@property (strong, nonatomic) IBOutlet UIProgressView *progress_overall;
+@property (strong, nonatomic) IBOutlet UITextView *tv_log;
+@property (strong, nonatomic) NSString* action_string;
+@property (strong, nonatomic)    UIBarButtonItem *closeButton;
+-(void) onLogUpdate;
+-(void) onProgressUpdate;
+-(void) onSyncFinish;
+@end

+ 188 - 0
RedAnt ERP Mobile/common/Functions/offline/SyncControlPanelViewController.m

@@ -0,0 +1,188 @@
+//
+//  SyncControlPanelViewController.m
+//  iSales-NPD
+//
+//  Created by Ray on 7/8/16.
+//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
+//
+
+#import "SyncControlPanelViewController.h"
+#import "AppDelegate.h"
+#import "RAUtils.h"
+@interface SyncControlPanelViewController ()
+
+@end
+
+@implementation SyncControlPanelViewController
+
+- (void)viewDidLoad {
+    [super viewDidLoad];
+    self.edgesForExtendedLayout = UIRectEdgeNone ;
+    
+    self.closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
+                                                                    style:UIBarButtonItemStylePlain
+                                                                   target:self
+                                                                   action:@selector( onCloseClick:)];
+    
+    self.closeButton.enabled=false;
+    self.navigationItem.rightBarButtonItem = self.closeButton;
+    
+    
+    self.tv_log.layer.borderWidth=1 ; //边框粗细
+    self.tv_log.layer.borderColor=[UIColor darkGrayColor].CGColor; //边框颜色
+    
+    
+                    UIApplication * app = [UIApplication sharedApplication];
+                    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    appDelegate.settingUI=self;
+
+    // Do any additional setup after loading the view.
+}
+- (void)onCloseClick:(UIButton *)sender {
+    
+    //    if(self.onDismissVC)
+    //        self.onDismissVC();
+    [self dismissViewControllerAnimated:true completion:nil];
+}
+- (void)didReceiveMemoryWarning {
+    [super didReceiveMemoryWarning];
+    // Dispose of any resources that can be recreated.
+}
+-(void) onProgressUpdate
+{
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    self.progress_overall.progress= appDelegate.overall_progress;
+    self.progress_current.progress= appDelegate.file_progress;
+    
+    
+}
+- (IBAction)onSendlogClick:(id)sender {
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    
+    if(appDelegate.downloadlog.length==0)
+    {
+        [RAUtils message_alert:@"Log is empty sending canceled." title:@"Sending log" controller:self] ;
+        return;
+    }
+    
+    
+    
+    //  NSString *path = NSTemporaryDirectory();
+    
+    //    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
+    
+    // Get the string representation of CFUUID object.
+    
+    NSString* filename =[[NSUUID UUID] UUIDString];
+    //  NSString *filePath = [path stringByAppendingPathComponent:filename];
+    
+    
+    
+    
+    
+    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
+    
+    if(mc==nil)
+        return;
+    mc.mailComposeDelegate = self;
+    [mc setSubject:@"offline sync log"];
+    
+    
+    [mc setToRecipients:@[@"ray.zhang@united-cn.net",@"RedAntSupport@united-us.net"]];
+    
+    
+    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
+    // CFShow(infoDictionary);
+    // app名称
+    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleName"];
+    // app版本
+    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
+    // app build版本
+    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
+    
+    
+    NSString* appinfo =[NSString stringWithFormat:@"App info: %@   %@ build%@",app_Name,app_Version,app_build];
+    //    if(self.mail_content==nil)
+    //        self.mail_content=@"";
+    
+    NSString* htmlbody = [NSString stringWithFormat:@"<p>%@</p></br>%@",@"Process description:",appinfo];
+    
+    [mc setMessageBody:htmlbody
+                isHTML:YES];
+    
+    
+    
+    NSData *data = [appDelegate.log dataUsingEncoding:NSUTF8StringEncoding];//[NSData dataWithContentsOfFile:filePath];
+    
+    //    if(self.attachment_name.length>0)
+    //        filename = self.attachment_name;
+    [mc addAttachmentData:data mimeType:@"text/plain" fileName:filename];
+    [self presentModalViewController:mc animated:YES];
+    
+    return;
+    
+}
+
+-(void) onLogUpdate
+{
+    UIApplication * app = [UIApplication sharedApplication];
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    dispatch_async(dispatch_get_main_queue(), ^{
+        self.tv_log.text = appDelegate.downloadlog;
+        
+        [self.tv_log scrollRangeToVisible:NSMakeRange(appDelegate.downloadlog.length-1,0)];
+    });
+    
+    
+}
+
+-(void) onSyncFinish
+{
+    self.closeButton.enabled=true;
+//    UIApplication * app = [UIApplication sharedApplication];
+//    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+//    appDelegate.downloadlog=nil;
+//    appDelegate.downloading=false;
+////    self.downloadlog=nil;
+////    self.downloading=false;
+//    appDelegate.download_task=nil;
+//    appDelegate.vid=nil;
+}
+/*
+#pragma mark - Navigation
+
+// In a storyboard-based application, you will often want to do a little preparation before navigation
+- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
+    // Get the new view controller using [segue destinationViewController].
+    // Pass the selected object to the new view controller.
+}
+*/
+- (void)mailComposeController:(MFMailComposeViewController*)controller
+          didFinishWithResult:(MFMailComposeResult)result
+                        error:(NSError*)error {
+    switch (result)
+    {
+        case MFMailComposeResultCancelled:
+            NSLog(@"Mail send canceled...");
+            break;
+        case MFMailComposeResultSaved:
+            NSLog(@"Mail saved...");
+            break;
+        case MFMailComposeResultSent:
+            NSLog(@"Mail sent...");
+            break;
+        case MFMailComposeResultFailed:
+            NSLog(@"Mail send errored: %@...", [error localizedDescription]);
+            break;
+        default:
+            break;
+    }
+    [self dismissModalViewControllerAnimated:YES];
+}
+@end

+ 7 - 5
RedAnt ERP Mobile/common/Functions/order/OrderDetailViewController.m

@@ -1156,7 +1156,7 @@
                 
                 
                 NSString* file_name=[img_url lastPathComponent];
-                NSData* img_data=[iSalesDB load_cached_img:file_name];
+                NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
                 if(img_data!=nil)
                 {
                     
@@ -1176,7 +1176,8 @@
                             
                             if(downloadimg_data!=nil)
                             {
-                                [iSalesDB cache_img:downloadimg_data :file_name ];
+                                
+                                [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                                 
                                 UIImage * img =[UIImage imageWithData:downloadimg_data];
                                 cell.sign_img.image=img ;
@@ -1379,7 +1380,7 @@
             [cell.imgbtn setBackgroundImage:[UIImage imageNamed:@"loading_s"] forState:UIControlStateNormal];
             
             NSString* file_name=[img_url lastPathComponent];
-            NSData* img_data=[iSalesDB load_cached_img:file_name];
+            NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
             if(img_data!=nil)
             {
                 
@@ -1399,7 +1400,8 @@
                         
                         if(downloadimg_data!=nil)
                         {
-                            [iSalesDB cache_img:downloadimg_data :file_name ];
+                            
+                            [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                             
                             UIImage * img =[UIImage imageWithData:downloadimg_data];
                             [cell.imgbtn setBackgroundImage:img forState:UIControlStateNormal];
@@ -1515,7 +1517,7 @@
     //    [cell set_Count:count];
     //
     //    NSString* file_name=[img_url lastPathComponent];
-    //    NSData* img_data=[iSalesDB load_cached_img:file_name];
+    //    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
     //    if(img_data!=nil)
     //    {
     //

+ 1 - 1
RedAnt ERP Mobile/common/Functions/order/OrderListViewController.m

@@ -889,7 +889,7 @@ dispatch_async(self.loading_queue, ^{
 //    [cell set_Count:count];
     
 //    NSString* file_name=[img_url lastPathComponent];
-//    NSData* img_data=[iSalesDB load_cached_img:file_name];
+//    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
 //    if(img_data!=nil)
 //    {
 //        

+ 1 - 1
RedAnt ERP Mobile/common/Functions/portfolio/PDFListViewController.m

@@ -445,7 +445,7 @@
     //    [cell set_Count:count];
     
     //    NSString* file_name=[img_url lastPathComponent];
-    //    NSData* img_data=[iSalesDB load_cached_img:file_name];
+    //    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
     //    if(img_data!=nil)
     //    {
     //

+ 1 - 0
RedAnt ERP Mobile/common/Functions/portfolio/PortfolioEditQTYViewController.h

@@ -34,6 +34,7 @@
 @property (strong, nonatomic) IBOutlet UILabel *labelpriceafter;
 
 @property (strong, nonatomic) IBOutlet UILabel *labelNewPrice;
+@property (strong, nonatomic) IBOutlet UILabel *labelNote;
 
 @property int ids_count;
 @end

+ 2 - 1
RedAnt ERP Mobile/common/Functions/portfolio/PortfolioEditQTYViewController.m

@@ -245,10 +245,11 @@
 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
 {
     int lenth = 20;
-   return lenth>textView.text.length;
+   return (lenth>textView.text.length||[text isEqualToString:@""]);
    
 }
 
+
 #pragma mark textField delegate
 - (BOOL)textFieldShouldReturn:(UITextField *)textField {
     [textField resignFirstResponder];

+ 5 - 4
RedAnt ERP Mobile/common/Functions/portfolio/PortfolioViewController.m

@@ -641,7 +641,7 @@
                         }
                         else
                         {
-                            [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Edit QTY" controller:self] ;
+                            [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Edit Portfolio" controller:self] ;
                         }
                         
                         
@@ -1114,7 +1114,7 @@
     //    UIImageView* iv =cell.btnImage.imageView;
     [cell.btnImage setBackgroundImage:[UIImage imageNamed:@"loading_s"] forState:UIControlStateNormal];
     NSString* file_name=[img_url lastPathComponent];
-    NSData* img_data=[iSalesDB load_cached_img:file_name];
+    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
     if(img_data!=nil)
     {
         
@@ -1135,7 +1135,8 @@
                 
                 if(downloadimg_data!=nil)
                 {
-                    [iSalesDB cache_img:downloadimg_data :file_name ];
+                    
+                    [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                     
                     UIImage * img =[UIImage imageWithData:downloadimg_data];
                     [cell.btnImage setBackgroundImage:img forState:UIControlStateNormal];
@@ -1301,7 +1302,7 @@
                     }
                     else
                     {
-                        [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Edit QTY" controller:self] ;
+                        [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Edit Portfolio" controller:self] ;
                     }
                     
                     

+ 23 - 7
RedAnt ERP Mobile/common/Functions/search+itemsearch/ItemSearchViewController.m

@@ -296,6 +296,19 @@
 }
 - (IBAction)onFilterClicked:(id)sender {
     
+    
+    UIApplication * app = [UIApplication sharedApplication];
+    
+    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    
+    
+    if(appDelegate.offline_mode)
+    {
+        [RAUtils message_alert:@"offline mode does not support this function." title:@"Item Search Filter" controller:self] ;
+        
+        return;
+    }
+    
     ItemSearchFilterViewController * filterVC =[ self.storyboard instantiateViewControllerWithIdentifier:@"ItemSearchFilterViewController"];
     
     if(self.default_filter==nil)
@@ -1353,7 +1366,7 @@
         //    cell.Price.text = price;
         cell.cellImageView.image=[UIImage imageNamed:@"loading_s"];
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1373,7 +1386,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;
@@ -1402,7 +1416,7 @@
         static NSString * CellIdentifier = @"CategoryCellNPDLarge";
         CategoryCellNPD * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
         NSDictionary * item_json =[[self.category_data objectForKey:@"items" ] objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
-        NSString* img_url =[item_json valueForKey:@"mg_big"];
+        NSString* img_url =[item_json valueForKey:@"img_big"];
         NSString* description =[item_json valueForKey:@"description"];
         
         NSString* modelid =[item_json valueForKey:@"fash_name"];
@@ -1450,7 +1464,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1470,7 +1484,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;
@@ -1546,7 +1561,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1566,7 +1581,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;

+ 10 - 7
RedAnt ERP Mobile/common/Functions/search+itemsearch/SearchViewController.m

@@ -1369,7 +1369,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1389,7 +1389,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;
@@ -1417,7 +1418,7 @@
         static NSString * CellIdentifier = @"CategoryCellNPDLarge";
         CategoryCellNPD * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
         NSDictionary * item_json =[[self.category_data objectForKey:@"items" ] objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
-        NSString* img_url =[item_json valueForKey:@"mg_big"];
+        NSString* img_url =[item_json valueForKey:@"img_big"];
         NSString* description =[item_json valueForKey:@"description"];
         
         NSString* name =[item_json valueForKey:@"fash_name"];
@@ -1469,7 +1470,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1489,7 +1490,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;
@@ -1565,7 +1567,7 @@
         //    cell.Price.text = price;
         
         NSString* file_name=[img_url lastPathComponent];
-        NSData* img_data=[iSalesDB load_cached_img:file_name];
+        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
         if(img_data!=nil)
         {
             
@@ -1585,7 +1587,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         cell.cellImageView.image = img;

+ 4 - 4
RedAnt ERP Mobile/common/Functions/sidemenu/FunctionTestViewController.m

@@ -108,7 +108,7 @@ self.airPrinterController = [UIPrintInteractionController sharedPrintController]
         
         NSHTTPURLResponse* urlResponse = nil;
         
-        NSError *error = [[NSError alloc] init];
+        NSError *error = nil;
         
         NSData* content= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
         
@@ -180,7 +180,7 @@ self.airPrinterController = [UIPrintInteractionController sharedPrintController]
                 //                // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                 //                NSString *path = NSTemporaryDirectory();
                 //                NSString *filePath = [path stringByAppendingPathComponent:self.filename];
-                //                //    NSError *error = [[NSError alloc] init];
+                //                //    NSError *error = nil;
                 //                //    BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
                 //                //    NSAssert(bo,@"创建目录失败");
                 //                [self.content writeToFile:filePath atomically:YES];
@@ -239,7 +239,7 @@ self.airPrinterController = [UIPrintInteractionController sharedPrintController]
         
         NSHTTPURLResponse* urlResponse = nil;
         
-        NSError *error = [[NSError alloc] init];
+        NSError *error = nil;
         
         NSData* content= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
         
@@ -263,7 +263,7 @@ self.airPrinterController = [UIPrintInteractionController sharedPrintController]
 //                // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 //                NSString *path = NSTemporaryDirectory();
 //                NSString *filePath = [path stringByAppendingPathComponent:self.filename];
-//                //    NSError *error = [[NSError alloc] init];
+//                //    NSError *error = nil;
 //                //    BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
 //                //    NSAssert(bo,@"创建目录失败");
 //                [self.content writeToFile:filePath atomically:YES];

+ 1 - 0
RedAnt ERP Mobile/common/Functions/sidemenu/LoginViewController.h

@@ -21,6 +21,7 @@
 @interface LoginViewController : UIViewController
 @property (strong, nonatomic) IBOutlet UIButton *checkSavePassword;
 
+@property (strong, nonatomic) IBOutlet UIButton *checkOfflineMode;
 @property (nonatomic, weak) id<LoginViewControllerDelegate> delegate;
 @property (strong, nonatomic) IBOutlet UIButton *btnLogin;
 

+ 51 - 2
RedAnt ERP Mobile/common/Functions/sidemenu/LoginViewController.m

@@ -10,7 +10,7 @@
 
 #import "RetrievePassViewController.h"
 #import "UILabel+FontAppearance.h"
-
+#import "OLDataProvider.h"
 
 
 @interface LoginViewController ()
@@ -47,6 +47,10 @@
     
     
     
+    [self.checkOfflineMode setImage:[UIImage imageNamed:@"checkbox"] forState:UIControlStateNormal];
+    [self.checkOfflineMode setImage:[UIImage imageNamed:@"checkbox_check"] forState:UIControlStateSelected];
+    
+    
     NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
     NSString * user = [AESCrypt decrypt:[defaults stringForKey:@"user"] password:@"usai"];
     
@@ -60,10 +64,15 @@
         self.checkSavePassword.selected=true;
         
     }
+ //   NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+//    [defaults removeObjectForKey:@"EnableOfflineMode"];
+//    [defaults setBool:self.checkOfflineMode.selected forKey:@"EnableOfflineMode"];
+    self.checkOfflineMode.selected=[defaults boolForKey:@"EnableOfflineMode"];
     
+     [self.checkOfflineMode addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
     
     [self.checkSavePassword addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
-    
+    self.checkOfflineMode.tag=999;
     
     self.logindata = [iSalesDB get_saveduser];
     
@@ -93,6 +102,44 @@
 -(void)checkboxClick:(UIButton *)btn
 {
     btn.selected = !btn.selected;
+    
+    if(btn.tag==999)
+    {
+        
+        bool haveofflineData=[OLDataProvider check_offlinedata];
+        
+        if(btn.selected)
+        {
+            if(haveofflineData)
+            {
+                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+                [defaults removeObjectForKey:@"EnableOfflineMode"];
+                [defaults setBool:self.checkOfflineMode.selected forKey:@"EnableOfflineMode"];
+                
+                [defaults synchronize];
+                AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
+                appDelegate.offline_mode = self.checkOfflineMode.selected;
+            }
+            else
+            {
+                btn.selected = !btn.selected;
+                
+                [RAUtils alert_view:@"Offline data not found, you must login online and download offline data first." title:@"Offline data not found"];
+            }
+        }
+        else
+        {
+                        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+            [defaults removeObjectForKey:@"EnableOfflineMode"];
+            [defaults setBool:self.checkOfflineMode.selected forKey:@"EnableOfflineMode"];
+            
+            [defaults synchronize];
+            AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
+            appDelegate.offline_mode = self.checkOfflineMode.selected;
+        }
+
+
+    }
 }
 - (IBAction)CloseClick:(id)sender {
     
@@ -130,6 +177,8 @@
     DebugLog(@"Login...   user= %@ ; password= %@",user,password);
     
     
+
+    
     self.btnLogin.enabled = false;
     UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Sign in"];
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

+ 4 - 3
RedAnt ERP Mobile/common/Functions/watchlist/WatchListViewController.m

@@ -577,7 +577,7 @@
                 }
             else
             {
-                [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Loading Watchlist" controller:self] ;
+                [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Loading Wish list" controller:self] ;
             }
             
             self.isrefreshing=false;
@@ -748,7 +748,7 @@
     //    UIImageView* iv =cell.btnImage.imageView;
     [cell.btnImage setBackgroundImage:[UIImage imageNamed:@"loading_s"] forState:UIControlStateNormal];
     NSString* file_name=[img_url lastPathComponent];
-    NSData* img_data=[iSalesDB load_cached_img:file_name];
+    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
     if(img_data!=nil)
     {
         
@@ -769,7 +769,8 @@
                 
                 if(downloadimg_data!=nil)
                 {
-                    [iSalesDB cache_img:downloadimg_data :file_name ];
+                    
+                    [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                     
                     UIImage * img =[UIImage imageWithData:downloadimg_data];
                     [cell.btnImage setBackgroundImage:img forState:UIControlStateNormal];

+ 8 - 1
RedAnt ERP Mobile/common/RAUtils.h

@@ -31,12 +31,16 @@ typedef void (^add_to_cart_Handler)(void);
 +(NSDictionary*) string2dict:(NSString*) str;
 +(NSString*) dict2string:(NSDictionary*) dict;
 +(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim;
-
++(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim brackets:(NSString*)brackets;
 +(NSString*) base64en:(NSString*) string;
 +(NSString*) base64de:(NSString*) string;
 +(NSDictionary*) device_info;
 +(NSDictionary*) error_dict:(NSError*)error;
 
+
++(NSDictionary*) dictfromfile:(NSString*) path;
+
+
 + (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size;
 +(UIImage*)img_compress:(UIImage*)image kbsize:(float) size;
 +(NSString* )current_date;
@@ -48,4 +52,7 @@ typedef void (^add_to_cart_Handler)(void);
 
 +(NSArray*) string2arr:(NSString*) string separator:(NSString*)separator;
 +(void) add_to_cart:(UIViewController*) vc selectorholder:(id)holder selector:(SEL)addtocart;
+
+
++ (bool)mergeContentsOfPath:(NSString *)srcDir intoPath:(NSString *)dstDir error:(NSError**)err;
 @end

+ 253 - 157
RedAnt ERP Mobile/common/RAUtils.m

@@ -12,6 +12,68 @@
 #import <sys/param.h>
 #import <sys/mount.h>
 @implementation RAUtils
++(NSDictionary*) dictfromfile:(NSString*) path
+{
+    NSData *filedata = [NSData dataWithContentsOfFile:path];
+    
+    NSError *error = nil;
+    NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: filedata
+                                                               options: NSJSONReadingMutableContainers
+                                                                 error: &error];
+    // NSLog(@"%@",string2dic);
+    return string2dic;
+    
+}
++ (bool)mergeContentsOfPath:(NSString *)srcDir intoPath:(NSString *)dstDir error:(NSError**)err {
+    
+    NSLog(@"- mergeContentsOfPath: %@\n intoPath: %@", srcDir, dstDir);
+    
+    NSFileManager *fm = [NSFileManager defaultManager];
+    NSDirectoryEnumerator *srcDirEnum = [fm enumeratorAtPath:srcDir];
+    NSString *subPath;
+    while ((subPath = [srcDirEnum nextObject])) {
+        
+        NSLog(@" subPath: %@", subPath);
+        NSString *srcFullPath =  [srcDir stringByAppendingPathComponent:subPath];
+        NSString *potentialDstPath = [dstDir stringByAppendingPathComponent:subPath];
+        
+        // Need to also check if file exists because if it doesn't, value of `isDirectory` is undefined.
+        BOOL isDirectory = ([[NSFileManager defaultManager] fileExistsAtPath:srcFullPath isDirectory:&isDirectory] && isDirectory);
+        
+        // Create directory, or delete existing file and move file to destination
+        if (isDirectory) {
+            NSLog(@"   create directory");
+            [fm createDirectoryAtPath:potentialDstPath withIntermediateDirectories:YES attributes:nil error:err];
+            if (err && *err) {
+                NSLog(@"ERROR: %@", *err);
+                return false;
+            }
+        }
+        else {
+            if ([fm fileExistsAtPath:potentialDstPath]) {
+                NSLog(@"   removeItemAtPath");
+                [fm removeItemAtPath:potentialDstPath error:err];
+                if (err && *err) {
+                    NSLog(@"ERROR: %@", *err);
+                    return false;
+                }
+            }
+            
+            NSLog(@"   moveItemAtPath");
+            [fm moveItemAtPath:srcFullPath toPath:potentialDstPath error:err];
+            if (err && *err) {
+                NSLog(@"ERROR: %@", *err);
+                return false;
+            }
+        }
+    }
+    [fm removeItemAtPath:srcDir error:err];
+    if (err && *err) {
+        NSLog(@"ERROR: %@", *err);
+        return false;
+    }
+    return true;
+}
 
 + (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
     // 创建一个bitmap的context
@@ -25,13 +87,13 @@
     UIGraphicsEndImageContext();
     // 返回新的改变大小后的图片
     
- //   NSData  *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
+    //   NSData  *imageData=UIImageJPEGRepresentation(scaledImage, 1.f);
     return scaledImage;
 }
 
 +(UIImage*)img_compress:(UIImage*)image kbsize:(float) size
 {
-
+    
     
     
     //UIImage *image=[UIImage imageNamed:@"xxoo.jpeg"];
@@ -40,7 +102,7 @@
     if(size>imageData.length/1024)
         return image;
     
- //   CGFloat size=40.f;// kb
+    //   CGFloat size=40.f;// kb
     CGFloat scale=size/(imageData.length/1024);
     
     scale = sqrt (scale);
@@ -50,11 +112,11 @@
     newsize.width = newsize.width*scale;
     
     return [RAUtils scaleToSize:image size:newsize];
-//    NSData *newData=UIImageJPEGRepresentation(image, scale);
-
-//    UIImage* ret= [[UIImage alloc] initWithData:newData];
-//    
-//    return ret;
+    //    NSData *newData=UIImageJPEGRepresentation(image, scale);
+    
+    //    UIImage* ret= [[UIImage alloc] initWithData:newData];
+    //
+    //    return ret;
 }
 
 +(NSString*) FloatFormat:(float)value
@@ -120,7 +182,7 @@
         }
         else
         {
-           size+=[self fileSizeForDir:fullPath];
+            size+=[self fileSizeForDir:fullPath];
         }
     }
     return size;
@@ -133,7 +195,7 @@
     [ret setValue:[NSString stringWithFormat:@"%d",error.code] forKey:@"error_code"];
     [ret setValue:error.domain forKey:@"err_domain"];
     [ret setValue:[error localizedDescription] forKey:@"err_message"];
-   // [ret setObject:error.userInfo forKey:@"user_info"];
+    // [ret setObject:error.userInfo forKey:@"user_info"];
     return ret;
 }
 +(NSString*) current_date
@@ -166,40 +228,40 @@
     //
     //        }];
     
-//    UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
-//        
-//        UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Delete Order"];
-//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-//            
-//            NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
-//            
-//            dispatch_async(dispatch_get_main_queue(), ^{
-//                [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
-//                
-//                
-//                if([[return_json valueForKey:@"result"] intValue]==2)
-//                {
-//                    
-//                    [RAUtils error_alert:nil title:@"Order Delete"] ;
-//                }
-//                else
-//                {
-//                    [RAUtils error_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order Failed."] ;
-//                }
-//                
-//                
-//                
-//                
-//            });
-//        });
-//        
-//        
-//    }];
+    //    UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+    //
+    //        UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Delete Order"];
+    //        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+    //
+    //            NSDictionary* return_json = [iSalesNetwork delete_Order:orderid];
+    //
+    //            dispatch_async(dispatch_get_main_queue(), ^{
+    //                [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
+    //
+    //
+    //                if([[return_json valueForKey:@"result"] intValue]==2)
+    //                {
+    //
+    //                    [RAUtils error_alert:nil title:@"Order Delete"] ;
+    //                }
+    //                else
+    //                {
+    //                    [RAUtils error_alert:[return_json valueForKey:@"err_msg"] title:@"Delete Order Failed."] ;
+    //                }
+    //
+    //
+    //
+    //
+    //            });
+    //        });
+    //
+    //
+    //    }];
     
     UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
         //NSLog(@"Cancel");
     }];
-   // [alertControl addAction:actionOne];
+    // [alertControl addAction:actionOne];
     
     [alertControl addAction:alertthree];
     
@@ -213,14 +275,14 @@
     
     
     [vc presentViewController:alertControl animated:YES completion:nil];
-
+    
     
     
     return;
-
-
     
-
+    
+    
+    
 }
 
 +(void) neworder:(UIViewController*) vc selectorholder:(id)holder selector:(SEL)addtocart
@@ -285,16 +347,16 @@
     UIApplication * app = [UIApplication sharedApplication];
     AppDelegate *appDelegate = (AppDelegate *)[app delegate];
     MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
-
-   
+    
+    
     
     if(appDelegate.bLogin==false)
     {
         
         LoginViewController * loginvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
-
-        loginvc.returnValue = ^(bool blogin){
         
+        loginvc.returnValue = ^(bool blogin){
+            
             if(blogin)
             {
                 if(appDelegate.user_type==USER_ROLE_EMPLOYEE)
@@ -304,12 +366,12 @@
                     
                     
                     NSString* msg =@"";
-//                    if(appDelegate.contact_id.length>0)
-//                    {
-//                        msg = [msg stringByAppendingString:@"Customer:"];
-//                        msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
-//                        
-//                    }
+                    //                    if(appDelegate.contact_id.length>0)
+                    //                    {
+                    //                        msg = [msg stringByAppendingString:@"Customer:"];
+                    //                        msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
+                    //
+                    //                    }
                     
                     UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
                     //block代码块取代了delegate
@@ -419,7 +481,7 @@
                     
                     
                 }
-
+                
                 else
                 {
                     
@@ -430,7 +492,7 @@
                 }
             }
             
-
+            
         };
         
         UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
@@ -462,7 +524,7 @@
                 
                 
                 NSString* msg =@"";
-
+                
                 
                 UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Add to cart" message:msg preferredStyle:UIAlertControllerStyleAlert];
                 //block代码块取代了delegate
@@ -573,9 +635,9 @@
             }
             
             else
-            
+                
             {
-               
+                
                 UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Checking Pending Order"];
                 
                 
@@ -587,7 +649,7 @@
                     
                     dispatch_async(dispatch_get_main_queue(), ^{
                         
-                      [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
+                        [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                         
                         if([[return_json valueForKey:@"result"] intValue]==2)
                         {
@@ -760,7 +822,7 @@
                                         
                                     }];
                                     
-                                   
+                                    
                                     [alertControl addAction:actionOne];
                                     UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                                     }];
@@ -795,7 +857,7 @@
                                     
                                     
                                     
-                                   
+                                    
                                     
                                     UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Create new order" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                         
@@ -890,43 +952,43 @@
                 
                 
             }
-//            // [main_vc checklogin:false];
-//            
-//            if(appDelegate.can_create_order)
-//            {
-//                NSString* msg =@"";
-//                if(appDelegate.contact_id.length>0)
-//                {
-//                    msg = [msg stringByAppendingString:@"\n\nCustomer:"];
-//                    msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
-//                    
-//                }
-//                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil),NSLocalizedString(@"Create new order", nil), nil];
-//                
-//                // alert.
-//                [alert show];
-//            }
-//            else
-//            {
-//                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil), nil];
-//                
-//                // alert.
-//                [alert show];
-//            }
+            //            // [main_vc checklogin:false];
+            //
+            //            if(appDelegate.can_create_order)
+            //            {
+            //                NSString* msg =@"";
+            //                if(appDelegate.contact_id.length>0)
+            //                {
+            //                    msg = [msg stringByAppendingString:@"\n\nCustomer:"];
+            //                    msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
+            //
+            //                }
+            //                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil),NSLocalizedString(@"Create new order", nil), nil];
+            //
+            //                // alert.
+            //                [alert show];
+            //            }
+            //            else
+            //            {
+            //                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Check for saved order", nil), nil];
+            //
+            //                // alert.
+            //                [alert show];
+            //            }
         }
         else
         {
             
-//            if(appDelegate.order_code==nil)
-//                [ self neworder];
-//            else
-                [holder performSelector:addtocart];
+            //            if(appDelegate.order_code==nil)
+            //                [ self neworder];
+            //            else
+            [holder performSelector:addtocart];
             
             
             
         }
     }
-
+    
 }
 
 
@@ -953,13 +1015,13 @@
     
     
     appDelegate.recent_model = newdict;
-//    
-//    
-//    if(!bexist)
-//    {
-//        [appDelegate.recent_model setObject:item forKey:[NSString stringWithFormat:@"item_%d",count]];
-//        appDelegate.recent_model[@"count"]=[NSString stringWithFormat:@"%d",count+1];
-//    }
+    //
+    //
+    //    if(!bexist)
+    //    {
+    //        [appDelegate.recent_model setObject:item forKey:[NSString stringWithFormat:@"item_%d",count]];
+    //        appDelegate.recent_model[@"count"]=[NSString stringWithFormat:@"%d",count+1];
+    //    }
 }
 +(void) alert_view :(NSString*) msg title:(NSString*) title
 {
@@ -990,23 +1052,23 @@
     NSAssert(msg!=nil, @"error message from json is nil");
     UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
     [alert show];
-//    
-//    
-//    UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
-//    aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
-// //   check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
-////    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
-////        [alert setValue:aiView forKey:@"accessoryView"];
-////    }else{
-////        [alert addSubview:aiView];
-////    }
-//    
-//    aiView.hidden = false;
-//    aiView.hidesWhenStopped = false;
-//    [aiView startAnimating];
-//    
-//[alert addSubview:aiView];
-  
+    //
+    //
+    //    UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125.0, 80.0, 30.0, 30.0)];
+    //    aiView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
+    // //   check if os version is 7 or above. ios7.0及以上UIAlertView弃用了addSubview方法
+    ////    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
+    ////        [alert setValue:aiView forKey:@"accessoryView"];
+    ////    }else{
+    ////        [alert addSubview:aiView];
+    ////    }
+    //
+    //    aiView.hidden = false;
+    //    aiView.hidesWhenStopped = false;
+    //    [aiView startAnimating];
+    //
+    //[alert addSubview:aiView];
+    
     return alert;
     //return nil;
     // return alert;
@@ -1030,9 +1092,9 @@
     [info setValue:[[UIDevice currentDevice] localizedModel] forKey:@"localizedModel"];
     
     return info;
-//    [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
-//    [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
-//    [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
+    //    [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
+    //    [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
+    //    [info setValue:[[UIDevice currentDevice] name] forKey:@"name"];
     
 }
 
@@ -1046,17 +1108,51 @@
 {
     
     NSMutableArray * marr = [arr mutableCopy];
+    
+begin:
+    for (NSString* item in marr) {
+        if(item.length==0 )
+            if( btrim)
+            {
+                
+                [marr removeObject:item];
+                goto begin;
+            }
+        
+    }
+    NSString * ret = [marr componentsJoinedByString:separator];
+    return ret;
+}
++(NSString*) arr2string:(NSArray *) arr separator:(NSString*)separator trim:(bool) btrim brackets:(NSString*)brackets
+{
+    if(brackets!=nil)
+        separator = [NSString stringWithFormat:@"%@%@%@",brackets,separator,brackets];
+    NSMutableArray * marr = [arr mutableCopy];
+begin:
     for (NSString* item in marr) {
         if(item.length==0 )
             if( btrim)
-            [marr removeObject:item];
+            {
+                
+                [marr removeObject:item];
+                goto begin;
+            }
+        
+        
         
     }
     NSString * ret = [marr componentsJoinedByString:separator];
+    
+    if(brackets!=nil)
+        ret = [NSString stringWithFormat:@"%@%@%@",brackets,ret,brackets];
+    
     return ret;
 }
 +(NSDictionary*) string2dict:(NSString*) str
 {
+    
+    if(str==nil)
+        return nil;
     NSError *error = nil;
     NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding:NSUTF8StringEncoding]
                                                                options: NSJSONReadingMutableContainers
@@ -1073,7 +1169,7 @@
 }
 +(NSString*) dict2string:(NSDictionary*) dict
 {
-
+    
     if(dict==nil)
         return nil;
     
@@ -1111,18 +1207,18 @@
 +(void) deletefiles :(NSString*) path
 {
     
-//    NSString *extension = @"m4r";
+    //    NSString *extension = @"m4r";
     NSFileManager *fileManager = [NSFileManager defaultManager];
-//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
-//    NSString *documentsDirectory = [paths objectAtIndex:0];
+    //    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
+    //    NSString *documentsDirectory = [paths objectAtIndex:0];
     
     NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
     NSEnumerator *e = [contents objectEnumerator];
     NSString *filename;
     while ((filename = [e nextObject])) {
- 
-     bool result=  [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
-     
+        
+        bool result=  [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
+        
         if(!result)
             NSLog(@"delete file failed %@------%@",path,filename);
     }
@@ -1170,19 +1266,19 @@
                 break;
                 
             default:
-               // assert(@"UNDEFINE ERROR CODE!");
+                // assert(@"UNDEFINE ERROR CODE!");
                 break;
         }
     }
-//    if(code==RESULT_NET_NOTAVAILABLE)
-//        [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
-//    else
-        [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
+    //    if(code==RESULT_NET_NOTAVAILABLE)
+    //        [ret setValue:[NSString stringWithFormat:@"%d",RESULT_NET_ERROR] forKey:@"result"];
+    //    else
+    [ret setValue:[NSString stringWithFormat:@"%d",code] forKey:@"result"];
     [ret setValue:msg forKey:@"err_msg"];
     
-//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
-//                                                       options:0
-//                                                         error:nil];
+    //    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ret
+    //                                                       options:0
+    //                                                         error:nil];
     
     return ret;
 }
@@ -1193,30 +1289,30 @@
     return rect;
     
     
-//    BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
-//    
-//    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
-//    if (!iOS7) {
-//        screenHeight -= 20;
-//    }
-//    UIView *view = v;
-//    CGFloat x = .0;
-//    CGFloat y = .0;
-//    while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
-//        x += view.frame.origin.x;
-//        y += view.frame.origin.y;
-//        view = view.superview;
-//        if ([view isKindOfClass:[UIScrollView class]]) {
-//            x -= ((UIScrollView *) view).contentOffset.x;
-//            y -= ((UIScrollView *) view).contentOffset.y;
-//        }
-//    }
-//    return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
+    //    BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
+    //    
+    //    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
+    //    if (!iOS7) {
+    //        screenHeight -= 20;
+    //    }
+    //    UIView *view = v;
+    //    CGFloat x = .0;
+    //    CGFloat y = .0;
+    //    while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
+    //        x += view.frame.origin.x;
+    //        y += view.frame.origin.y;
+    //        view = view.superview;
+    //        if ([view isKindOfClass:[UIScrollView class]]) {
+    //            x -= ((UIScrollView *) view).contentOffset.x;
+    //            y -= ((UIScrollView *) view).contentOffset.y;
+    //        }
+    //    }
+    //    return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
 }
 
 
-    @end
-    
-    
-    
-    
+@end
+
+
+
+

+ 7 - 3
RedAnt ERP Mobile/common/const.h

@@ -34,6 +34,9 @@
 #define URL_LOCAL 0
 #define URL_NONE 2
 
+#define RETRY_DELAY 15 //offline getting data retry delay.
+#define DOWNLOAD_RETRY_TIMES 5 //retry times for single download.
+#define REQUEST_DOWNLOAD_RETRY_TIMES 240 //retry times for single download.40==60 min
 
 #define REFRESH_NONE 0
 #define REFRESH_VIEW 1
@@ -50,9 +53,10 @@
 #define AP_MESSAGE_NEW				 5
 #define AP_MESSAGE_NONE					 6
 
-#define OFFLINE_MODE false
-#define OFFLINE_IMG_TYPE_CATEGORY 0
-#define OFFLINE_IMG_TYPE_DETAIL 1
+//#define OFFLINE_MODE true
+#define OFFLINE_ARRAY_SEPARATOR @";"
+#define OFFLINE_IMG_TYPE_CATEGORY 1
+#define OFFLINE_IMG_TYPE_DETAIL 0
 
 #define RESULT_FALSE 0
 #define RESULT_TRUE		 2

+ 3 - 2
RedAnt ERP Mobile/common/customUI/ImageScrollerView.m

@@ -60,7 +60,7 @@
         {
             NSString* img_url = imgURL[i];
             NSString* file_name=[img_url lastPathComponent];
-            NSData* img_data=[iSalesDB load_cached_img:file_name];
+            NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
             if(img_data!=nil)
             {
                 dispatch_async(dispatch_get_main_queue(), ^{
@@ -85,7 +85,8 @@
                     
                     if(downloadimg_data!=nil)
                     {
-                        [iSalesDB cache_img:downloadimg_data :file_name ];
+                        
+                        [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                         
                         UIImage * img =[UIImage imageWithData:downloadimg_data];
                         [data addObject:img];

+ 3 - 2
RedAnt ERP Mobile/common/customUI/NIDropDown.m

@@ -190,7 +190,7 @@
     cell.textLabel.text=[NSString stringWithFormat:@"%@: %@",selectorname,[item valueForKey:@"title"]];
     NSString* img_url = [item valueForKey:@"pic_url"];
     NSString* file_name=[img_url lastPathComponent];
-    NSData* img_data=[iSalesDB load_cached_img:file_name];
+    NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
     if(img_data!=nil)
     {
         dispatch_async(dispatch_get_main_queue(), ^{
@@ -207,7 +207,8 @@
             
             if(downloadimg_data!=nil)
             {
-                [iSalesDB cache_img:downloadimg_data :file_name ];
+                
+                [iSalesDB cache_img:downloadimg_data filename:file_name saveTo:img_url];
                 
                 UIImage * img =[UIImage imageWithData:downloadimg_data];
                 cell.imageView.image=img;

+ 6 - 3
RedAnt ERP Mobile/common/data_provider/iSalesDB.h

@@ -12,7 +12,7 @@
 #import "config.h"
 @interface iSalesDB : NSObject
 +(void)testdata;
-+ (BOOL) initializeDb;
++ (int) initializeDb;
 +(void)execSql:(NSString *)sql db:(sqlite3 *)db;
 +(void)execSql:(NSString *)sql;
 + (sqlite3*) get_db;
@@ -27,10 +27,13 @@
 
 + (int) get_recordcount:(sqlite3*)db table:(NSString*) tablename where:(NSString*) whereclause;
 
-+ (NSData*) load_cached_img:(NSString*) filename;
-+ (void) cache_img: (NSData*) imgData :(NSString*) name;
++ (NSData*) load_cached_img:(NSString*) filename loadFrom:(NSString*) path;
++ (void) cache_img: (NSData*) imgData filename:(NSString*) name saveTo:(NSString*) path;
 
 
 + (NSDictionary*) search_pdf:(int) offset limit:(int)limit keywords:(NSString*) keywords;
 +(NSArray*) get_saveduser;
+
++ (sqlite3*) get_db_at:(NSString* )path;
++(int) AddExFunction:(sqlite3 *) db;
 @end

+ 198 - 61
RedAnt ERP Mobile/common/data_provider/iSalesDB.m

@@ -11,13 +11,90 @@
 #import "AppDelegate.h"
 @implementation iSalesDB
 
+void encryptfield (sqlite3_context *context, int argc, sqlite3_value **argv) {
+    assert(argc == 1);
+    switch (sqlite3_value_type(argv[0])){
+        case SQLITE_TEXT: {
+            unsigned const char *string = sqlite3_value_text (argv[0]);
+            
+            //Get the Objective C string (much easier to manage)
+            NSString *ocString = [[NSString alloc] initWithUTF8String:(char *) string] ;
+            NSString* encrypt=[AESCrypt fastencrypt:ocString];
+            //            //Split it on punctuation and spaces
+            //            NSMutableCharacterSet *cset = [NSCharacterSet punctuationCharacterSet];
+            //            [cset addCharactersInString:@" "];
+            //            NSArray *tokens = [ocString componentsSeparatedByCharactersInSet:cset];
+            //            //Sort it
+            //            NSArray *sortedArray = [tokens sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
+            //            ocString = [sortedArray componentsJoinedByString:@" "];
+            //            ocString = [ocString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
+            
+            const char *rString = [encrypt UTF8String];
+            
+            //NSLog (@"%@", [[[NSString alloc] initWithUTF8String:(char *) rString] autorelease]);
+            
+            sqlite3_result_text(context, rString, strlen(rString) * sizeof(char), NULL);
+            break;
+        }
+        default: {
+            sqlite3_result_null(context);
+            break;
+        }
+    }
+}
+
+void decryptfield (sqlite3_context *context, int argc, sqlite3_value **argv) {
+    assert(argc == 1);
+    switch (sqlite3_value_type(argv[0])){
+        case SQLITE_TEXT: {
+            unsigned const char *string = sqlite3_value_text (argv[0]);
+            
+            //Get the Objective C string (much easier to manage)
+            NSString *ocString = [[NSString alloc] initWithUTF8String:(char *) string] ;
+            NSString* decrypt=[AESCrypt fastdecrypt:ocString];
+//            //Split it on punctuation and spaces
+//            NSMutableCharacterSet *cset = [NSCharacterSet punctuationCharacterSet];
+//            [cset addCharactersInString:@" "];
+//            NSArray *tokens = [ocString componentsSeparatedByCharactersInSet:cset];
+//            //Sort it
+//            NSArray *sortedArray = [tokens sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
+//            ocString = [sortedArray componentsJoinedByString:@" "];
+//            ocString = [ocString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
+            
+            const char *rString = [decrypt UTF8String];
+            
+            //NSLog (@"%@", [[[NSString alloc] initWithUTF8String:(char *) rString] autorelease]);
+            
+            sqlite3_result_text(context, rString, strlen(rString) * sizeof(char), NULL);
+            break;
+        }
+        default: {
+            sqlite3_result_null(context);
+            break;
+        }
+    }
+}
+
+//+(void) icuRegexpFunc:(sqlite3_context *)p nArg:(int) nArg apArg: (sqlite3_value **)apArg
+//{
+//}
++(int) AddExFunction:(sqlite3 *) db
+{
+    
+    int nResult	= 0;
+    nResult=sqlite3_create_function(db, "decrypt", -1, SQLITE_ANY, 0, decryptfield, 0, 0);
+    nResult=sqlite3_create_function(db, "encrypt", -1, SQLITE_ANY, 0, encryptfield, 0, 0);
+//  sqlite3_create_function(database, "yourAwesome", 4, SQLITE_UTF8, NULL, &yourAwesomeFunc, NULL, NULL);
+//    nResult	= sqlite3_create_function(db, "containi", -1, SQLITE_ANY, 0, icuContainiFunc, 0, 0);
+    return nResult;
+}
 +(NSArray*) get_saveduser
 {
     {
         sqlite3* db = [self get_db ];
         NSMutableArray* ret = [[NSMutableArray alloc] init];
-//        ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
-//        NSString* user = appDelegate.user;
+        //        ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
+        //        NSString* user = appDelegate.user;
         NSString *sqlQuery = @"select name,pwd from login_info ";
         sqlite3_stmt * statement;
         
@@ -37,7 +114,7 @@
                 name = [AESCrypt decrypt:name password:@"usai"];
                 pwd = [AESCrypt decrypt:pwd password:@"usai"];
                 
-               
+                
                 NSMutableDictionary* up = [[NSMutableDictionary alloc]init];
                 up[@"name"]=name;
                 up[@"pwd"]=pwd;
@@ -97,7 +174,7 @@
     NSString* drop_login =@"DROP TABLE IF EXISTS offline_login;";
     NSString* drop_cart =@"DROP TABLE IF EXISTS offline_cart;";
     NSString* drop_wish =@"DROP TABLE IF EXISTS offline_wishlist;";
-     NSString* drop_contact =@"DROP TABLE IF EXISTS offline_contact;";
+    NSString* drop_contact =@"DROP TABLE IF EXISTS offline_contact;";
     NSString* drop_contact_image =@"DROP TABLE IF EXISTS contact_image;";
     
     
@@ -111,7 +188,7 @@
     [iSalesDB execSql:drop_contact db:db];
     [iSalesDB execSql:drop_contact_image db:db];
     
-    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), meterial 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);";
+    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);";
     
     
     
@@ -120,7 +197,7 @@
     NSString* create_model_price=@"CREATE TABLE IF NOT EXISTS model_price ( _id INTEGER PRIMARY KEY, product_id INTEGER,price float , type integer);";
     NSString* create_category=@"CREATE TABLE IF NOT EXISTS category ( _id INTEGER PRIMARY KEY, code VARCHAR(20),name VARCHAR(20));";
     
-    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));";
+    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));";
     
     
     
@@ -160,7 +237,7 @@
     [iSalesDB execSql:create_contact_image db:db];
     
     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==')";
-     [iSalesDB execSql:insert_user_queeniey db:db];
+    [iSalesDB execSql:insert_user_queeniey db:db];
     //   [self execSql:create_model_category db:db];
     
     //        if( ![self checkForField:@"search_history" field:@"level" db:db])
@@ -199,7 +276,7 @@
     {
         
         int category = arc4random() % 4;
-        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,meterial,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];
+        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];
         
         
         NSString* sql_1=[NSString stringWithFormat:@"insert into model_price (product_id,price,type) values(%d,12.%d,0);",i,i%100];
@@ -263,6 +340,24 @@
     }
     return db;
     
+}
+
++ (sqlite3*) get_db_at:(NSString* )path
+{
+    sqlite3* db = nil;
+    
+    //    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
+    //    NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
+    //    NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
+    
+    //    DebugLog(@"DB path:%@",database_path);
+    if (sqlite3_open([path UTF8String], &db) != SQLITE_OK) {
+        
+        DebugLog(@"sqlite3_open failed. msg:%s",sqlite3_errmsg(db));
+        sqlite3_close(db);
+    }
+    return db;
+    
 }
 + (NSString* )   sqliteEscape :(NSString*) keyWord
 {
@@ -298,7 +393,7 @@
     if(!  [fileManager fileExistsAtPath:pdf_cache isDirectory:&bdir])
     {
         
-        NSError *error = [[NSError alloc] init];
+        NSError *error = nil;
         bool bsuccess=[fileManager createDirectoryAtPath:pdf_cache withIntermediateDirectories:YES attributes:nil error:&error];
         
         if(!bsuccess)
@@ -314,7 +409,7 @@
     }
     NSString *save_path = [pdf_cache stringByAppendingPathComponent:filename];
     
-    NSError *error = [[NSError alloc] init];
+    NSError *error = nil;
     
     bool bsuccess=[fileManager copyItemAtPath:temp_path toPath:save_path error:&error];
     
@@ -326,9 +421,33 @@
         DebugLog(@"PDF SAVE FAILED,%@",filename);
     
 }
-+ (void) cache_img: (NSData*) imgData :(NSString*) name
++ (void) cache_img: (NSData*) imgData filename:(NSString*) name saveTo:(NSString*) path
 {
     
+    path=[path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
+    path=[path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
+    path=[path stringByReplacingOccurrencesOfString:name withString:@""];
+    
+//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
+//    NSString *cachefolder = [paths objectAtIndex:0];
+//    NSString *img_cache = [cachefolder stringByAppendingPathComponent:[NSString stringWithFormat:@"img_cache/%@",@"www.newpacificdirect.com/u/NPD/20160615/mytest/"]];
+//    if ([[NSFileManager defaultManager] fileExistsAtPath:img_cache]) {
+//        
+//        NSLog(@"目录已经存在了");
+//        
+//    }
+//    else
+//    {
+//        NSError *error = nil;
+//        bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:img_cache withIntermediateDirectories:YES attributes:nil error:&error];
+//        
+//        if(!bsuccess)
+//            DebugLog(@"Create temp folder failed");
+//    }
+    
+    
+    if(path.length==0)
+        path=@"";
     
     AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
     
@@ -338,13 +457,13 @@
         return;
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
     NSString *cachefolder = [paths objectAtIndex:0];
-    NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
+    NSString *img_cache = [cachefolder stringByAppendingPathComponent:[NSString stringWithFormat:@"img_cache/%@",path]];
     NSFileManager* fileManager = [NSFileManager defaultManager];
     BOOL bdir=YES;
     if(!  [fileManager fileExistsAtPath:img_cache isDirectory:&bdir])
     {
         
-        NSError *error = [[NSError alloc] init];
+        NSError *error = nil;
         bool bsuccess=[fileManager createDirectoryAtPath:img_cache withIntermediateDirectories:YES attributes:nil error:&error];
         
         if(!bsuccess)
@@ -367,10 +486,14 @@
         DebugLog(@"IMG CACHE FAILED,%@",name);
     
 }
-+ (NSData*) load_cached_img:(NSString*) filename
++ (NSData*) load_cached_img:(NSString*) filename loadFrom:(NSString*) path
 {
     
     
+    path=[path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
+    path=[path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
+//    path=[path stringByReplacingOccurrencesOfString:filename withString:@""];
+    
     AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
     
     if(appDelegate.bEnable_Cache==false)
@@ -383,7 +506,7 @@
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
     NSString *cachefolder = [paths objectAtIndex:0];
     NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
-    NSString *filePath = [img_cache stringByAppendingPathComponent:filename];
+    NSString *filePath = [img_cache stringByAppendingPathComponent:path];
     
     NSFileManager* fileManager = [NSFileManager defaultManager];
     if(  [fileManager fileExistsAtPath:filePath ])
@@ -413,25 +536,25 @@
     return data;
     
 }
-+ (BOOL) initializeDb {
++ (int) initializeDb {
     DebugLog (@"initializeDB");
     
-//    return false;
-//    
-//       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
-//    NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
-//    NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
-//    
+    //    return false;
+    //
+    //       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
+    //    NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
+    //    NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
+    //
     
     // move db file from document to cache ;
     //   NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
-//    NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] ;//[searchPaths objectAtIndex: 0];
-//    NSString* dbFilePath = [documentFolderPath stringByAppendingPathComponent:DBNAME];
-//    if ([[NSFileManager defaultManager] fileExistsAtPath: dbFilePath])
-//    {
-//        [[NSFileManager defaultManager] moveItemAtPath:dbFilePath toPath:database_path error:nil];
-//        
-//    }
+    //    NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] ;//[searchPaths objectAtIndex: 0];
+    //    NSString* dbFilePath = [documentFolderPath stringByAppendingPathComponent:DBNAME];
+    //    if ([[NSFileManager defaultManager] fileExistsAtPath: dbFilePath])
+    //    {
+    //        [[NSFileManager defaultManager] moveItemAtPath:dbFilePath toPath:database_path error:nil];
+    //
+    //    }
     // end move;
     
     
@@ -439,54 +562,70 @@
     
     
     
-    if (true)//! [[NSFileManager defaultManager] fileExistsAtPath: database_path])
-    {
+
         sqlite3 *db = [self get_db];
         
-        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 ,ETA DATE, demension VARCHAR(20), seat_height VARCHAR(20), meterial 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));";
+        NSString* create_model=@"CREATE TABLE IF NOT EXISTS model ( _id INTEGER, 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,bundle_item text,alert VARCHAR(20,0),PRIMARY KEY(_id));";
         
+        NSString* create_price=@"CREATE TABLE IF NOT EXISTS price ( _id INTEGER PRIMARY KEY, name text,  type integer,  order_by integer);";
         
         
-        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);";
+        NSString* create_wishlist=@"CREATE TABLE IF NOT EXISTS wishlist ( _id INTEGER PRIMARY KEY, user_id INTEGER,  product_id integer , create_time TIMESTAMP default (datetime('now', 'localtime')));";
         
-        NSString* create_model_price=@"CREATE TABLE IF NOT EXISTS model_price ( _id INTEGER PRIMARY KEY, product_id INTEGER,price float , type integer, price_name varchar(30));";
+        
+        NSString* create_image=@"CREATE TABLE IF NOT EXISTS model_image ( _id INTEGER PRIMARY KEY, name VARCHAR(20), url text, type integer, product_id INTEGER, default_img integer);";
+        
+        NSString* create_model_price=@"CREATE TABLE IF NOT EXISTS model_price ( _id INTEGER PRIMARY KEY, product_id INTEGER,price text , type integer, price_name text, expire_datetime datetime);";
         NSString* create_category=@"CREATE TABLE IF NOT EXISTS category ( _id INTEGER PRIMARY KEY, code VARCHAR(20),name VARCHAR(20));";
         NSString* create_offline_setting=@"CREATE TABLE IF NOT EXISTS offline_setting ( _id INTEGER PRIMARY KEY, name VARCHAR(20),value VARCHAR(40));";
         
         
-        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));";
-        
+        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), default_price text, price text, user_id integer);";
+    
+     NSString* create_offline_order=@"CREATE TABLE IF NOT EXISTS offline_order ( _id INTEGER PRIMARY KEY, order_id text not null,status integer, general_notes TEXT ,internal_notes text,signature  text,user_type integer,contact_id text,sales_code TEXT,user_id integer, create_time TIMESTAMP default (datetime('now', 'localtime')));";
+    
+
         
         
         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));";
         NSString* create_offline_wish=@"CREATE TABLE IF NOT EXISTS offline_wishlist ( _id INTEGER PRIMARY KEY, product_id INTEGER);";
         
         
-        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);";
+        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 VARCHAR(40,0), 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), PRIMARY KEY(_id) );";
         
-        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));";
+        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));";
         
         
-        NSString* create_login_info=@"CREATE TABLE IF NOT EXISTS login_info ( _id INTEGER PRIMARY KEY, name VARCHAR(256), pwd VARCHAR(256), lastlogin timestamp);";
-//    
-//        [self execSql:create_model db:db];
-//        
-//        [self execSql:create_image db:db];
-//        
-//        [self execSql:create_model_price db:db];
-//        [self execSql:create_category db:db];
-//        [self execSql:create_offline_setting db:db];
-//        
-//        [self execSql:create_offline_login db:db];
-//        
-//        [self execSql:create_offline_cart db:db];
-//        
-//        [self execSql:create_offline_wish db:db];
-//        
-//        [self execSql:create_offline_contact db:db];
-//        
-//        [self execSql:create_contact_image db:db];
-//        
+        NSString* create_login_info=@"CREATE TABLE IF NOT EXISTS login_info ( _id INTEGER PRIMARY KEY, name VARCHAR(256), pwd VARCHAR(256), lastlogin timestamp );";
+        //
+        
+        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
+        
+        //if(appDelegate.offline_mode)
+        {
+            [self execSql:create_model db:db];
+            [self execSql:create_wishlist db:db];
+            [self execSql:create_price db:db];
+            [self execSql:create_image db:db];
+            
+            [self execSql:create_model_price db:db];
+            [self execSql:create_category db:db];
+            [self execSql:create_offline_setting db:db];
+            
+            [self execSql:create_offline_login db:db];
+            
+            [self execSql:create_offline_cart db:db];
+            
+            [self execSql:create_offline_wish db:db];
+            
+            [self execSql:create_offline_contact db:db];
+            
+            [self execSql:create_contact_image db:db];
+            
+            [self execSql:create_offline_order db:db];
+            
+            
+        }
         
         [self execSql:create_login_info db:db];
         
@@ -507,11 +646,9 @@
         int ret=sqlite3_close(db);
         return ret;
         //        int aaa = 0;
-    }
-    return YES;
     
     
-    DebugLog (@"bottom of initializeDb");
+   // DebugLog (@"bottom of initializeDb");
 }
 +(void)execSql:(NSString *)sql db:(sqlite3 *)db
 {

+ 2 - 2
RedAnt ERP Mobile/common/data_provider/iSalesNetwork.h

@@ -51,7 +51,7 @@
 
 +(NSDictionary*) cart_setGeneralNote:(NSString*) order_code notes:(NSString*) notes;
 
-+(NSDictionary*) check_Offline:(NSString* )ver;
++(NSDictionary*) check_Offline:(NSString* )ver  useInternalAddress:(bool)buseinternaladdress vid:(NSString*) vid;
 +(NSDictionary*) download_Offline:(NSString* )vid;
 
 +(NSDictionary*) add_toCart:(NSString* ) item_id count:(int) count;
@@ -63,7 +63,7 @@
 //+(NSDictionary*) portfolio_setQTY:(NSString*) watchlist_id QTY:(int)qty;
 
 +(NSDictionary*) cart_remove:(NSString* ) item_ids;
-+(NSDictionary*) cart_check:(NSString* ) item_ids;
+//+(NSDictionary*) cart_check:(NSString* ) item_ids;
 +(NSDictionary*) watchlist_remove:(NSString* ) item_ids;
 
 +(NSDictionary*) move_wish2cart:(NSString* ) item_ids;

Fișier diff suprimat deoarece este prea mare
+ 313 - 120
RedAnt ERP Mobile/common/data_provider/iSalesNetwork.m


Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff