Browse Source

modularizado la funcionalidad de preferencias, acceso nativo a la camara y mejorado el mecanismo de autenticacion y preferencias

robert2206 8 years ago
parent
commit
ec7fa264ff

+ 13 - 1
src/app/app.module.ts

@@ -19,6 +19,12 @@ import { ToolsPage } from '../pages/tools/tools'
 import { SettingsPage } from '../pages/settings/settings';
 import { AboutPage } from '../pages/about/about'
 
+import { DataProvider } from '../providers/data-provider';
+import { OdooProvider } from '../providers/odoo-provider';
+import { SyncProvider } from '../providers/sync-provider';
+import { NetworkProvider } from '../providers/network-provider';
+import { PreferencesProvider } from '../providers/preferences-provider';
+
 @NgModule({
     declarations: [
         MyApp,
@@ -56,6 +62,12 @@ import { AboutPage } from '../pages/about/about'
         SettingsPage,
         AboutPage
     ],
-    providers: []
+    providers: [
+        DataProvider,
+        OdooProvider,
+        SyncProvider,
+        NetworkProvider,
+        PreferencesProvider
+    ]
 })
 export class AppModule {}

+ 11 - 2
src/pages/login/login.ts

@@ -17,6 +17,9 @@ export class LoginPage {
         public tokenService: TokenService
     ) {}
 
+    /**
+     *
+     */
     ionViewDidLoad() {
         this.menuCtrl.enable(false);
 
@@ -27,8 +30,14 @@ export class LoginPage {
 
     // Signin odoo
     signin(): void {
-        this.tokenService.getToken();
-        this.goToHome();
+        this.tokenService.getToken().then(r => {
+            console.log(r);
+            
+            this.goToHome();
+        }).catch(e => {
+            console.log(e);
+            
+        });
     }
 
     // Go to home

+ 8 - 14
src/pages/product-details/product-details.ts

@@ -1,12 +1,12 @@
 import { Component } from '@angular/core';
 import { NavController, NavParams, ActionSheetController } from 'ionic-angular';
-import { Camera } from 'ionic-native';
 import { Product } from '../../models/product'
 import { DataProvider } from '../../providers/data-provider'
+import { CameraProvider } from '../../providers/camera-provider';
 
 @Component({
     selector: 'page-product-details',
-    providers: [DataProvider],
+    providers: [CameraProvider],
     templateUrl: 'product-details.html'
 })
 export class ProductDetailsPage {
@@ -28,7 +28,8 @@ export class ProductDetailsPage {
         public navCtrl: NavController,
         public params: NavParams,
         public data: DataProvider,
-        public actionSheetCtrl: ActionSheetController
+        public actionSheetCtrl: ActionSheetController,
+        private cameraProvider: CameraProvider
     ) { 
         this.initialize();
     }
@@ -64,14 +65,14 @@ export class ProductDetailsPage {
                     text: "Desde la cámara",
                     icon: "camera",
                     handler: () => {
-                        this.takePicture(Camera.PictureSourceType.CAMERA);
+                        this.takePicture("camera");
                     }
                 },
                 {
                     text: "Desde la galería",
                     icon: "images",
                     handler: () => {
-                        this.takePicture(Camera.PictureSourceType.SAVEDPHOTOALBUM);
+                        this.takePicture("album");
                     }
                 },
                 {
@@ -85,15 +86,8 @@ export class ProductDetailsPage {
     /**
      *
      */
-    takePicture(sourceType: number) {
-        Camera.getPicture({
-            sourceType: sourceType,
-            destinationType: Camera.DestinationType.DATA_URL,
-            correctOrientation: true,
-            saveToPhotoAlbum: false,
-            targetHeight: 300,
-            targetWidth: 300
-        }).then(i => {
+    takePicture(source: string): void {
+        this.cameraProvider.getPicture(source).then(i => {
             this.product.image = i; 
         }).catch(e => {
             console.log(e);                    

+ 5 - 11
src/pages/product-list/product-list.ts

@@ -8,16 +8,15 @@ import { DataProvider } from '../../providers/data-provider'
 
 @Component({
     selector: 'page-product-list',
-    providers: [DataProvider],
     templateUrl: 'product-list.html'
 })
 export class ProductListPage extends DefaultListable<Product> implements INavigable {
 
     constructor(
         public navCtrl: NavController,
-        public data: DataProvider,
         public alertCtrl: AlertController,
-        public toastCtrl: ToastController
+        public toastCtrl: ToastController,
+        private dataProvider: DataProvider,
     ){
         super();
         this.initialize();
@@ -27,7 +26,7 @@ export class ProductListPage extends DefaultListable<Product> implements INaviga
      * Initialize data list
      */
     initialize(): void {
-        this.data.getAll("product").then(r => { 
+        this.dataProvider.getAll("product").then(r => { 
             this.elements = r.products;
         });
     }
@@ -66,17 +65,12 @@ export class ProductListPage extends DefaultListable<Product> implements INaviga
                         let item = this.elements[this.selectedIndex];
                         this.toggleDelete(-1);
 
-                        this.data.delete("product", item).then(result => {
+                        this.dataProvider.delete("product", item).then(result => {
                             this.elements.splice(this.selectedIndex, 1);
-
-                            this.toastCtrl.create({
-                                message: "Producto eliminado",
-                                duration: 500
-                            }).present();
                         }).catch(() => {
                             this.toastCtrl.create({
                                 message: "No se pudo eliminar el producto",
-                                duration: 500
+                                duration: 1000
                             }).present();
                         });
                     }

+ 6 - 7
src/pages/settings/settings.html

@@ -41,13 +41,12 @@
 
         <ion-item>
             <ion-label>Frecuencia de sincronización</ion-label>
-            <ion-select [ngModel]="syncFrecuency" (ngModelChange)="changeSyncFrecuency($event)">
-                <ion-option value="10">10 minutos</ion-option>
-                <ion-option value="30">30 minutos</ion-option>
-                <ion-option value="60">1 hora</ion-option>
-                <ion-option value="1440">1 día</ion-option>
-                <ion-option value="10080">1 semana</ion-option>
-                <ion-option value="302400">1 mes</ion-option>
+            <ion-select [disabled]="!sync" [ngModel]="syncFrecuency" (ngModelChange)="changeSyncFrecuency($event)">
+                <ion-option value="minute">1 minuto</ion-option>
+                <ion-option value="hour">1 hora</ion-option>
+                <ion-option value="day">1 día</ion-option>
+                <ion-option value="week">1 semana</ion-option>
+                <ion-option value="month">1 mes</ion-option>
             </ion-select>
         </ion-item>
     </ion-list>

+ 29 - 17
src/pages/settings/settings.ts

@@ -1,6 +1,7 @@
 import { Component } from '@angular/core';
 import { NavController } from 'ionic-angular';
-import { LocalNotifications } from 'ionic-native';
+import { BackgroundMode, LocalNotifications } from 'ionic-native';
+import { PreferencesProvider } from '../../providers/preferences-provider';
 
 @Component({
     selector: 'page-settings',
@@ -8,12 +9,13 @@ import { LocalNotifications } from 'ionic-native';
 })
 export class SettingsPage {
 
-    initialPage: number;
+    startPage: number;
     sync: boolean;
-    syncFrecuency;
+    syncFrecuency: string;
 
     constructor(
-        public navCtrl: NavController
+        public navCtrl: NavController,
+        public preferencesProvider: PreferencesProvider
     ) { 
         this.initialize();
     }
@@ -26,38 +28,48 @@ export class SettingsPage {
      *
      */
     initialize() {
-        this.initialPage = +localStorage.getItem("initial_page");
-        this.sync = (localStorage.getItem("sync") === "true");
-        this.syncFrecuency = +(localStorage.getItem("sync_frecuency") ? localStorage.getItem("sync_frecuency") : "10");
+        this.startPage = this.preferencesProvider.getStartPage();
+        this.sync = this.preferencesProvider.getSync();
+        this.syncFrecuency = this.preferencesProvider.getSyncFrecuency();
     }
 
     /**
      *
      */
     changeInitialPage(e: any) {
-        localStorage.setItem("initial_page", e);
+        this.preferencesProvider.setStartPage(e);
     }
 
     /**
      *
      */
     changeSync(e: any) {
-        localStorage.setItem("sync", e);
-
-        console.log(e);
+        this.sync = e;
+        this.preferencesProvider.setSync(e);
         
+        // if (e) {
+        //     BackgroundMode.enable();
+
+        //     LocalNotifications.schedule({
+        //         id: 1,
+        //         title: "Actualización de datos de Odoo Mobile",
+        //         every: "minute"
+        //     });
+
+        //     LocalNotifications.on("trigger", () => { 
+        //         console.log("Realizar actualización");
+        //     });
+        // } else {
+        //     BackgroundMode.disable();
 
-        LocalNotifications.schedule({
-            id: 1,
-            text: "Test notification",
-            every: "minute"
-        });
+        //     LocalNotifications.clearAll();
+        // }
     }
 
     /**
      *
      */
     changeSyncFrecuency(e: any) {
-        localStorage.setItem("sync_frecuency", e);
+        this.preferencesProvider.setSyncFrecuency(e);
     }
 }

+ 1 - 1
src/pages/tools/tools.html

@@ -12,7 +12,7 @@
 <ion-content padding>
 
     <ion-card>
-        <button ion-item (click)="syncAllData()">
+        <button ion-item (click)="askIfSyncData()">
             <ion-icon name="sync" color="primary" item-left></ion-icon>
             <h2>Sincronizar datos</h2>
             <p>Sincroniza sus datos con su cuenta de Odoo</p>

+ 32 - 7
src/pages/tools/tools.ts

@@ -1,11 +1,11 @@
 import { Component } from '@angular/core';
-import { NavController, AlertController } from 'ionic-angular';
-import { DataProvider } from '../../providers/data-provider';
+import { NavController, AlertController, LoadingController, ToastController } from 'ionic-angular';
 import { LoginPage } from '../login/login';
+import { DataProvider } from '../../providers/data-provider';
+import { SyncProvider } from '../../providers/sync-provider';
 
 @Component({
     selector: 'page-tools',
-    providers: [DataProvider],
     templateUrl: 'tools.html'
 })
 export class ToolsPage {
@@ -13,7 +13,10 @@ export class ToolsPage {
     constructor(
         public navCtrl: NavController,
         public alertCtrl: AlertController,
-        public dataProvider: DataProvider 
+        public loadingCtrl: LoadingController,
+        public toastCtrl: ToastController,
+        public dataProvider: DataProvider, 
+        public syncProvider: SyncProvider
     ) { }
 
     ionViewDidLoad() {
@@ -23,8 +26,8 @@ export class ToolsPage {
     /**
      *
      */
-    syncAllData() {
-         this.alertCtrl.create({
+    askIfSyncData(): void {
+        this.alertCtrl.create({
             title: "Confirmar",
             message: "Desea sincronizar sus datos ahora?",
             buttons: [
@@ -34,13 +37,35 @@ export class ToolsPage {
                 {
                     text: "Aceptar",
                     handler: () => {
-                        console.log("ok");
+                        this.syncData();
                     }
                 }
             ]
         }).present();
     }
 
+    /**
+     *
+     */
+    syncData() {
+        let loader = this.loadingCtrl.create({
+            content: "Actualizando datos, espere..."
+        });
+
+        loader.present();
+
+        this.syncProvider.doSync().then(r => {
+            loader.dismiss();
+        }).catch(e => {
+            loader.dismiss();
+
+            this.toastCtrl.create({
+                message: "No se pudo actualizar los datos",
+                duration: 1000
+            }).present();
+        });
+    }
+
     /**
      *
      */

+ 30 - 0
src/providers/camera-provider.ts

@@ -0,0 +1,30 @@
+import { Injectable } from '@angular/core';
+import { Camera } from 'ionic-native';
+
+@Injectable()
+export class CameraProvider {
+    
+    options: any;
+
+    constructor() { 
+        this.options = {
+            sourceType: Camera.PictureSourceType.CAMERA,
+            destinationType: Camera.DestinationType.DATA_URL,
+            correctOrientation: true,
+            saveToPhotoAlbum: false,
+            targetHeight: 300,
+            targetWidth: 300
+        }
+    }    
+    
+    /**
+     *
+     */
+    getPicture(source: string): Promise<any> {
+        if (source == "album") {
+            this.options.sourceType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
+        }
+        
+        return Camera.getPicture(this.options);
+    }
+}

+ 1 - 1
src/providers/data-provider.ts

@@ -96,7 +96,7 @@ export class DataProvider {
     /**
      *
      */
-    getAll(type: string): any {
+    getAll(type: string): Promise<any> {
         return new Promise((resolve, reject) => {
             resolve(this.data.rel.find(type));
         });

+ 15 - 0
src/providers/network-provider.ts

@@ -0,0 +1,15 @@
+import { Injectable } from '@angular/core';
+import { Diagnostic } from 'ionic-native';
+
+@Injectable()
+export class NetworkProvider {
+
+    constructor() { }
+    
+    /**
+     *
+    */
+    isAvailable(): Promise<any> {
+        return Diagnostic.isWifiAvailable();
+    }
+}

+ 29 - 0
src/providers/odoo-provider.ts

@@ -0,0 +1,29 @@
+import { Injectable } from '@angular/core';
+import { Http, Headers, Response, RequestOptions } from '@angular/http';
+
+@Injectable()
+export class OdooProvider {
+
+    constructor() { }
+    
+    /**
+     *
+     */
+    get(resource: string) {
+
+    }
+
+    /**
+     *
+     */
+    put(resource: string, data: Array<any>) {
+
+    }
+
+    /**
+     *
+     */
+    delete(resource: string, data: Array<any>) {
+
+    }
+}

+ 83 - 0
src/providers/preferences-provider.ts

@@ -0,0 +1,83 @@
+import { Injectable } from '@angular/core';
+
+@Injectable()
+export class PreferencesProvider {
+
+    tokenPrefix: string = "odix_token";
+    hostPrefix: string = "odix_host";
+    startPagePrefix: string = "odix_start_page";
+    syncPrefix: string = "odix_sync";
+    syncFrecuencyPrefix: string = "odix_sync_frecuency";
+
+    constructor() { }
+
+    /**
+     *
+     */
+    setToken(token: string): void {
+        localStorage.setItem(this.tokenPrefix, token);
+    }
+
+    /**
+     *
+     */
+    getToken(): string {
+        return localStorage.getItem(this.tokenPrefix);
+    }
+
+    /**
+     *
+     */
+    setHost(host: string): void {
+        localStorage.setItem(this.hostPrefix, host);
+    }
+
+    /**
+     *
+     */
+    getHost(): string {
+        return localStorage.getItem(this.hostPrefix);
+    }
+
+    /**
+     *
+     */
+    setStartPage(page: number): void {
+        localStorage.setItem(this.startPagePrefix, page.toString());
+    }
+
+    /**
+     *
+     */
+    getStartPage(): number {
+        return +localStorage.getItem(this.startPagePrefix);
+    }
+
+    /**
+     *
+     */
+    setSync(sync: boolean): void {
+        localStorage.setItem(this.syncPrefix, sync ? "true" : "false");
+    }
+
+    /**
+     *
+     */
+    getSync(): boolean {
+        return localStorage.getItem(this.syncPrefix) === "true";
+    }
+
+    /**
+     *
+     */
+    setSyncFrecuency(frecuency: string) {
+        localStorage.setItem(this.syncFrecuencyPrefix, frecuency);
+    }
+
+    /**
+     *
+     */
+    getSyncFrecuency(): string {
+        return localStorage.getItem(this.syncFrecuencyPrefix) ? "minute" : localStorage.getItem(this.syncFrecuencyPrefix);
+    }
+}

+ 43 - 0
src/providers/sync-provider.ts

@@ -0,0 +1,43 @@
+import { Injectable } from '@angular/core';
+import { DataProvider } from './data-provider';
+import { OdooProvider } from './odoo-provider';
+import { NetworkProvider } from './network-provider'
+
+@Injectable()    
+export class SyncProvider {
+
+    constructor(
+        private dataProvider: DataProvider,
+        private odooProvider: OdooProvider
+    ) { }
+
+    /**
+     *
+     */
+    doSync(): Promise<any> {
+        return new Promise((resolve, reject) => {
+            this.getProductsForUpdate().then(p => {
+                console.log(p);
+                resolve();
+            }).catch(e => {
+                console.log(e);
+                reject(e);
+            });
+        });
+    }
+
+    /**
+     *
+     */
+    private getProductsForUpdate(): Promise<any> {
+        return new Promise((resolve, reject) => {
+            this.dataProvider.getAll("product").then(r => {
+                resolve(r.products.filter(item => {
+                    return item;
+                }));
+            }).catch(e => {
+                reject(e);
+            });
+        });
+    }
+}

+ 0 - 0
src/providers/sync/product-sync-provider.ts


+ 16 - 26
src/providers/token-service.ts

@@ -2,6 +2,7 @@ import { Injectable } from '@angular/core';
 import { Http, Response, Headers, RequestOptions } from '@angular/http';
 import { Observable } from 'rxjs/Observable'
 import { Token } from '../components/token-component';
+import { PreferencesProvider } from '../providers/preferences-provider';
 
 import 'rxjs/add/operator/map';
 import 'rxjs/add/operator/catch';
@@ -12,23 +13,26 @@ export class TokenService {
 
     username: string = 'admin';
     password: string = 'admin';
-    url: string = '192.168.100.141:22000';
+    url: string = '127.0.0.1:8069';
 
-    constructor(public http: Http) {
+    constructor(
+        public http: Http,
+        public preferencesProvider: PreferencesProvider
+    ) {
     }
 
     /**
      * Pass token auth
      */
-    getToken(): void {
-        // let response = this.getTokenFromServer();
-        //
-        // response.subscribe(data => {
-        //         this.setLocalToken(data.value);
-        //     }, err => console.error(err),
-        //     () => console.log('Token received')
-        // );
-        this.checkTokenOnServer();
+    getToken(): Promise<any> {
+        return new Promise((resolve, reject) => {
+            this.getTokenFromServer().subscribe(data => {
+                this.preferencesProvider.setToken(data.value);
+                resolve(data.value);
+            }, err => {
+                reject(err);
+            });
+        });
     }
 
     /**
@@ -61,21 +65,7 @@ export class TokenService {
      * Get token from local storage
      */
     private getTokenFromLocal(): string {
-        return localStorage.getItem('odoo');
-    }
-
-    /**
-     * Store token locally
-     */
-    private setLocalToken(value): void {
-        localStorage.setItem('odoo', value);
-    }
-
-    /**
-     * Check if introduced url is valid
-     */
-    private checkUrl(): boolean {
-        return this.url.includes('.');
+        return this.preferencesProvider.getToken();
     }
 
     /**