├── LICENSE
├── README.md
├── app
├── app.html
├── app.ts
├── pages
│ ├── item-details
│ │ ├── item-details.html
│ │ ├── item-details.scss
│ │ └── item-details.ts
│ ├── list
│ │ ├── list.html
│ │ └── list.ts
│ └── login
│ │ ├── login.html
│ │ ├── login.scss
│ │ └── login.ts
├── providers
│ ├── auth-helper.ts
│ ├── drive-helper.ts
│ └── expense.ts
└── theme
│ ├── app.core.scss
│ ├── app.ios.scss
│ ├── app.md.scss
│ ├── app.variables.scss
│ └── app.wp.scss
├── config.xml
├── gulpfile.js
├── hooks
├── README.md
└── after_prepare
│ └── 010_add_platform_class.js
├── ionic.config.json
├── package.json
├── resources
├── android
│ ├── icon
│ │ ├── drawable-hdpi-icon.png
│ │ ├── drawable-ldpi-icon.png
│ │ ├── drawable-mdpi-icon.png
│ │ ├── drawable-xhdpi-icon.png
│ │ ├── drawable-xxhdpi-icon.png
│ │ └── drawable-xxxhdpi-icon.png
│ └── splash
│ │ ├── drawable-land-hdpi-screen.png
│ │ ├── drawable-land-ldpi-screen.png
│ │ ├── drawable-land-mdpi-screen.png
│ │ ├── drawable-land-xhdpi-screen.png
│ │ ├── drawable-land-xxhdpi-screen.png
│ │ ├── drawable-land-xxxhdpi-screen.png
│ │ ├── drawable-port-hdpi-screen.png
│ │ ├── drawable-port-ldpi-screen.png
│ │ ├── drawable-port-mdpi-screen.png
│ │ ├── drawable-port-xhdpi-screen.png
│ │ ├── drawable-port-xxhdpi-screen.png
│ │ └── drawable-port-xxxhdpi-screen.png
├── icon.png
├── ios
│ ├── icon
│ │ ├── icon-40.png
│ │ ├── icon-40@2x.png
│ │ ├── icon-50.png
│ │ ├── icon-50@2x.png
│ │ ├── icon-60.png
│ │ ├── icon-60@2x.png
│ │ ├── icon-60@3x.png
│ │ ├── icon-72.png
│ │ ├── icon-72@2x.png
│ │ ├── icon-76.png
│ │ ├── icon-76@2x.png
│ │ ├── icon-small.png
│ │ ├── icon-small@2x.png
│ │ ├── icon-small@3x.png
│ │ ├── icon.png
│ │ └── icon@2x.png
│ └── splash
│ │ ├── Default-568h@2x~iphone.png
│ │ ├── Default-667h.png
│ │ ├── Default-736h.png
│ │ ├── Default-Landscape-736h.png
│ │ ├── Default-Landscape@2x~ipad.png
│ │ ├── Default-Landscape~ipad.png
│ │ ├── Default-Portrait@2x~ipad.png
│ │ ├── Default-Portrait~ipad.png
│ │ ├── Default@2x~iphone.png
│ │ └── Default~iphone.png
└── splash.png
├── tsconfig.json
├── typings.json
├── typings
├── browser.d.ts
├── browser
│ └── ambient
│ │ └── es6-shim
│ │ └── index.d.ts
├── main.d.ts
├── main
│ └── ambient
│ │ └── es6-shim
│ │ └── index.d.ts
└── text-encoding
│ └── text-encoding.d.ts
└── www
├── Expenses.xlsx
├── img
└── appicon.png
└── index.html
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Richard diZerega
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ionic2-Angular2-ExcelAPI-Expense-App
2 | Simple mobile application written in Ionic2/Angular2 for capturing expenses. It uses Excel and OneDrive for Business for storage.
3 |
4 | You can find out more about the solution at https://blogs.msdn.microsoft.com/richard_dizeregas_blog/2016/06/07/using-onedrive-and-excel-apis-in-the-microsoft-graph-for-app-storage/
5 |
--------------------------------------------------------------------------------
/app/app.html:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/app.ts:
--------------------------------------------------------------------------------
1 | import {ViewChild} from '@angular/core';
2 | import {App, Platform, MenuController, Nav} from 'ionic-angular';
3 | import {StatusBar} from 'ionic-native';
4 | import {AuthHelper} from './providers/auth-helper';
5 | import {LoginPage} from './pages/login/login';
6 | import {ListPage} from './pages/list/list';
7 |
8 |
9 | @App({
10 | templateUrl: 'build/app.html',
11 | providers: [AuthHelper],
12 | config: {} // http://ionicframework.com/docs/v2/api/config/Config/
13 | })
14 | class MyApp {
15 | @ViewChild(Nav) nav: Nav;
16 |
17 | //initialize login as default page
18 | rootPage: any = LoginPage;
19 |
20 | constructor(
21 | private platform: Platform,
22 | private menu: MenuController,
23 | private authHelper: AuthHelper
24 | ) {
25 | this.initializeApp();
26 | }
27 |
28 | initializeApp() {
29 | this.platform.ready().then(() => {
30 | StatusBar.styleDefault();
31 |
32 | //check for signed in user
33 | let n = this.nav;
34 | this.authHelper.checkAuth().then(function(result) {
35 | if (result)
36 | n.setRoot(ListPage);
37 | else
38 | n.setRoot(LoginPage);
39 | });
40 | });
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/pages/item-details/item-details.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Edit Expense
4 | New Expense
5 |
6 |
7 |
11 |
12 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | Vendor
23 |
24 |
25 |
26 | Category
27 |
28 | Airfare
29 | Car Rental/Taxi
30 | Lodging
31 | Meals
32 | Other
33 | Phone/Wifi
34 |
35 |
36 |
37 | Amount
38 |
39 |
40 |
41 | Receipt
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/app/pages/item-details/item-details.scss:
--------------------------------------------------------------------------------
1 | div.selection {
2 | font-size: 22px;
3 | display: block;
4 | text-align: center;
5 | padding-top: 5%;
6 | }
7 |
8 | #img {
9 | display: block;
10 | margin-left: auto;
11 | margin-right: auto;
12 | }
13 |
14 | .landscape {
15 | width: 300px;
16 | }
17 |
18 | .portrait {
19 | width: 200px;
20 | }
--------------------------------------------------------------------------------
/app/pages/item-details/item-details.ts:
--------------------------------------------------------------------------------
1 | import {NgZone} from '@angular/core';
2 | import {Page, NavController, NavParams, ActionSheet, Loading, ViewController, Alert } from 'ionic-angular';
3 | import {Expense} from '../../providers/expense';
4 | import {DriveHelper} from '../../providers/drive-helper';
5 |
6 | @Page({
7 | templateUrl: 'build/pages/item-details/item-details.html',
8 | providers: [Expense, DriveHelper]
9 | })
10 | export class ItemDetailsPage {
11 | selectedItem: Expense;
12 | zone: NgZone;
13 | isPortrait: boolean;
14 | isNew: boolean = false;
15 | loading: Loading;
16 | helper: DriveHelper;
17 | viewCtrl: ViewController;
18 | index: number;
19 |
20 | constructor(private nav: NavController,
21 | viewCtrl: ViewController,
22 | navParams: NavParams,
23 | zone: NgZone,
24 | driveHelper: DriveHelper) {
25 |
26 | // If we navigated to this page, we will have an item available as a nav param
27 | this.selectedItem = navParams.get('item');
28 | this.index = navParams.get('index');
29 | this.zone = zone;
30 | this.isPortrait = true;
31 | this.helper = driveHelper;
32 | this.viewCtrl = viewCtrl;
33 |
34 | //determine if this is an create or update
35 | if (this.selectedItem == null) {
36 | this.isNew = true;
37 | this.selectedItem = new Expense();
38 | }
39 | else {
40 | this.selectedItem.receiptUpdated = false;
41 | if (!this.selectedItem.receiptData && this.selectedItem.receiptId) {
42 | let ctrl = this;
43 | ctrl.showWaiting('Loading...');
44 | ctrl.helper.loadPhoto(ctrl.selectedItem.receiptId).then(function(img:string) {
45 | //initialize the image into an Image object to determine ratio
46 | let i = new Image();
47 | i.onload = () => {
48 | ctrl.isPortrait = (i.width < i.height);
49 | ctrl.selectedItem.receiptData = img;
50 | ctrl.loading.dismiss();
51 | };
52 | i.src = 'data:image/jpg;base64, ' + img;
53 | }, function(err) {
54 | ctrl.loading.dismiss();
55 | ctrl.error(err);
56 | })
57 | }
58 | }
59 | }
60 |
61 | //captures receipt from camera or photo library
62 | captureReceipt() {
63 | let ctrl = this;
64 | let actionSheet = ActionSheet.create({
65 | title: 'Select Receipt Source',
66 | buttons: [
67 | {
68 | text: 'Camera',
69 | handler: () => {
70 | //use the camera to capture receipt
71 | ctrl.showWaiting('Loading...');
72 | navigator.camera.getPicture(function(imgData) {
73 | ctrl.imgLoaded(imgData, ctrl);
74 | }, function(err) {
75 | //ignore...could be from cancel
76 | ctrl.loading.dismiss();
77 | }, { quality: 50,
78 | destinationType: Camera.DestinationType.DATA_URL,
79 | sourceType: Camera.PictureSourceType.CAMERA});
80 | }
81 | },{
82 | text: 'Photo Library',
83 | handler: () => {
84 | //use the photo library to capture receipt
85 | ctrl.showWaiting('Loading...');
86 | navigator.camera.getPicture(function(imgData) {
87 | ctrl.imgLoaded(imgData, ctrl);
88 | }, function(err) {
89 | //ignore...could be from cancel
90 | ctrl.loading.dismiss();
91 | }, { quality: 50,
92 | destinationType: Camera.DestinationType.DATA_URL,
93 | sourceType: Camera.PictureSourceType.PHOTOLIBRARY
94 | });
95 | }
96 | }
97 | ]
98 | });
99 | this.nav.present(actionSheet);
100 | }
101 |
102 | //shows waiting indicator with message
103 | showWaiting(msg:string) {
104 | //initialize loading indicator
105 | this.loading = Loading.create({
106 | content: msg,
107 | dismissOnPageChange: false
108 | });
109 | this.nav.present(this.loading);
110 | }
111 |
112 | //callback when image is loaded
113 | imgLoaded(imgData: string, ctrl: ItemDetailsPage) {
114 | //determine img ratio
115 | let i = new Image();
116 | i.onload = () => {
117 | ctrl.isPortrait = (i.width < i.height);
118 | ctrl.selectedItem.receiptData = imgData;
119 | ctrl.selectedItem.receiptUpdated = true;
120 | ctrl.loading.dismiss();
121 | };
122 | i.src = 'data:image/jpg;base64, ' + imgData;
123 | }
124 |
125 | //dismisses the view
126 | dismiss() {
127 | //dismiss the modal
128 | this.viewCtrl.dismiss();
129 | }
130 |
131 | //saves the expense item
132 | save() {
133 | let ctrl = this;
134 | this.showWaiting('Saving...');
135 |
136 | //save the item
137 | if (ctrl.isNew) {
138 | this.selectedItem.create(this.helper).then(function(result) {
139 | //dismiss the waiting indicator and this pass the item back to parent
140 | ctrl.loading.dismiss();
141 | ctrl.viewCtrl.dismiss(ctrl.selectedItem);
142 | }, function(err) {
143 | ctrl.loading.dismiss();
144 | ctrl.error(err);
145 | });
146 | }
147 | else {
148 | this.selectedItem.update(this.index, this.helper).then(function(result) {
149 | //dismiss the waiting indicator and this pass the item back to parent
150 | ctrl.loading.dismiss();
151 | ctrl.viewCtrl.dismiss(ctrl.selectedItem);
152 | }, function(err) {
153 | ctrl.loading.dismiss();
154 | ctrl.error(err);
155 | });
156 | }
157 | }
158 |
159 | //displays error message
160 | error(msg) {
161 | let alert = Alert.create({
162 | title: 'Error Occurred',
163 | subTitle: msg,
164 | buttons: ['OK']
165 | });
166 | this.nav.present(alert);
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/app/pages/list/list.html:
--------------------------------------------------------------------------------
1 |
2 | My Expenses
3 |
4 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
{{item.vendor}}
24 |
25 | ${{item.amount}}
26 |
27 |
28 |
29 |
33 |
37 |
38 |
39 |
40 |
41 | You navigated here from {{selectedItem.title}}
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/pages/list/list.ts:
--------------------------------------------------------------------------------
1 | import {NgZone} from '@angular/core';
2 | import {Page, NavController, NavParams, Loading, Modal, Alert} from 'ionic-angular';
3 | import {CurrencyPipe} from '@angular/common';
4 | import {ItemDetailsPage} from '../item-details/item-details';
5 | import {DriveHelper} from '../../providers/drive-helper';
6 | import {Expense} from '../../providers/expense';
7 |
8 |
9 | @Page({
10 | templateUrl: 'build/pages/list/list.html',
11 | providers: [DriveHelper, Expense],
12 | pipes: [CurrencyPipe]
13 | })
14 | export class ListPage {
15 | selectedItem: any;
16 | icons: string[];
17 | items: Array;
18 | loading: Loading;
19 | helper: DriveHelper;
20 | zone: NgZone;
21 |
22 | constructor(
23 | private nav: NavController,
24 | navParams: NavParams,
25 | driveHelper: DriveHelper,
26 | zone: NgZone) {
27 | // If we navigated to this page, we will have an item available as a nav param
28 | this.selectedItem = navParams.get('item');
29 | this.items = [];
30 | this.helper = driveHelper;
31 | this.zone = zone;
32 |
33 | //show loading indicator
34 | this.showWaiting('Loading...');
35 |
36 | //ensure the configuration is in place before getting data
37 | let ctrl = this;
38 | ctrl.helper.ensureConfig().then(function(result: boolean) {
39 | //check for success
40 | if (result) {
41 | ctrl.listRefresh(null);
42 | }
43 | else
44 | ctrl.error('Failed to ensure configuration');
45 | }, function(err) {
46 | ctrl.error(err);
47 | });
48 | }
49 |
50 | //refreshes the list
51 | listRefresh(refresher) {
52 | let ctrl = this;
53 | Expense.getItems(this.helper).then(function(data: Array) {
54 | ctrl.items = data;
55 | if (ctrl.loading.isLoaded())
56 | ctrl.loading.dismiss();
57 | if (refresher)
58 | refresher.complete();
59 | }, function(err) {
60 | ctrl.error(err);
61 | });
62 | }
63 |
64 | //show the waiting indicator with message
65 | showWaiting(msg:string) {
66 | //initialize loading indicator
67 | this.loading = Loading.create({
68 | content: msg,
69 | dismissOnPageChange: false
70 | });
71 | this.nav.present(this.loading);
72 | }
73 |
74 | //launches the new dialog
75 | new() {
76 | let ctrl = this;
77 |
78 | ctrl.zone.run(() => {
79 | //launch the detail page in a modal window
80 | let modal = Modal.create(ItemDetailsPage, { item: null });
81 | modal.onDismiss(newItem => {
82 | //check if a new item was passed back
83 | if (newItem)
84 | ctrl.items.push(newItem);
85 | });
86 | this.nav.present(modal);
87 | });
88 | }
89 |
90 | //launches the edit dialog
91 | edit(evt, index:number, item:Expense, slidingItem) {
92 | let ctrl = this;
93 | slidingItem.close();
94 |
95 | ctrl.zone.run(() => {
96 | //launch the detail page in a modal window
97 | let modal = Modal.create(ItemDetailsPage, { item: item, index: index });
98 | modal.onDismiss(updateItem => {
99 | //check if a new item was passed back
100 | if (updateItem)
101 | item = updateItem;
102 | });
103 | this.nav.present(modal);
104 | });
105 | }
106 |
107 | //deletes the specified row
108 | delete(evt, index:number, item:Expense) {
109 | let ctrl = this;
110 | this.showWaiting('Deleting expense...');
111 |
112 | //delete the expense
113 | ctrl.zone.run(() => {
114 | item.delete(ctrl.helper, index).then(function() {
115 | //remove the item from the items array
116 | ctrl.items.splice(index, 1);
117 | ctrl.loading.dismiss();
118 | }, function(err) {
119 | ctrl.error(err);
120 | ctrl.loading.dismiss();
121 | });
122 | });
123 | }
124 |
125 | //displays error message
126 | error(msg) {
127 | let alert = Alert.create({
128 | title: 'Error Occurred',
129 | subTitle: msg,
130 | buttons: ['OK']
131 | });
132 | this.nav.present(alert);
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/app/pages/login/login.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Login
4 |
5 |
6 |
7 |
8 |
9 |
Welcome Expense Manager!
10 |
This application allow you to capture expenses when you are on the go and stores them in an Excel workbook in OneDrive for Business. You can even capture receipts!
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/app/pages/login/login.scss:
--------------------------------------------------------------------------------
1 | .getting-started {
2 |
3 | p {
4 | margin: 20px 0;
5 | line-height: 22px;
6 | font-size: 16px;
7 | }
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/app/pages/login/login.ts:
--------------------------------------------------------------------------------
1 | import {Page, NavController,Alert} from 'ionic-angular';
2 | import {AuthHelper} from '../../providers/auth-helper';
3 | import {ListPage} from '../list/list';
4 |
5 | @Page({
6 | templateUrl: 'build/pages/login/login.html'
7 | })
8 | export class LoginPage {
9 | constructor(private nav: NavController, private authHelper: AuthHelper) {}
10 |
11 | login() {
12 | let ctrl = this;
13 | this.authHelper.signin().then(function(token) {
14 | ctrl.nav.setRoot(ListPage);
15 | }, function(err) {
16 | ctrl.error(err);
17 | });
18 | }
19 |
20 | error(msg) {
21 | let alert = Alert.create({
22 | title: 'Error Occurred',
23 | subTitle: msg,
24 | buttons: ['OK']
25 | });
26 | this.nav.present(alert);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/providers/auth-helper.ts:
--------------------------------------------------------------------------------
1 | import {Injectable} from '@angular/core';
2 |
3 | @Injectable()
4 | export class AuthHelper {
5 | constructor() {
6 |
7 | }
8 |
9 | // Private resources
10 | _aadAuthContext = null;//Microsoft.ADAL.AuthenticationContext;
11 | _aadAuthority : string = "https://login.microsoftonline.com/common";
12 | _aadAppClientId : String = "a3aa36ec-7e2d-4239-885a-61e2be5b9f42";
13 | _aadAppRedirect : String = "http://localhost:8000";
14 | _graphResource : String = "https://graph.microsoft.com";
15 |
16 | // Private function to get authentication context using ADAL
17 | ensureContext() {
18 | return new Promise((resolve, reject) => {
19 | // Check if aadAuthContext is already initialized
20 | if (this._aadAuthContext == null) {
21 | // aadAuthContext is null...initialize it
22 | this._aadAuthContext = new Microsoft.ADAL.AuthenticationContext(this._aadAuthority, false);
23 | resolve(this._aadAuthContext);
24 | }
25 | else {
26 | // aadAuthContext is already initialized so resolve in promise
27 | resolve(this._aadAuthContext);
28 | }
29 | });
30 | }
31 |
32 | // Private function to get access token for a specific resource using ADAL
33 | getTokenForResource(resource) {
34 | var helper = this;
35 | return new Promise((resolve, reject) => {
36 | this.ensureContext().then(function (context) {
37 | // First try to get the token silently
38 | helper.getTokenForResourceSilent(context, resource).then(function (token) {
39 | // We were able to get the token silently...return it
40 | resolve(token);
41 | }, function (err) {
42 | // We failed to get the token silently...try getting it with user interaction
43 | helper._aadAuthContext.acquireTokenAsync(resource, helper._aadAppClientId, helper._aadAppRedirect).then(function (token) {
44 | // Resolve the promise with the token
45 | resolve(token);
46 | }, function (err) {
47 | // Reject the promise
48 | reject("Error getting token");
49 | });
50 | });
51 | });
52 | });
53 | }
54 |
55 | // Private function to get access token for a specific resource silent using ADAL
56 | getTokenForResourceSilent(context, resource) {
57 | var helper = this;
58 | return new Promise((resolve, reject) => {
59 | // read the tokenCache
60 | context.tokenCache.readItems().then(function (cacheItems) {
61 | // Try to get the roken silently
62 | var user_id;
63 | if (cacheItems.length > 1) {
64 | user_id = cacheItems[0].userInfo.userId;
65 | }
66 | context.acquireTokenSilentAsync(resource, helper._aadAppClientId, user_id).then(function (authResult) {
67 | // Resolve the authResult from the silent token call
68 | resolve(authResult);
69 | }, function (err) {
70 | // Error getting token silent...reject the promise
71 | reject("Error getting token silent");
72 | });
73 | }, function (err) {
74 | // Error getting cached data...reject the promise
75 | reject("Error reading token cache");
76 | });
77 | });
78 | }
79 |
80 | // check authenticated by getting token silently
81 | checkAuth() {
82 | var helper = this;
83 | return new Promise((resolve, reject) => {
84 | helper.ensureContext().then(function (context) {
85 | // First try to get the token silently
86 | helper.getTokenForResourceSilent(context, helper._graphResource).then(function (token) {
87 | // We were able to get the token silently...return it
88 | resolve(true);
89 | }, function (err) {
90 | // We failed to get the token silently...try getting it with user interaction
91 | resolve(false);
92 | });
93 | });
94 | });
95 | }
96 |
97 | // Try signin
98 | signin() {
99 | return new Promise((resolve, reject) => {
100 | this.getTokenForResource(this._graphResource).then(function(token) {
101 | resolve(token);
102 | }, function(err) {
103 | reject("Sign-in failed");
104 | });
105 | });
106 | }
107 | }
--------------------------------------------------------------------------------
/app/providers/drive-helper.ts:
--------------------------------------------------------------------------------
1 | import {Injectable} from '@angular/core';
2 | import {Http, Headers} from '@angular/http';
3 | import {AuthHelper} from '../providers/auth-helper';
4 |
5 | @Injectable()
6 | export class DriveHelper {
7 | constructor(
8 | private authHelper: AuthHelper,
9 | private http: Http) {
10 | this.workbookItemId = window.localStorage.getItem('CACHE_KEY_WORKBOOK');
11 | }
12 |
13 | workbookItemId: string;
14 |
15 | //gets all items from a OneDrive folder at the specified URI
16 | getItems(uri: string) {
17 | //ensure the app folder and Excel data source exists
18 | let helper = this;
19 | return new Promise((resolve, reject) => {
20 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
21 | helper.http.get(uri, {
22 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
23 | })
24 | .subscribe(res => {
25 | // Check the response status
26 | if (res.status === 200)
27 | resolve(res.json().value);
28 | else
29 | reject('Error calling MS Graph');
30 | });
31 | }, function(err) {
32 | reject(err); //error getting token for MS Graph
33 | });
34 | });
35 | }
36 |
37 | //ensures the "Expenses.xslx" file exists in the approot
38 | ensureConfig() {
39 | let helper = this;
40 | return new Promise((resolve, reject) => {
41 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
42 | helper.http.get('https://graph.microsoft.com/v1.0/me/drive/special/approot:/Expenses.xlsx', {
43 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
44 | })
45 | .subscribe(res => {
46 | // Check the response status
47 | if (res.status === 200) {
48 | helper.workbookItemId = res.json().id;
49 | window.localStorage.setItem('CACHE_KEY_WORKBOOK', helper.workbookItemId);
50 | resolve(true);
51 | }
52 | else {
53 | //create the files
54 | helper.createWorkbook().then(function(datasourceId: string) {
55 | helper.workbookItemId = datasourceId;
56 | window.localStorage.setItem('CACHE_KEY_WORKBOOK', helper.workbookItemId);
57 | resolve(true);
58 | }, function(err) {
59 | reject(err);
60 | });
61 | }
62 | });
63 | }, function(err) {
64 | reject(err); //error getting token for MS Graph
65 | });
66 | });
67 | }
68 |
69 | //uploads a file to the MyExpenses folder
70 | uploadFile(base64: string, name: string) {
71 | let helper = this;
72 | return new Promise((resolve, reject) => {
73 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
74 | //convert base64 string to binary
75 | let binary = helper.getBinaryFileContents(base64);
76 |
77 | //prepare the request
78 | let req = new XMLHttpRequest();
79 | req.open('PUT', 'https://graph.microsoft.com/v1.0/me/drive/special/approot:/' + name + '/content', false);
80 | req.setRequestHeader('Content-type', 'application/octet-stream');
81 | req.setRequestHeader('Content-length', binary.length.toString());
82 | req.setRequestHeader('Authorization', 'Bearer ' + token.accessToken);
83 | req.setRequestHeader('Accept', 'application/json;odata.metadata=full');
84 | req.send(binary);
85 |
86 | //check response
87 | if (req.status === 201)
88 | resolve(JSON.parse(req.responseText).id); //resolve id of new file
89 | else
90 | reject('Failed to upload file');
91 | }, function(err) {
92 | reject(err); //error getting token for MS Graph
93 | });
94 | });
95 | }
96 |
97 | //creates the "Expenses.xslx" workbook in the approot folder specified
98 | createWorkbook() {
99 | //adds a the workbook to OneDrive
100 | let helper = this;
101 | return new Promise((resolve, reject) => {
102 | //get token for resource
103 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
104 | //reference the Excel document template at the root application www directory
105 | window.resolveLocalFileSystemURL(cordova.file.applicationDirectory + 'www/Expenses.xlsx', function (fileEntry) {
106 | fileEntry.file(function (file) {
107 | //open the file with a FileReader
108 | var reader = new FileReader();
109 | reader.onloadend = function(evt: ProgressEvent) {
110 | //read base64 file and convert to binary
111 | let base64 = evt.target.result;
112 | base64 = base64.substring(base64.indexOf(',') + 1);
113 |
114 | //perform the PUT
115 | helper.uploadFile(base64, 'Expenses.xlsx').then(function(id: string) {
116 | resolve(id);
117 | }, function(err) {
118 | reject(err);
119 | });
120 | };
121 |
122 | //catch read errors
123 | reader.onerror = function(err) {
124 | reject('Error loading file');
125 | };
126 |
127 | //read the file as an ArrayBuffer
128 | reader.readAsDataURL(file);
129 | },
130 | function(err) {
131 | reject('Error opening file');
132 | });
133 | }, function(err) {
134 | reject('Error resolving file on file system');
135 | });
136 | }, function(err) {
137 | reject(err); //error getting token for MS Graph
138 | });
139 | });
140 | }
141 |
142 | //converts a base64 string to binary array of type Uint8Array for uploading
143 | getBinaryFileContents(base64FileContents: string) {
144 | var raw = window.atob(base64FileContents);
145 | var rawLength = raw.length;
146 | var array = new Uint8Array(new ArrayBuffer(rawLength));
147 |
148 | for(var i = 0; i < rawLength; i++) {
149 | array[i] = raw.charCodeAt(i);
150 | }
151 |
152 | return array;
153 | }
154 |
155 | //gets rows from the Expenses.xslx workbook
156 | getRows() {
157 | let helper = this;
158 | return new Promise((resolve, reject) => {
159 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
160 | helper.http.get('https://graph.microsoft.com/beta/me/drive/items/' + helper.workbookItemId + '/workbook/worksheets(\'Sheet1\')/tables(\'Table1\')/rows', {
161 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
162 | })
163 | .subscribe(res => {
164 | // Check the response status before trying to resolve
165 | if (res.status === 200)
166 | resolve(res.json().value);
167 | else
168 | reject('Get rows failed');
169 | });
170 | }, function(err) {
171 | reject(err); //error getting token for MS Graph
172 | });
173 | });
174 | }
175 |
176 | //adds a row to the Excel datasource
177 | addRow(rowData: any) {
178 | let helper = this;
179 | return new Promise((resolve, reject) => {
180 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
181 | helper.http.post('https://graph.microsoft.com/beta/me/drive/items/' + helper.workbookItemId + '/workbook/worksheets(\'Sheet1\')/tables(\'Table1\')/rows', JSON.stringify(rowData), {
182 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
183 | })
184 | .subscribe(res => {
185 | // Check the response status before trying to resolve
186 | if (res.status === 201)
187 | resolve();
188 | else
189 | reject('Get rows failed');
190 | });
191 | }, function(err) {
192 | reject(err); //error getting token for MS Graph
193 | });
194 | });
195 | }
196 |
197 | //updates a row in the Excel datasource
198 | updateRow(index:number, rowData:any) {
199 | let helper = this;
200 | return new Promise((resolve, reject) => {
201 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
202 | let address = 'Sheet1!A' + (index + 2) + ':D' + (index + 2);
203 | helper.http.patch('https://graph.microsoft.com/beta/me/drive/items/' + helper.workbookItemId + '/workbook/worksheets(\'Sheet1\')/range(address=\'' + address + '\')', JSON.stringify(rowData), {
204 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
205 | })
206 | .subscribe(res => {
207 | // Check the response status before trying to resolve
208 | if (res.status === 200)
209 | resolve();
210 | else
211 | reject('Get rows failed');
212 | });
213 | }, function(err) {
214 | reject(err); //error getting token for MS Graph
215 | });
216 | });
217 | }
218 |
219 | //deletes a row in the Excel datasource
220 | deleteRow(index:number) {
221 | let helper = this;
222 | return new Promise((resolve, reject) => {
223 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
224 | let address = 'Sheet1!A' + (index + 2) + ':D' + (index + 2);
225 | helper.http.post('https://graph.microsoft.com/beta/me/drive/items/' + helper.workbookItemId + '/workbook/worksheets(\'Sheet1\')/range(address=\'' + address + '\')/delete', JSON.stringify({ 'shift': 'Up' }), {
226 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
227 | })
228 | .subscribe(res => {
229 | // Check the response status before trying to resolve
230 | if (res.status === 204)
231 | resolve();
232 | else
233 | reject('Delete row failed');
234 | });
235 | }, function(err) {
236 | reject(err); //error getting token for MS Graph
237 | });
238 | });
239 | }
240 |
241 | //deletes a file from OneDrive for business
242 | deleteFile(id:string) {
243 | let helper = this;
244 | return new Promise((resolve, reject) => {
245 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
246 | helper.http.delete('https://graph.microsoft.com/beta/me/drive/items/' + id, {
247 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
248 | })
249 | .subscribe(res => {
250 | // Check the response status before trying to resolve
251 | if (res.status === 204)
252 | resolve();
253 | else
254 | reject('Delete row failed');
255 | });
256 | }, function(err) {
257 | reject(err); //error getting token for MS Graph
258 | });
259 | });
260 | }
261 |
262 | //loads a photo from OneDrive for Business
263 | loadPhoto(id:string) {
264 | //loads a photo for display
265 | let helper = this;
266 | return new Promise((resolve, reject) => {
267 | helper.authHelper.getTokenForResource(helper.authHelper._graphResource).then(function(token: Microsoft.ADAL.AuthenticationResult) {
268 | //first get the thumbnails
269 | helper.http.get('https://graph.microsoft.com/beta/me/drive/items/' + id + '/thumbnails', {
270 | headers: new Headers({ 'Authorization': 'Bearer ' + token.accessToken })
271 | })
272 | .subscribe(res => {
273 | // Check the response status before trying to resolve
274 | if (res.status === 200) {
275 | var data = res.json().value;
276 | var resource = data[0].medium.url.substring(8);
277 | resource = "https://" + resource.substring(0, resource.indexOf('/'));
278 | helper.authHelper.getTokenForResource(resource).then(function(thumbtoken: Microsoft.ADAL.AuthenticationResult) {
279 | //prepare the content request
280 | let req = new XMLHttpRequest();
281 | req.open('GET', data[0].medium.url, true);
282 | req.responseType = 'blob';
283 | req.setRequestHeader('Authorization', 'Bearer ' + thumbtoken.accessToken);
284 | req.setRequestHeader('Accept', 'application/json;odata=verbose');
285 | req.onload = function(e) {
286 | //check response
287 | if (this.status === 200) {
288 | //get the blob and convert to base64 using FileReader
289 | var blob = req.response;
290 | var reader = new FileReader();
291 | reader.onload = function(evt){
292 | var base64 = evt.target.result;
293 | base64 = base64.substring(base64.indexOf(',') + 1);
294 | resolve(base64);
295 | };
296 | reader.readAsDataURL(blob);
297 | }
298 | else
299 | reject('Failed to read image');
300 | };
301 | req.onerror = function(e) {
302 | reject('Failed to download image');
303 | };
304 | req.send();
305 | }, function(err) {
306 | reject('Error getting token for thumbnail');
307 | });
308 | }
309 | else
310 | reject('Thumbnail load failed');
311 | });
312 | }, function(err) {
313 | reject(err); //error getting token for MS Graph
314 | });
315 | });
316 | }
317 |
318 | //utility function get generate a random filename
319 | getRandomFileName(len: number, ext?: string, prefix?: string) {
320 | var val:string = '';
321 | var chars: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
322 | for (var i = 0; i < len; i++) {
323 | var index = Math.floor(Math.random() * chars.length);
324 | val += chars[index];
325 | }
326 |
327 | if (ext)
328 | val = val + ext;
329 | if (prefix)
330 | val = prefix + '_' + val;
331 |
332 | return val;
333 | }
334 | }
--------------------------------------------------------------------------------
/app/providers/expense.ts:
--------------------------------------------------------------------------------
1 | import {Injectable} from '@angular/core';
2 | import {DriveHelper} from '../providers/drive-helper';
3 |
4 | @Injectable()
5 | export class Expense {
6 | constructor() {
7 | }
8 |
9 | vendor: string;
10 | amount: number;
11 | category: string;
12 | receiptId: string;
13 | receiptData: string;
14 | receiptUpdated: boolean = false;
15 |
16 | //creates a new expense entry
17 | create(helper: DriveHelper) {
18 | let obj = this;
19 | return new Promise((resolve, reject) => {
20 | //first check if receipt exists
21 | if (obj.receiptUpdated) {
22 | //generate random filename
23 | var filename = helper.getRandomFileName(8, '.jpg', obj.category.replace(' ', '').replace('/', ''));
24 |
25 | //first try to save the receipt if exists
26 | helper.uploadFile(obj.receiptData, filename).then(function(id: string) {
27 | obj.receiptId = id;
28 |
29 | //now update the row
30 | var rowData = obj.parse();
31 | helper.addRow(rowData).then(function() {
32 | resolve(obj);
33 | }, function(err) {
34 | reject(err);
35 | });
36 | }, function(err) {
37 | reject(err);
38 | });
39 | }
40 | else {
41 | //add row without picture
42 | var rowData = obj.parse();
43 | helper.addRow(rowData).then(function() {
44 | resolve(obj);
45 | }, function(err) {
46 | reject(err);
47 | });
48 | }
49 | });
50 | }
51 |
52 | //updates an existing expense entry
53 | update(index: number, helper:DriveHelper) {
54 | let obj = this;
55 | return new Promise((resolve, reject) => {
56 | //first check if receipt updates
57 | if (obj.receiptUpdated) {
58 | //generate random filename
59 | var filename = helper.getRandomFileName(8, '.jpg', obj.category.replace(' ', '').replace('/', ''));
60 |
61 | //first try to save the receipt if exists
62 | helper.uploadFile(obj.receiptData, filename).then(function(id: string) {
63 | obj.receiptId = id;
64 |
65 | //now update the row
66 | var rowData = obj.parse();
67 | helper.updateRow(index, rowData).then(function() {
68 | resolve(obj);
69 | }, function(err) {
70 | reject(err);
71 | });
72 | }, function(err) {
73 | reject(err);
74 | });
75 | }
76 | else {
77 | //use same picture, just update the metadata
78 | var rowData = obj.parse();
79 | helper.updateRow(index, rowData).then(function() {
80 | resolve(obj);
81 | }, function(err) {
82 | reject(err);
83 | });
84 | }
85 | });
86 | }
87 |
88 | //deletes and expense entry
89 | delete(helper: DriveHelper, index:number) {
90 | let obj = this;
91 | return new Promise((resolve, reject) => {
92 | helper.deleteRow(index).then(function() {
93 | helper.deleteFile(obj.receiptId).then(function() {
94 | resolve();
95 | }, function(err) {
96 | reject(err);
97 | })
98 | }, function(err) {
99 | reject(err);
100 | })
101 | });
102 | }
103 |
104 | //parses the object into a mutli-dimensional array for Excel
105 | parse() {
106 | return { values: [[ this.vendor, this.amount, this.category, this.receiptId ]] };
107 | }
108 |
109 | //parses the raw data from excel into an array of Expense objects
110 | static parseArray(items:Array) : Array {
111 | var result: Array = new Array();
112 | for (var i = 0; i < items.length; i++) {
113 | var e = new Expense();
114 | e.vendor = items[i].values[0][0];
115 | e.amount = items[i].values[0][1];
116 | e.category = items[i].values[0][2];
117 | e.receiptId = items[i].values[0][3];
118 | result.push(e);
119 | }
120 | return result;
121 | }
122 |
123 | //gets all expense items
124 | static getItems(helper:DriveHelper) {
125 | return new Promise((resolve, reject) => {
126 | helper.getRows().then(function(data: Array) {
127 | resolve(Expense.parseArray(data));
128 | }, function(err) {
129 | reject(err);
130 | });
131 | });
132 | }
133 | }
--------------------------------------------------------------------------------
/app/theme/app.core.scss:
--------------------------------------------------------------------------------
1 | // http://ionicframework.com/docs/v2/theming/
2 |
3 |
4 | // App Shared Imports
5 | // --------------------------------------------------
6 | // These are the imports which make up the design of this app.
7 | // By default each design mode includes these shared imports.
8 | // App Shared Sass variables belong in app.variables.scss.
9 |
10 | @import "../pages/login/login";
11 |
12 | @import "../pages/item-details/item-details";
13 |
--------------------------------------------------------------------------------
/app/theme/app.ios.scss:
--------------------------------------------------------------------------------
1 | // http://ionicframework.com/docs/v2/theming/
2 |
3 |
4 | // App Shared Variables
5 | // --------------------------------------------------
6 | // Shared Sass variables go in the app.variables.scss file
7 | @import 'app.variables';
8 |
9 |
10 | // App iOS Variables
11 | // --------------------------------------------------
12 | // iOS only Sass variables can go here
13 |
14 |
15 | // Ionic iOS Sass
16 | // --------------------------------------------------
17 | // Custom App variables must be declared before importing Ionic.
18 | // Ionic will use its default values when a custom variable isn't provided.
19 | @import "ionic.ios";
20 |
21 |
22 | // App Shared Sass
23 | // --------------------------------------------------
24 | // All Sass files that make up this app goes into the app.core.scss file.
25 | // For simpler CSS overrides, custom app CSS must come after Ionic's CSS.
26 | @import 'app.core';
27 |
28 |
29 | // App iOS Only Sass
30 | // --------------------------------------------------
31 | // CSS that should only apply to the iOS app
32 |
--------------------------------------------------------------------------------
/app/theme/app.md.scss:
--------------------------------------------------------------------------------
1 | // http://ionicframework.com/docs/v2/theming/
2 |
3 |
4 | // App Shared Variables
5 | // --------------------------------------------------
6 | // Shared Sass variables go in the app.variables.scss file
7 | @import 'app.variables';
8 |
9 |
10 | // App Material Design Variables
11 | // --------------------------------------------------
12 | // Material Design only Sass variables can go here
13 |
14 |
15 | // Ionic Material Design Sass
16 | // --------------------------------------------------
17 | // Custom App variables must be declared before importing Ionic.
18 | // Ionic will use its default values when a custom variable isn't provided.
19 | @import "ionic.md";
20 |
21 |
22 | // App Shared Sass
23 | // --------------------------------------------------
24 | // All Sass files that make up this app goes into the app.core.scss file.
25 | // For simpler CSS overrides, custom app CSS must come after Ionic's CSS.
26 | @import 'app.core';
27 |
28 |
29 | // App Material Design Only Sass
30 | // --------------------------------------------------
31 | // CSS that should only apply to the Material Design app
32 |
--------------------------------------------------------------------------------
/app/theme/app.variables.scss:
--------------------------------------------------------------------------------
1 | // http://ionicframework.com/docs/v2/theming/
2 |
3 | // Ionic Shared Functions
4 | // --------------------------------------------------
5 | // Makes Ionic Sass functions available to your App
6 |
7 | @import 'globals.core';
8 |
9 | // App Shared Variables
10 | // --------------------------------------------------
11 | // To customize the look and feel of this app, you can override
12 | // the Sass variables found in Ionic's source scss files. Setting
13 | // variables before Ionic's Sass will use these variables rather than
14 | // Ionic's default Sass variable values. App Shared Sass imports belong
15 | // in the app.core.scss file and not this file. Sass variables specific
16 | // to the mode belong in either the app.ios.scss or app.md.scss files.
17 |
18 |
19 | // App Shared Color Variables
20 | // --------------------------------------------------
21 | // It's highly recommended to change the default colors
22 | // to match your app's branding. Ionic uses a Sass map of
23 | // colors so you can add, rename and remove colors as needed.
24 | // The "primary" color is the only required color in the map.
25 | // Both iOS and MD colors can be further customized if colors
26 | // are different per mode.
27 |
28 | $colors: (
29 | primary: #387ef5,
30 | secondary: #32db64,
31 | danger: #f53d3d,
32 | light: #f4f4f4,
33 | dark: #222,
34 | favorite: #69BB7B
35 | );
36 |
--------------------------------------------------------------------------------
/app/theme/app.wp.scss:
--------------------------------------------------------------------------------
1 | // http://ionicframework.com/docs/v2/theming/
2 |
3 |
4 | // App Shared Variables
5 | // --------------------------------------------------
6 | // Shared Sass variables go in the app.variables.scss file
7 | @import 'app.variables';
8 |
9 |
10 | // App Windows Variables
11 | // --------------------------------------------------
12 | // Windows only Sass variables can go here
13 |
14 |
15 | // Ionic Windows Sass
16 | // --------------------------------------------------
17 | // Custom App variables must be declared before importing Ionic.
18 | // Ionic will use its default values when a custom variable isn't provided.
19 | @import "ionic.wp";
20 |
21 |
22 | // App Shared Sass
23 | // --------------------------------------------------
24 | // All Sass files that make up this app goes into the app.core.scss file.
25 | // For simpler CSS overrides, custom app CSS must come after Ionic's CSS.
26 | @import 'app.core';
27 |
28 |
29 | // App Windows Only Sass
30 | // --------------------------------------------------
31 | // CSS that should only apply to the Windows app
32 |
--------------------------------------------------------------------------------
/config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | MyExpenses
4 | An Ionic Framework and Cordova project.
5 | Ionic Framework Team
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/gulpfile.js:
--------------------------------------------------------------------------------
1 | var gulp = require('gulp'),
2 | gulpWatch = require('gulp-watch'),
3 | del = require('del'),
4 | runSequence = require('run-sequence'),
5 | argv = process.argv;
6 |
7 |
8 | /**
9 | * Ionic hooks
10 | * Add ':before' or ':after' to any Ionic project command name to run the specified
11 | * tasks before or after the command.
12 | */
13 | gulp.task('serve:before', ['watch']);
14 | gulp.task('emulate:before', ['build']);
15 | gulp.task('deploy:before', ['build']);
16 | gulp.task('build:before', ['build']);
17 |
18 | // we want to 'watch' when livereloading
19 | var shouldWatch = argv.indexOf('-l') > -1 || argv.indexOf('--livereload') > -1;
20 | gulp.task('run:before', [shouldWatch ? 'watch' : 'build']);
21 |
22 | /**
23 | * Ionic Gulp tasks, for more information on each see
24 | * https://github.com/driftyco/ionic-gulp-tasks
25 | *
26 | * Using these will allow you to stay up to date if the default Ionic 2 build
27 | * changes, but you are of course welcome (and encouraged) to customize your
28 | * build however you see fit.
29 | */
30 | var buildBrowserify = require('ionic-gulp-browserify-typescript');
31 | var buildSass = require('ionic-gulp-sass-build');
32 | var copyHTML = require('ionic-gulp-html-copy');
33 | var copyFonts = require('ionic-gulp-fonts-copy');
34 | var copyScripts = require('ionic-gulp-scripts-copy');
35 |
36 | var isRelease = argv.indexOf('--release') > -1;
37 |
38 | gulp.task('watch', ['clean'], function(done){
39 | runSequence(
40 | ['sass', 'html', 'fonts', 'scripts'],
41 | function(){
42 | gulpWatch('app/**/*.scss', function(){ gulp.start('sass'); });
43 | gulpWatch('app/**/*.html', function(){ gulp.start('html'); });
44 | buildBrowserify({ watch: true }).on('end', done);
45 | }
46 | );
47 | });
48 |
49 | gulp.task('build', ['clean'], function(done){
50 | runSequence(
51 | ['sass', 'html', 'fonts', 'scripts'],
52 | function(){
53 | buildBrowserify({
54 | minify: isRelease,
55 | browserifyOptions: {
56 | debug: !isRelease
57 | },
58 | uglifyOptions: {
59 | mangle: false
60 | }
61 | }).on('end', done);
62 | }
63 | );
64 | });
65 |
66 | gulp.task('sass', buildSass);
67 | gulp.task('html', copyHTML);
68 | gulp.task('fonts', copyFonts);
69 | gulp.task('scripts', copyScripts);
70 | gulp.task('clean', function(){
71 | return del('www/build');
72 | });
73 |
--------------------------------------------------------------------------------
/hooks/README.md:
--------------------------------------------------------------------------------
1 |
21 | # Cordova Hooks
22 |
23 | Cordova Hooks represent special scripts which could be added by application and plugin developers or even by your own build system to customize cordova commands. Hook scripts could be defined by adding them to the special predefined folder (`/hooks`) or via configuration files (`config.xml` and `plugin.xml`) and run serially in the following order:
24 | * Application hooks from `/hooks`;
25 | * Application hooks from `config.xml`;
26 | * Plugin hooks from `plugins/.../plugin.xml`.
27 |
28 | __Remember__: Make your scripts executable.
29 |
30 | __Note__: `.cordova/hooks` directory is also supported for backward compatibility, but we don't recommend using it as it is deprecated.
31 |
32 | ## Supported hook types
33 | The following hook types are supported:
34 |
35 | after_build/
36 | after_compile/
37 | after_docs/
38 | after_emulate/
39 | after_platform_add/
40 | after_platform_rm/
41 | after_platform_ls/
42 | after_plugin_add/
43 | after_plugin_ls/
44 | after_plugin_rm/
45 | after_plugin_search/
46 | after_plugin_install/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being installed
47 | after_prepare/
48 | after_run/
49 | after_serve/
50 | before_build/
51 | before_compile/
52 | before_docs/
53 | before_emulate/
54 | before_platform_add/
55 | before_platform_rm/
56 | before_platform_ls/
57 | before_plugin_add/
58 | before_plugin_ls/
59 | before_plugin_rm/
60 | before_plugin_search/
61 | before_plugin_install/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being installed
62 | before_plugin_uninstall/ <-- Plugin hooks defined in plugin.xml are executed exclusively for a plugin being uninstalled
63 | before_prepare/
64 | before_run/
65 | before_serve/
66 | pre_package/ <-- Windows 8 and Windows Phone only.
67 |
68 | ## Ways to define hooks
69 | ### Via '/hooks' directory
70 | To execute custom action when corresponding hook type is fired, use hook type as a name for a subfolder inside 'hooks' directory and place you script file here, for example:
71 |
72 | # script file will be automatically executed after each build
73 | hooks/after_build/after_build_custom_action.js
74 |
75 |
76 | ### Config.xml
77 |
78 | Hooks can be defined in project's `config.xml` using `` elements, for example:
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 | ...
89 |
90 |
91 |
92 |
93 |
94 |
95 | ...
96 |
97 |
98 | ### Plugin hooks (plugin.xml)
99 |
100 | As a plugin developer you can define hook scripts using `` elements in a `plugin.xml` like that:
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 | ...
109 |
110 |
111 | `before_plugin_install`, `after_plugin_install`, `before_plugin_uninstall` plugin hooks will be fired exclusively for the plugin being installed/uninstalled.
112 |
113 | ## Script Interface
114 |
115 | ### Javascript
116 |
117 | If you are writing hooks in Javascript you should use the following module definition:
118 | ```javascript
119 | module.exports = function(context) {
120 | ...
121 | }
122 | ```
123 |
124 | You can make your scipts async using Q:
125 | ```javascript
126 | module.exports = function(context) {
127 | var Q = context.requireCordovaModule('q');
128 | var deferral = new Q.defer();
129 |
130 | setTimeout(function(){
131 | console.log('hook.js>> end');
132 | deferral.resolve();
133 | }, 1000);
134 |
135 | return deferral.promise;
136 | }
137 | ```
138 |
139 | `context` object contains hook type, executed script full path, hook options, command-line arguments passed to Cordova and top-level "cordova" object:
140 | ```json
141 | {
142 | "hook": "before_plugin_install",
143 | "scriptLocation": "c:\\script\\full\\path\\appBeforePluginInstall.js",
144 | "cmdLine": "The\\exact\\command\\cordova\\run\\with arguments",
145 | "opts": {
146 | "projectRoot":"C:\\path\\to\\the\\project",
147 | "cordova": {
148 | "platforms": ["wp8"],
149 | "plugins": ["com.plugin.withhooks"],
150 | "version": "0.21.7-dev"
151 | },
152 | "plugin": {
153 | "id": "com.plugin.withhooks",
154 | "pluginInfo": {
155 | ...
156 | },
157 | "platform": "wp8",
158 | "dir": "C:\\path\\to\\the\\project\\plugins\\com.plugin.withhooks"
159 | }
160 | },
161 | "cordova": {...}
162 | }
163 |
164 | ```
165 | `context.opts.plugin` object will only be passed to plugin hooks scripts.
166 |
167 | You can also require additional Cordova modules in your script using `context.requireCordovaModule` in the following way:
168 | ```javascript
169 | var Q = context.requireCordovaModule('q');
170 | ```
171 |
172 | __Note__: new module loader script interface is used for the `.js` files defined via `config.xml` or `plugin.xml` only.
173 | For compatibility reasons hook files specified via `/hooks` folders are run via Node child_process spawn, see 'Non-javascript' section below.
174 |
175 | ### Non-javascript
176 |
177 | Non-javascript scripts are run via Node child_process spawn from the project's root directory and have the root directory passes as the first argument. All other options are passed to the script using environment variables:
178 |
179 | * CORDOVA_VERSION - The version of the Cordova-CLI.
180 | * CORDOVA_PLATFORMS - Comma separated list of platforms that the command applies to (e.g.: android, ios).
181 | * CORDOVA_PLUGINS - Comma separated list of plugin IDs that the command applies to (e.g.: org.apache.cordova.file, org.apache.cordova.file-transfer)
182 | * CORDOVA_HOOK - Path to the hook that is being executed.
183 | * CORDOVA_CMDLINE - The exact command-line arguments passed to cordova (e.g.: cordova run ios --emulate)
184 |
185 | If a script returns a non-zero exit code, then the parent cordova command will be aborted.
186 |
187 | ## Writing hooks
188 |
189 | We highly recommend writing your hooks using Node.js so that they are
190 | cross-platform. Some good examples are shown here:
191 |
192 | [http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/](http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/)
193 |
194 | Also, note that even if you are working on Windows, and in case your hook scripts aren't bat files (which is recommended, if you want your scripts to work in non-Windows operating systems) Cordova CLI will expect a shebang line as the first line for it to know the interpreter it needs to use to launch the script. The shebang line should match the following example:
195 |
196 | #!/usr/bin/env [name_of_interpreter_executable]
197 |
--------------------------------------------------------------------------------
/hooks/after_prepare/010_add_platform_class.js:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 |
3 | // Add Platform Class
4 | // v1.0
5 | // Automatically adds the platform class to the body tag
6 | // after the `prepare` command. By placing the platform CSS classes
7 | // directly in the HTML built for the platform, it speeds up
8 | // rendering the correct layout/style for the specific platform
9 | // instead of waiting for the JS to figure out the correct classes.
10 |
11 | var fs = require('fs');
12 | var path = require('path');
13 |
14 | var rootdir = process.argv[2];
15 |
16 | function addPlatformBodyTag(indexPath, platform) {
17 | // add the platform class to the body tag
18 | try {
19 | var platformClass = 'platform-' + platform;
20 | var cordovaClass = 'platform-cordova platform-webview';
21 |
22 | var html = fs.readFileSync(indexPath, 'utf8');
23 |
24 | var bodyTag = findBodyTag(html);
25 | if(!bodyTag) return; // no opening body tag, something's wrong
26 |
27 | if(bodyTag.indexOf(platformClass) > -1) return; // already added
28 |
29 | var newBodyTag = bodyTag;
30 |
31 | var classAttr = findClassAttr(bodyTag);
32 | if(classAttr) {
33 | // body tag has existing class attribute, add the classname
34 | var endingQuote = classAttr.substring(classAttr.length-1);
35 | var newClassAttr = classAttr.substring(0, classAttr.length-1);
36 | newClassAttr += ' ' + platformClass + ' ' + cordovaClass + endingQuote;
37 | newBodyTag = bodyTag.replace(classAttr, newClassAttr);
38 |
39 | } else {
40 | // add class attribute to the body tag
41 | newBodyTag = bodyTag.replace('>', ' class="' + platformClass + ' ' + cordovaClass + '">');
42 | }
43 |
44 | html = html.replace(bodyTag, newBodyTag);
45 |
46 | fs.writeFileSync(indexPath, html, 'utf8');
47 |
48 | process.stdout.write('add to body class: ' + platformClass + '\n');
49 | } catch(e) {
50 | process.stdout.write(e);
51 | }
52 | }
53 |
54 | function findBodyTag(html) {
55 | // get the body tag
56 | try{
57 | return html.match(/])(.*?)>/gi)[0];
58 | }catch(e){}
59 | }
60 |
61 | function findClassAttr(bodyTag) {
62 | // get the body tag's class attribute
63 | try{
64 | return bodyTag.match(/ class=["|'](.*?)["|']/gi)[0];
65 | }catch(e){}
66 | }
67 |
68 | if (rootdir) {
69 |
70 | // go through each of the platform directories that have been prepared
71 | var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);
72 |
73 | for(var x=0; x
2 |
--------------------------------------------------------------------------------
/typings/browser/ambient/es6-shim/index.d.ts:
--------------------------------------------------------------------------------
1 | // Generated by typings
2 | // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/es6-shim/es6-shim.d.ts
3 | // Type definitions for es6-shim v0.31.2
4 | // Project: https://github.com/paulmillr/es6-shim
5 | // Definitions by: Ron Buckton
6 | // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
7 |
8 | declare type PropertyKey = string | number | symbol;
9 |
10 | interface IteratorResult {
11 | done: boolean;
12 | value?: T;
13 | }
14 |
15 | interface IterableShim {
16 | /**
17 | * Shim for an ES6 iterable. Not intended for direct use by user code.
18 | */
19 | "_es6-shim iterator_"(): Iterator;
20 | }
21 |
22 | interface Iterator {
23 | next(value?: any): IteratorResult;
24 | return?(value?: any): IteratorResult;
25 | throw?(e?: any): IteratorResult;
26 | }
27 |
28 | interface IterableIteratorShim extends IterableShim, Iterator {
29 | /**
30 | * Shim for an ES6 iterable iterator. Not intended for direct use by user code.
31 | */
32 | "_es6-shim iterator_"(): IterableIteratorShim;
33 | }
34 |
35 | interface StringConstructor {
36 | /**
37 | * Return the String value whose elements are, in order, the elements in the List elements.
38 | * If length is 0, the empty string is returned.
39 | */
40 | fromCodePoint(...codePoints: number[]): string;
41 |
42 | /**
43 | * String.raw is intended for use as a tag function of a Tagged Template String. When called
44 | * as such the first argument will be a well formed template call site object and the rest
45 | * parameter will contain the substitution values.
46 | * @param template A well-formed template string call site representation.
47 | * @param substitutions A set of substitution values.
48 | */
49 | raw(template: TemplateStringsArray, ...substitutions: any[]): string;
50 | }
51 |
52 | interface String {
53 | /**
54 | * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
55 | * value of the UTF-16 encoded code point starting at the string element at position pos in
56 | * the String resulting from converting this object to a String.
57 | * If there is no element at that position, the result is undefined.
58 | * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
59 | */
60 | codePointAt(pos: number): number;
61 |
62 | /**
63 | * Returns true if searchString appears as a substring of the result of converting this
64 | * object to a String, at one or more positions that are
65 | * greater than or equal to position; otherwise, returns false.
66 | * @param searchString search string
67 | * @param position If position is undefined, 0 is assumed, so as to search all of the String.
68 | */
69 | includes(searchString: string, position?: number): boolean;
70 |
71 | /**
72 | * Returns true if the sequence of elements of searchString converted to a String is the
73 | * same as the corresponding elements of this object (converted to a String) starting at
74 | * endPosition – length(this). Otherwise returns false.
75 | */
76 | endsWith(searchString: string, endPosition?: number): boolean;
77 |
78 | /**
79 | * Returns a String value that is made from count copies appended together. If count is 0,
80 | * T is the empty String is returned.
81 | * @param count number of copies to append
82 | */
83 | repeat(count: number): string;
84 |
85 | /**
86 | * Returns true if the sequence of elements of searchString converted to a String is the
87 | * same as the corresponding elements of this object (converted to a String) starting at
88 | * position. Otherwise returns false.
89 | */
90 | startsWith(searchString: string, position?: number): boolean;
91 |
92 | /**
93 | * Returns an HTML anchor element and sets the name attribute to the text value
94 | * @param name
95 | */
96 | anchor(name: string): string;
97 |
98 | /** Returns a HTML element */
99 | big(): string;
100 |
101 | /** Returns a