From 3edb1d0669123147102ab19781db98b4417fefd4 Mon Sep 17 00:00:00 2001 From: Jordan Walsh Date: Tue, 14 Mar 2017 15:46:49 +1100 Subject: [PATCH 1/6] refactored directories to clean up the structure --- lib/core.js | 2 +- lib/entities/{ => accounting}/account.js | 4 +- lib/entities/{ => accounting}/attachment.js | 4 +- .../{ => accounting}/banktransaction.js | 6 +- lib/entities/{ => accounting}/banktransfer.js | 6 +- lib/entities/{ => accounting}/contact.js | 12 +- lib/entities/{ => accounting}/invoice.js | 6 +- lib/entities/{ => accounting}/item.js | 4 +- lib/entities/{ => accounting}/journal.js | 4 +- lib/entities/{ => accounting}/organisation.js | 12 +- lib/entities/{ => accounting}/payment.js | 6 +- lib/entities/{ => accounting}/taxrate.js | 4 +- .../{ => accounting}/trackingcategory.js | 6 +- lib/entities/accounting/trackingoption.js | 53 +++++ lib/entities/{ => accounting}/user.js | 4 +- lib/entities/{ => payroll}/payitems.js | 4 +- .../{ => payroll}/payroll_employee.js | 6 +- lib/entities/payroll/timesheet.js | 85 ++++++++ lib/entities/timesheet.js | 100 --------- lib/entities/trackingoption.js | 23 -- .../{ => accounting}/accounts.js | 8 +- .../{ => accounting}/attachments.js | 8 +- .../{ => accounting}/banktransactions.js | 8 +- .../{ => accounting}/banktransfers.js | 8 +- .../{ => accounting}/contacts.js | 8 +- .../{ => accounting}/invoices.js | 8 +- lib/entity_helpers/{ => accounting}/items.js | 8 +- .../{ => accounting}/journals.js | 8 +- .../{ => accounting}/organisations.js | 8 +- .../{ => accounting}/payments.js | 8 +- .../{ => accounting}/taxrates.js | 8 +- .../{ => accounting}/trackingcategories.js | 10 +- lib/entity_helpers/{ => accounting}/users.js | 8 +- lib/entity_helpers/payitems.js | 52 ----- lib/entity_helpers/payroll/payitems.js | 45 ++++ .../{ => payroll}/payroll_employees.js | 8 +- lib/entity_helpers/payroll/timesheets.js | 31 +++ lib/entity_helpers/timesheets.js | 38 ---- lib/oauth/oauth2.js | 199 ------------------ lib/payroll.js | 20 +- 40 files changed, 325 insertions(+), 525 deletions(-) rename lib/entities/{ => accounting}/account.js (95%) rename lib/entities/{ => accounting}/attachment.js (93%) rename lib/entities/{ => accounting}/banktransaction.js (95%) rename lib/entities/{ => accounting}/banktransfer.js (93%) rename lib/entities/{ => accounting}/contact.js (94%) rename lib/entities/{ => accounting}/invoice.js (96%) rename lib/entities/{ => accounting}/item.js (94%) rename lib/entities/{ => accounting}/journal.js (94%) rename lib/entities/{ => accounting}/organisation.js (87%) rename lib/entities/{ => accounting}/payment.js (86%) rename lib/entities/{ => accounting}/taxrate.js (93%) rename lib/entities/{ => accounting}/trackingcategory.js (94%) create mode 100644 lib/entities/accounting/trackingoption.js rename lib/entities/{ => accounting}/user.js (89%) rename lib/entities/{ => payroll}/payitems.js (97%) rename lib/entities/{ => payroll}/payroll_employee.js (97%) create mode 100644 lib/entities/payroll/timesheet.js delete mode 100644 lib/entities/timesheet.js delete mode 100644 lib/entities/trackingoption.js rename lib/entity_helpers/{ => accounting}/accounts.js (86%) rename lib/entity_helpers/{ => accounting}/attachments.js (84%) rename lib/entity_helpers/{ => accounting}/banktransactions.js (85%) rename lib/entity_helpers/{ => accounting}/banktransfers.js (85%) rename lib/entity_helpers/{ => accounting}/contacts.js (86%) rename lib/entity_helpers/{ => accounting}/invoices.js (89%) rename lib/entity_helpers/{ => accounting}/items.js (85%) rename lib/entity_helpers/{ => accounting}/journals.js (92%) rename lib/entity_helpers/{ => accounting}/organisations.js (83%) rename lib/entity_helpers/{ => accounting}/payments.js (83%) rename lib/entity_helpers/{ => accounting}/taxrates.js (82%) rename lib/entity_helpers/{ => accounting}/trackingcategories.js (83%) rename lib/entity_helpers/{ => accounting}/users.js (86%) delete mode 100644 lib/entity_helpers/payitems.js create mode 100644 lib/entity_helpers/payroll/payitems.js rename lib/entity_helpers/{ => payroll}/payroll_employees.js (85%) create mode 100644 lib/entity_helpers/payroll/timesheets.js delete mode 100644 lib/entity_helpers/timesheets.js delete mode 100644 lib/oauth/oauth2.js diff --git a/lib/core.js b/lib/core.js index 400d66fd..9942184e 100644 --- a/lib/core.js +++ b/lib/core.js @@ -23,7 +23,7 @@ function Core(application, options) { this._application = application; _.each(HELPERS, function(entityHelper, id) { - var instance = new(require('./entity_helpers/' + entityHelper.file))(application); + var instance = new(require('./entity_helpers/accounting/' + entityHelper.file))(application); Object.defineProperty(self, id, { get: function() { return instance } }) diff --git a/lib/entities/account.js b/lib/entities/accounting/account.js similarity index 95% rename from lib/entities/account.js rename to lib/entities/accounting/account.js index 2d002266..76ae6583 100644 --- a/lib/entities/account.js +++ b/lib/entities/accounting/account.js @@ -1,6 +1,6 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger') + Entity = require('../entity'), + logger = require('../../logger') var AccountSchema = new Entity.SchemaObject({ Code: { type: String, toObject: 'always' }, diff --git a/lib/entities/attachment.js b/lib/entities/accounting/attachment.js similarity index 93% rename from lib/entities/attachment.js rename to lib/entities/accounting/attachment.js index e2300b5f..493faaa6 100644 --- a/lib/entities/attachment.js +++ b/lib/entities/accounting/attachment.js @@ -1,6 +1,6 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), + Entity = require('../entity'), + logger = require('../../logger'), dateformat = require('dateformat'), fs = require('fs') diff --git a/lib/entities/banktransaction.js b/lib/entities/accounting/banktransaction.js similarity index 95% rename from lib/entities/banktransaction.js rename to lib/entities/accounting/banktransaction.js index c0677458..19908d4b 100644 --- a/lib/entities/banktransaction.js +++ b/lib/entities/accounting/banktransaction.js @@ -1,9 +1,9 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), + Entity = require('../entity'), + logger = require('../../logger'), ContactSchema = require('./contact').ContactSchema, Contact = require('./contact'), - LineItemSchema = require('./shared').LineItemSchema + LineItemSchema = require('../shared').LineItemSchema var BankTransactionSchema = new Entity.SchemaObject({ Type: { type: String, toObject: 'always' }, diff --git a/lib/entities/banktransfer.js b/lib/entities/accounting/banktransfer.js similarity index 93% rename from lib/entities/banktransfer.js rename to lib/entities/accounting/banktransfer.js index ceb175b1..ac6ab147 100644 --- a/lib/entities/banktransfer.js +++ b/lib/entities/accounting/banktransfer.js @@ -1,9 +1,9 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), + Entity = require('../entity'), + logger = require('../../logger'), ContactSchema = require('./contact').ContactSchema, Contact = require('./contact'), - LineItemSchema = require('./shared').LineItemSchema + LineItemSchema = require('../shared').LineItemSchema var BankTransferSchema = new Entity.SchemaObject({ FromBankAccount: { diff --git a/lib/entities/contact.js b/lib/entities/accounting/contact.js similarity index 94% rename from lib/entities/contact.js rename to lib/entities/accounting/contact.js index 8e740224..f2968121 100644 --- a/lib/entities/contact.js +++ b/lib/entities/accounting/contact.js @@ -1,10 +1,10 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), - AddressSchema = require('./shared').AddressSchema, - PhoneSchema = require('./shared').PhoneSchema, - ContactPersonSchema = require('./shared').ContactPerson, - PaymentTermSchema = require('./shared').PaymentTermSchema, + Entity = require('../entity'), + logger = require('../../logger'), + AddressSchema = require('../shared').AddressSchema, + PhoneSchema = require('../shared').PhoneSchema, + ContactPersonSchema = require('../shared').ContactPerson, + PaymentTermSchema = require('../shared').PaymentTermSchema, dateformat = require('dateformat') var BatchPaymentSchema = new Entity.SchemaObject({ diff --git a/lib/entities/invoice.js b/lib/entities/accounting/invoice.js similarity index 96% rename from lib/entities/invoice.js rename to lib/entities/accounting/invoice.js index fd8900ab..44c62c21 100644 --- a/lib/entities/invoice.js +++ b/lib/entities/accounting/invoice.js @@ -1,9 +1,9 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), + Entity = require('../entity'), + logger = require('../../logger'), ContactSchema = require('./contact').ContactSchema, Contact = require('./contact'), - PaymentSchema = require('./shared').PaymentSchema + PaymentSchema = require('../shared').PaymentSchema var TrackingCategoryOptionsSchema = new Entity.SchemaObject({ TrackingCategoryID: { type: String, toObject: 'hasValue' }, diff --git a/lib/entities/item.js b/lib/entities/accounting/item.js similarity index 94% rename from lib/entities/item.js rename to lib/entities/accounting/item.js index 85b32190..129d6441 100644 --- a/lib/entities/item.js +++ b/lib/entities/accounting/item.js @@ -1,6 +1,6 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger') + Entity = require('../entity'), + logger = require('../../logger'); var ItemDetailSchema = new Entity.SchemaObject({ UnitPrice: { type: Number, toObject: 'hasValue' }, diff --git a/lib/entities/journal.js b/lib/entities/accounting/journal.js similarity index 94% rename from lib/entities/journal.js rename to lib/entities/accounting/journal.js index 19ff7b6d..48defe6d 100644 --- a/lib/entities/journal.js +++ b/lib/entities/accounting/journal.js @@ -1,6 +1,6 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger') + Entity = require('../entity'), + logger = require('../../logger'); var TrackingCategorySchema = new Entity.SchemaObject({ TrackingCategoryID: { type: String }, diff --git a/lib/entities/organisation.js b/lib/entities/accounting/organisation.js similarity index 87% rename from lib/entities/organisation.js rename to lib/entities/accounting/organisation.js index 7261be4e..121e47d2 100644 --- a/lib/entities/organisation.js +++ b/lib/entities/accounting/organisation.js @@ -1,10 +1,10 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), - AddressSchema = require('./shared').AddressSchema, - PhoneSchema = require('./shared').PhoneSchema, - ExternalLinkSchema = require('./shared').ExternalLinkSchema, - PaymentTermSchema = require('./shared').PaymentTermSchema + Entity = require('../entity'), + logger = require('../../logger'), + AddressSchema = require('../shared').AddressSchema, + PhoneSchema = require('../shared').PhoneSchema, + ExternalLinkSchema = require('../shared').ExternalLinkSchema, + PaymentTermSchema = require('../shared').PaymentTermSchema var OrganisationSchema = new Entity.SchemaObject({ APIKey: { type: String }, diff --git a/lib/entities/payment.js b/lib/entities/accounting/payment.js similarity index 86% rename from lib/entities/payment.js rename to lib/entities/accounting/payment.js index 6dda0164..650ca429 100644 --- a/lib/entities/payment.js +++ b/lib/entities/accounting/payment.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), - PaymentSchema = require('./shared').PaymentSchema + Entity = require('../entity'), + logger = require('../../logger'), + PaymentSchema = require('../shared').PaymentSchema var Payment = Entity.extend(PaymentSchema, { constructor: function(application, data, options) { diff --git a/lib/entities/taxrate.js b/lib/entities/accounting/taxrate.js similarity index 93% rename from lib/entities/taxrate.js rename to lib/entities/accounting/taxrate.js index 84b5f7e9..7cab9dfb 100644 --- a/lib/entities/taxrate.js +++ b/lib/entities/accounting/taxrate.js @@ -1,6 +1,6 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'); + Entity = require('../entity'), + logger = require('../../logger'); var TaxRateSchema = new Entity.SchemaObject({ Name: { type: String, toObject: 'always' }, diff --git a/lib/entities/trackingcategory.js b/lib/entities/accounting/trackingcategory.js similarity index 94% rename from lib/entities/trackingcategory.js rename to lib/entities/accounting/trackingcategory.js index 06996135..c12bbd77 100644 --- a/lib/entities/trackingcategory.js +++ b/lib/entities/accounting/trackingcategory.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), - TrackingOptionSchema = require('./shared').TrackingOptionSchema; + Entity = require('../entity'), + logger = require('../../logger'), + TrackingOptionSchema = require('../shared').TrackingOptionSchema; var TrackingCategorySchema = new Entity.SchemaObject({ TrackingCategoryID: { type: String, toObject: 'always' }, diff --git a/lib/entities/accounting/trackingoption.js b/lib/entities/accounting/trackingoption.js new file mode 100644 index 00000000..493faaa6 --- /dev/null +++ b/lib/entities/accounting/trackingoption.js @@ -0,0 +1,53 @@ +var _ = require('lodash'), + Entity = require('../entity'), + logger = require('../../logger'), + dateformat = require('dateformat'), + fs = require('fs') + +var AttachmentSchema = new Entity.SchemaObject({ + AttachmentID: { type: String, toObject: 'never' }, + FileName: { type: String, toObject: 'always' }, + Url: { type: String, toObject: 'always' }, + MimeType: { type: String, toObject: 'always' }, + ContentLength: { type: Number, toObject: 'always' } +}); + + +var Attachment = Entity.extend(AttachmentSchema, { + constructor: function(application, data, options) { + logger.debug('Attachment::constructor'); + this.Entity.apply(this, arguments); + }, + initialize: function(data, options) {}, + getContent: function(ownerPath) { + return this.application.core.attachments.getContent(ownerPath, this.FileName); + }, + save: function(ownerPath, streamOrFilePath) { + var self = this; + var path = ownerPath + '/Attachments/' + this.FileName; + + var base64string = base64_encode(streamOrFilePath); + console.log(base64string); + console.log(path); + + return this.application.postEntity(path, base64string, { type: this.MimeType }) + .then(function(ret) { + console.log(ret); + return ret.response.Attachments.Attachment; + }) + .catch(function(err) { + console.log(err); + }) + + function base64_encode(file) { + // read binary data + var bitmap = fs.readFileSync(file); + // convert binary data to base64 encoded string + return new Buffer(bitmap).toString('base64'); + } + } +}); + + +module.exports = Attachment; +module.exports.AttachmentSchema = AttachmentSchema; \ No newline at end of file diff --git a/lib/entities/user.js b/lib/entities/accounting/user.js similarity index 89% rename from lib/entities/user.js rename to lib/entities/accounting/user.js index cc5e1ec5..2defb590 100644 --- a/lib/entities/user.js +++ b/lib/entities/accounting/user.js @@ -1,6 +1,6 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger') + Entity = require('../entity'), + logger = require('../../logger'); var UserSchema = new Entity.SchemaObject({ UserID: { diff --git a/lib/entities/payitems.js b/lib/entities/payroll/payitems.js similarity index 97% rename from lib/entities/payitems.js rename to lib/entities/payroll/payitems.js index efef58e6..da00c1ed 100644 --- a/lib/entities/payitems.js +++ b/lib/entities/payroll/payitems.js @@ -1,6 +1,6 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger') + Entity = require('../entity'), + logger = require('../../logger') var EarningTypeSchema = new Entity.SchemaObject({ EarningsType: { type: String }, diff --git a/lib/entities/payroll_employee.js b/lib/entities/payroll/payroll_employee.js similarity index 97% rename from lib/entities/payroll_employee.js rename to lib/entities/payroll/payroll_employee.js index 1a54f333..21f29e59 100644 --- a/lib/entities/payroll_employee.js +++ b/lib/entities/payroll/payroll_employee.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), - ExternalLinkSchema = require('./shared').ExternalLinkSchema + Entity = require('../entity'), + logger = require('../../logger'), + ExternalLinkSchema = require('../shared').ExternalLinkSchema var AddressSchema = new Entity.SchemaObject({ StreetAddress: { type: String }, diff --git a/lib/entities/payroll/timesheet.js b/lib/entities/payroll/timesheet.js new file mode 100644 index 00000000..7fae2135 --- /dev/null +++ b/lib/entities/payroll/timesheet.js @@ -0,0 +1,85 @@ +var _ = require('lodash'), + Entity = require('../entity'), + logger = require('../../logger') + + +var TimesheetLineSchema = new Entity.SchemaObject({ + EarningsTypeID: { type: String }, + TrackingItemID: { type: String }, + NumberOfUnits: { type: Array, arrayType: Number, toObject: 'always' } +}); + +var TimesheetSchema = new Entity.SchemaObject({ + EmployeeID: { type: String, toObject: 'hasValue' }, + StartDate: { type: Date, toObjectTransform: Entity.dateToString, toObject: 'hasValue' }, + EndDate: { type: Date, toObjectTransform: Entity.dateToString, toObject: 'hasValue' }, + TimesheetLines: { type: Array, arrayType: TimesheetLineSchema, toObject: 'always' }, + Status: { type: String, toObject: 'hasValue' }, + TimesheetID: { type: String, toObject: 'hasValue' }, + Hours: { type: Number, toObject: 'hasValue' } +}); + +var Timesheet = Entity.extend(TimesheetSchema, { + constructor: function(application, data, options) { + logger.debug('Timesheet::constructor'); + this.Entity.apply(this, arguments); + }, + initialize: function(data, options) {}, + changes: function(options) { + return this._super(options); + }, + _toObject: function(options) { + return this._super(options); + }, + fromXmlObj: function(obj) { + var self = this; + Object.assign(self, _.omit(obj, 'TimesheetLines')); + if (obj.TimesheetLines) { + var items = this.application.asArray(obj.TimesheetLines.TimesheetLine); + _.each(items, function(item) { + + var index = self.TimesheetLines.push({ EarningsTypeID: item.EarningsTypeID }) - 1; + var addedNumberOfUnit = self.TimesheetLines[index]; + _.each(item.NumberOfUnits.NumberOfUnit, function(unit) { + addedNumberOfUnit.NumberOfUnits.push(unit); + }) + + }) + } + + return this; + }, + toXml: function() { + var timesheet = _.omit(this.toObject(), 'TimesheetLines'); + Object.assign(timesheet, { TimesheetLines: [] }); + _.forEach(this.TimesheetLines, function(timesheetline) { + timesheet.TimesheetLines.push({ TimesheetLine: _.pick(timesheetline.toObject(), 'EarningsTypeID', 'TrackingItemID') }); + var addedTimesheetLine = _.last(timesheet.TimesheetLines).TimesheetLine; + addedTimesheetLine.NumberOfUnits = { NumberOfUnit: [] }; + _.each(timesheetline.NumberOfUnits, function(num) { + addedTimesheetLine.NumberOfUnits.NumberOfUnit.push(num); + }) + + }) + + return this.application.js2xml(timesheet, 'Timesheet'); + }, + save: function(options) { + var self = this + var xml = '' + this.toXml() + ''; + var path, method; + if (this.TimesheetID) { + path = 'Timesheets/' + this.TimesheetID; + method = 'post' + } else { + path = 'Timesheets'; + method = 'post' + } + return this.application.putOrPostEntity(method, path, xml, { entityPath: 'Timesheets.Timesheet', entityConstructor: function(data) { return self.application.payroll.timesheets.newTimesheet(data) }, api: 'payroll' }); + } + +}); + + +module.exports = Timesheet; +module.exports.TimesheetSchema = TimesheetSchema; \ No newline at end of file diff --git a/lib/entities/timesheet.js b/lib/entities/timesheet.js deleted file mode 100644 index 37f32430..00000000 --- a/lib/entities/timesheet.js +++ /dev/null @@ -1,100 +0,0 @@ -var _ = require('lodash') - , Entity = require('./entity') - , logger = require('../logger') - - -var TimesheetLineSchema = new Entity.SchemaObject({ - EarningsTypeID: {type: String}, - TrackingItemID: {type: String}, - NumberOfUnits: {type: Array, arrayType: Number, toObject: 'always'} -}); - -var TimesheetSchema = new Entity.SchemaObject({ - EmployeeID: {type: String, toObject: 'hasValue'}, - StartDate: {type: Date, toObjectTransform: Entity.dateToString,toObject: 'hasValue'}, - EndDate: {type: Date, toObjectTransform: Entity.dateToString,toObject: 'hasValue'}, - TimesheetLines: {type: Array, arrayType: TimesheetLineSchema, toObject: 'always'}, - Status: {type: String, toObject: 'hasValue'}, - TimesheetID: {type: String, toObject: 'hasValue'}, - Hours: {type: Number, toObject: 'hasValue'} -}); - -var Timesheet = Entity.extend(TimesheetSchema, { - constructor: function (application, data, options) - { - logger.debug('Timesheet::constructor'); - this.Entity.apply(this, arguments); - }, - initialize: function (data, options) - { - }, - changes: function (options) - { - return this._super(options); - }, - _toObject: function (options) - { - return this._super(options); - }, - fromXmlObj: function (obj) - { - var self = this; - Object.assign(self, _.omit(obj, 'TimesheetLines')); - if (obj.TimesheetLines) { - var items = this.application.asArray(obj.TimesheetLines.TimesheetLine); - _.each(items,function(item) - { - - var index = self.TimesheetLines.push({ EarningsTypeID: item.EarningsTypeID}) - 1; - var addedNumberOfUnit = self.TimesheetLines[index]; - _.each(item.NumberOfUnits.NumberOfUnit, function(unit) - { - addedNumberOfUnit.NumberOfUnits.push(unit); - }) - - }) - } - - return this; - }, - toXml: function () - { - var timesheet = _.omit(this.toObject(), 'TimesheetLines'); - Object.assign(timesheet, { TimesheetLines: []}); - _.forEach(this.TimesheetLines, function(timesheetline) - { - timesheet.TimesheetLines.push({ TimesheetLine: _.pick(timesheetline.toObject(),'EarningsTypeID','TrackingItemID')}); - var addedTimesheetLine = _.last(timesheet.TimesheetLines).TimesheetLine; - addedTimesheetLine.NumberOfUnits = { NumberOfUnit: []}; - _.each(timesheetline.NumberOfUnits, function(num) - { - addedTimesheetLine.NumberOfUnits.NumberOfUnit.push(num); - }) - - }) - - return this.application.js2xml(timesheet, 'Timesheet'); - }, - save:function(options) - { - var self = this - var xml = '' + this.toXml() + ''; - var path, method; - if (this.TimesheetID) - { - path = 'Timesheets/' + this.TimesheetID; - method = 'post' - } - else - { - path = 'Timesheets'; - method = 'post' - } - return this.application.putOrPostEntity(method, path, xml, { entityPath: 'Timesheets.Timesheet',entityConstructor: function(data) { return self.application.payroll.timesheets.newTimesheet(data)}, api: 'payroll'}); - } - -}); - - -module.exports = Timesheet; -module.exports.TimesheetSchema = TimesheetSchema; diff --git a/lib/entities/trackingoption.js b/lib/entities/trackingoption.js deleted file mode 100644 index 01bb9fe2..00000000 --- a/lib/entities/trackingoption.js +++ /dev/null @@ -1,23 +0,0 @@ -var _ = require('lodash'), - Entity = require('./entity'), - logger = require('../logger'), - TrackingOptionSchema = require('./shared').TrackingOptionSchema; - -var TrackingOption = Entity.extend(TrackingOptionSchema, { - constructor: function(application, data, options) { - logger.debug('TrackingOption::constructor'); - this.Entity.apply(this, arguments); - }, - initialize: function(data, options) {}, - changes: function(options) { - return this._super(options); - }, - _toObject: function(options) { - return this._super(options); - }, - delete: function() { - return this.deleteEntities({ id: this.TrackingOptionID }); - } -}); - -module.exports = TrackingOption; \ No newline at end of file diff --git a/lib/entity_helpers/accounts.js b/lib/entity_helpers/accounting/accounts.js similarity index 86% rename from lib/entity_helpers/accounts.js rename to lib/entity_helpers/accounting/accounts.js index 7389ff7d..e50950b8 100644 --- a/lib/entity_helpers/accounts.js +++ b/lib/entity_helpers/accounting/accounts.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Account = require('../entities/account'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Account = require('../../entities/accounting/account'), util = require('util') var Accounts = EntityHelper.extend({ @@ -34,4 +34,4 @@ var Accounts = EntityHelper.extend({ } }) -module.exports = Accounts; +module.exports = Accounts; \ No newline at end of file diff --git a/lib/entity_helpers/attachments.js b/lib/entity_helpers/accounting/attachments.js similarity index 84% rename from lib/entity_helpers/attachments.js rename to lib/entity_helpers/accounting/attachments.js index f6e8d9f8..9ef5edc1 100644 --- a/lib/entity_helpers/attachments.js +++ b/lib/entity_helpers/accounting/attachments.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Attachment = require('../entities/attachment'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Attachment = require('../../entities/accounting/attachment'), util = require('util') var Attachments = EntityHelper.extend({ @@ -25,4 +25,4 @@ var Attachments = EntityHelper.extend({ } }) -module.exports = Attachments; +module.exports = Attachments; \ No newline at end of file diff --git a/lib/entity_helpers/banktransactions.js b/lib/entity_helpers/accounting/banktransactions.js similarity index 85% rename from lib/entity_helpers/banktransactions.js rename to lib/entity_helpers/accounting/banktransactions.js index e8d046eb..5983b912 100644 --- a/lib/entity_helpers/banktransactions.js +++ b/lib/entity_helpers/accounting/banktransactions.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - BankTransaction = require('../entities/banktransaction'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + BankTransaction = require('../../entities/accounting/banktransaction'), util = require('util') var BankTransactions = EntityHelper.extend({ @@ -31,4 +31,4 @@ var BankTransactions = EntityHelper.extend({ } }) -module.exports = BankTransactions; +module.exports = BankTransactions; \ No newline at end of file diff --git a/lib/entity_helpers/banktransfers.js b/lib/entity_helpers/accounting/banktransfers.js similarity index 85% rename from lib/entity_helpers/banktransfers.js rename to lib/entity_helpers/accounting/banktransfers.js index 9f8da4ab..dd0fd1cf 100644 --- a/lib/entity_helpers/banktransfers.js +++ b/lib/entity_helpers/accounting/banktransfers.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - BankTransfer = require('../entities/banktransfer'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + BankTransfer = require('../../entities/accounting/banktransfer'), util = require('util') var BankTransfers = EntityHelper.extend({ @@ -31,4 +31,4 @@ var BankTransfers = EntityHelper.extend({ } }) -module.exports = BankTransfers; +module.exports = BankTransfers; \ No newline at end of file diff --git a/lib/entity_helpers/contacts.js b/lib/entity_helpers/accounting/contacts.js similarity index 86% rename from lib/entity_helpers/contacts.js rename to lib/entity_helpers/accounting/contacts.js index d12b677a..65fcf0a5 100644 --- a/lib/entity_helpers/contacts.js +++ b/lib/entity_helpers/accounting/contacts.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Contact = require('../entities/contact'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Contact = require('../../entities/accounting/contact'), util = require('util') var Contacts = EntityHelper.extend({ @@ -32,4 +32,4 @@ var Contacts = EntityHelper.extend({ } }) -module.exports = Contacts; +module.exports = Contacts; \ No newline at end of file diff --git a/lib/entity_helpers/invoices.js b/lib/entity_helpers/accounting/invoices.js similarity index 89% rename from lib/entity_helpers/invoices.js rename to lib/entity_helpers/accounting/invoices.js index ddf82c24..f41ef55c 100644 --- a/lib/entity_helpers/invoices.js +++ b/lib/entity_helpers/accounting/invoices.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Invoice = require('../entities/invoice'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Invoice = require('../../entities/accounting/invoice'), util = require('util') var Invoices = EntityHelper.extend({ @@ -38,4 +38,4 @@ var Invoices = EntityHelper.extend({ } }) -module.exports = Invoices; +module.exports = Invoices; \ No newline at end of file diff --git a/lib/entity_helpers/items.js b/lib/entity_helpers/accounting/items.js similarity index 85% rename from lib/entity_helpers/items.js rename to lib/entity_helpers/accounting/items.js index 3f1f3b5d..9492c651 100644 --- a/lib/entity_helpers/items.js +++ b/lib/entity_helpers/accounting/items.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Item = require('../entities/item'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Item = require('../../entities/accounting/item'), util = require('util') var Items = EntityHelper.extend({ @@ -31,4 +31,4 @@ var Items = EntityHelper.extend({ } }) -module.exports = Items; +module.exports = Items; \ No newline at end of file diff --git a/lib/entity_helpers/journals.js b/lib/entity_helpers/accounting/journals.js similarity index 92% rename from lib/entity_helpers/journals.js rename to lib/entity_helpers/accounting/journals.js index 0ba7c671..1b8b5219 100644 --- a/lib/entity_helpers/journals.js +++ b/lib/entity_helpers/accounting/journals.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Journal = require('../entities/journal'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Journal = require('../../entities/accounting/journal'), util = require('util') var Journals = EntityHelper.extend({ @@ -59,4 +59,4 @@ var Journals = EntityHelper.extend({ } }) -module.exports = Journals; +module.exports = Journals; \ No newline at end of file diff --git a/lib/entity_helpers/organisations.js b/lib/entity_helpers/accounting/organisations.js similarity index 83% rename from lib/entity_helpers/organisations.js rename to lib/entity_helpers/accounting/organisations.js index c643114b..f66ba677 100644 --- a/lib/entity_helpers/organisations.js +++ b/lib/entity_helpers/accounting/organisations.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Organisation = require('../entities/organisation'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Organisation = require('../../entities/accounting/organisation'), util = require('util') var Organisations = EntityHelper.extend({ @@ -27,4 +27,4 @@ var Organisations = EntityHelper.extend({ } }) -module.exports = Organisations; +module.exports = Organisations; \ No newline at end of file diff --git a/lib/entity_helpers/payments.js b/lib/entity_helpers/accounting/payments.js similarity index 83% rename from lib/entity_helpers/payments.js rename to lib/entity_helpers/accounting/payments.js index 10f93256..e59e246a 100644 --- a/lib/entity_helpers/payments.js +++ b/lib/entity_helpers/accounting/payments.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Payment = require('../entities/payment'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Payment = require('../../entities/accounting/payment'), util = require('util') var Payments = EntityHelper.extend({ @@ -25,4 +25,4 @@ var Payments = EntityHelper.extend({ } }) -module.exports = Payments; +module.exports = Payments; \ No newline at end of file diff --git a/lib/entity_helpers/taxrates.js b/lib/entity_helpers/accounting/taxrates.js similarity index 82% rename from lib/entity_helpers/taxrates.js rename to lib/entity_helpers/accounting/taxrates.js index 41a727ef..809800a8 100644 --- a/lib/entity_helpers/taxrates.js +++ b/lib/entity_helpers/accounting/taxrates.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - TaxRate = require('../entities/taxrate'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + TaxRate = require('../../entities/accounting/taxrate'), util = require('util') var TaxRates = EntityHelper.extend({ @@ -23,4 +23,4 @@ var TaxRates = EntityHelper.extend({ } }) -module.exports = TaxRates; +module.exports = TaxRates; \ No newline at end of file diff --git a/lib/entity_helpers/trackingcategories.js b/lib/entity_helpers/accounting/trackingcategories.js similarity index 83% rename from lib/entity_helpers/trackingcategories.js rename to lib/entity_helpers/accounting/trackingcategories.js index 412d0930..f9ed5e56 100644 --- a/lib/entity_helpers/trackingcategories.js +++ b/lib/entity_helpers/accounting/trackingcategories.js @@ -1,8 +1,8 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - TrackingCategory = require('../entities/trackingcategory'), - TrackingOption = require('../entities/trackingoption.js'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + TrackingCategory = require('../../entities/accounting/trackingcategory'), + TrackingOption = require('../../entities/accounting/trackingoption'), util = require('util') var TrackingCategories = EntityHelper.extend({ @@ -36,4 +36,4 @@ var TrackingCategories = EntityHelper.extend({ } }) -module.exports = TrackingCategories; +module.exports = TrackingCategories; \ No newline at end of file diff --git a/lib/entity_helpers/users.js b/lib/entity_helpers/accounting/users.js similarity index 86% rename from lib/entity_helpers/users.js rename to lib/entity_helpers/accounting/users.js index 414f59ff..c4cf3c6c 100644 --- a/lib/entity_helpers/users.js +++ b/lib/entity_helpers/accounting/users.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - User = require('../entities/user'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + User = require('../../entities/accounting/user'), util = require('util') var Users = EntityHelper.extend({ @@ -30,4 +30,4 @@ var Users = EntityHelper.extend({ } }) -module.exports = Users; +module.exports = Users; \ No newline at end of file diff --git a/lib/entity_helpers/payitems.js b/lib/entity_helpers/payitems.js deleted file mode 100644 index e88ac005..00000000 --- a/lib/entity_helpers/payitems.js +++ /dev/null @@ -1,52 +0,0 @@ -var _ = require('lodash') - , logger = require('../logger') - , EntityHelper = require('./entity_helper') - , PayItemsObject = require('../entities/payitems') - , EarningsType = require('../entities/payitems').EarningsType - , BenefitType = require('../entities/payitems').BenefitType - , DeductionType = require('../entities/payitems').DeductionType - , ReimbursementType = require('../entities/payitems').ReimbursementType - , TimeOffType = require('../entities/payitems').TimeOffType - , util = require('util') - -var PayItems = EntityHelper.extend({ - constructor: function (application, options) - { - EntityHelper.call(this, application, Object.assign({ - entityPlural: 'PayItems', path: 'Payitems'}, options)); - }, - newPayItems: function(data, options) - { - return new PayItemsObject(this.application, data, options) - }, - newEarningType: function (data, options) - { - return new EarningsType(this.application, data, options) - }, - newDeductionType: function (data, options) - { - return new DeductionType(this.application, data, options) - }, - newBenefitType: function (data, options) - { - return new BenefitType(this.application, data, options) - }, - newReimbursementType: function (data, options) - { - return new ReimbursementType(this.application, data, options) - }, - newTimeOffType: function (data, options) - { - return new TimeOffType(this.application, data, options) - }, - getPayItems: function (options) - { - var self = this; - var clonedOptions = Object.assign({},options, { api: 'payroll'}); - clonedOptions.entityConstructor = function(data) { return self.newPayItems(data)}; - return this.getEntities(clonedOptions) - } -}) - -module.exports = PayItems; - diff --git a/lib/entity_helpers/payroll/payitems.js b/lib/entity_helpers/payroll/payitems.js new file mode 100644 index 00000000..7d374869 --- /dev/null +++ b/lib/entity_helpers/payroll/payitems.js @@ -0,0 +1,45 @@ +var _ = require('lodash'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + PayItemsObject = require('../../entities/payroll/payitems'), + EarningsType = require('../../entities/payroll/payitems').EarningsType, + BenefitType = require('../../entities/payroll/payitems').BenefitType, + DeductionType = require('../../entities/payroll/payitems').DeductionType, + ReimbursementType = require('../../entities/payroll/payitems').ReimbursementType, + TimeOffType = require('../../entities/payroll/payitems').TimeOffType, + util = require('util') + +var PayItems = EntityHelper.extend({ + constructor: function(application, options) { + EntityHelper.call(this, application, Object.assign({ + entityPlural: 'PayItems', + path: 'Payitems' + }, options)); + }, + newPayItems: function(data, options) { + return new PayItemsObject(this.application, data, options) + }, + newEarningType: function(data, options) { + return new EarningsType(this.application, data, options) + }, + newDeductionType: function(data, options) { + return new DeductionType(this.application, data, options) + }, + newBenefitType: function(data, options) { + return new BenefitType(this.application, data, options) + }, + newReimbursementType: function(data, options) { + return new ReimbursementType(this.application, data, options) + }, + newTimeOffType: function(data, options) { + return new TimeOffType(this.application, data, options) + }, + getPayItems: function(options) { + var self = this; + var clonedOptions = Object.assign({}, options, { api: 'payroll' }); + clonedOptions.entityConstructor = function(data) { return self.newPayItems(data) }; + return this.getEntities(clonedOptions) + } +}) + +module.exports = PayItems; \ No newline at end of file diff --git a/lib/entity_helpers/payroll_employees.js b/lib/entity_helpers/payroll/payroll_employees.js similarity index 85% rename from lib/entity_helpers/payroll_employees.js rename to lib/entity_helpers/payroll/payroll_employees.js index 648a3471..b3d559c8 100644 --- a/lib/entity_helpers/payroll_employees.js +++ b/lib/entity_helpers/payroll/payroll_employees.js @@ -1,7 +1,7 @@ var _ = require('lodash'), - logger = require('../logger'), - EntityHelper = require('./entity_helper'), - Employee = require('../entities/payroll_employee'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Employee = require('../../entities/payroll/payroll_employee'), util = require('util') var Employees = EntityHelper.extend({ @@ -29,4 +29,4 @@ var Employees = EntityHelper.extend({ } }) -module.exports = Employees; +module.exports = Employees; \ No newline at end of file diff --git a/lib/entity_helpers/payroll/timesheets.js b/lib/entity_helpers/payroll/timesheets.js new file mode 100644 index 00000000..79e5159a --- /dev/null +++ b/lib/entity_helpers/payroll/timesheets.js @@ -0,0 +1,31 @@ +var _ = require('lodash'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Timesheet = require('../../entities/payroll/timesheet'), + util = require('util') + +var Timesheets = EntityHelper.extend({ + constructor: function(application, options) { + EntityHelper.call(this, application, Object.assign({ entityName: 'Timesheet', entityPlural: 'Timesheets' }, options)); + }, + newTimesheet: function(data, options) { + return new Timesheet(this.application, data, options) + }, + getTimesheet: function(id, modifiedAfter, where, order) { + return this.getTimesheets({ id: id, modifiedAfter: modifiedAfter, where: where, order: order }) + .then(function(timesheets) { + return _.first(timesheets); + }) + }, + saveTimesheets: function(timesheets, options) { + return this.saveEntities(timesheets, Object.assign({}, options, { method: 'post', api: 'payroll' })); + }, + getTimesheets: function(options) { + var self = this; + var clonedOptions = Object.assign({}, options, { api: 'payroll' }); + clonedOptions.entityConstructor = function(data) { return self.newTimesheet(data) }; + return this.getEntities(clonedOptions) + } +}) + +module.exports = Timesheets; \ No newline at end of file diff --git a/lib/entity_helpers/timesheets.js b/lib/entity_helpers/timesheets.js deleted file mode 100644 index 9aa4dec6..00000000 --- a/lib/entity_helpers/timesheets.js +++ /dev/null @@ -1,38 +0,0 @@ -var _ = require('lodash') - , logger = require('../logger') - , EntityHelper = require('./entity_helper') - , Timesheet = require('../entities/timesheet') - , util = require('util') - -var Timesheets = EntityHelper.extend({ - constructor: function (application, options) - { - EntityHelper.call(this, application, Object.assign({ entityName:'Timesheet', entityPlural:'Timesheets'}, options)); - }, - newTimesheet: function (data, options) - { - return new Timesheet(this.application, data, options) - }, - getTimesheet: function (id, modifiedAfter,where, order) - { - return this.getTimesheets({ id: id, modifiedAfter: modifiedAfter, where: where, order: order}) - .then(function (timesheets) - { - return _.first(timesheets); - }) - }, - saveTimesheets: function (timesheets, options) - { - return this.saveEntities(timesheets, Object.assign({},options,{ method: 'post',api: 'payroll'})); - }, - getTimesheets: function (options) - { - var self = this; - var clonedOptions = Object.assign({},options, { api: 'payroll'}); - clonedOptions.entityConstructor = function(data) { return self.newTimesheet(data)}; - return this.getEntities(clonedOptions) - } -}) - -module.exports = Timesheets; - diff --git a/lib/oauth/oauth2.js b/lib/oauth/oauth2.js deleted file mode 100644 index 3210171f..00000000 --- a/lib/oauth/oauth2.js +++ /dev/null @@ -1,199 +0,0 @@ -var querystring= require('querystring'), - crypto= require('crypto'), - https= require('https'), - http= require('http'), - URL= require('url'), - OAuthUtils= require('./_utils'); - -exports.OAuth2= function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) { - this._clientId= clientId; - this._clientSecret= clientSecret; - this._baseSite= baseSite; - this._authorizeUrl= authorizePath || "/oauth/authorize"; - this._accessTokenUrl= accessTokenPath || "/oauth/access_token"; - this._accessTokenName= "access_token"; - this._authMethod= "Bearer"; - this._customHeaders = customHeaders || {}; - this._useAuthorizationHeaderForGET= false; -} - -// This 'hack' method is required for sites that don't use -// 'access_token' as the name of the access token (for requests). -// ( http://tools.ietf.org/html/draft-ietf-oauth-v2-16#section-7 ) -// it isn't clear what the correct value should be atm, so allowing -// for specific (temporary?) override for now. -exports.OAuth2.prototype.setAccessTokenName= function ( name ) { - this._accessTokenName= name; -} - -// Sets the authorization method for Authorization header. -// e.g. Authorization: Bearer # "Bearer" is the authorization method. -exports.OAuth2.prototype.setAuthMethod = function ( authMethod ) { - this._authMethod = authMethod; -}; - - -// If you use the OAuth2 exposed 'get' method (and don't construct your own _request call ) -// this will specify whether to use an 'Authorize' header instead of passing the access_token as a query parameter -exports.OAuth2.prototype.useAuthorizationHeaderforGET = function(useIt) { - this._useAuthorizationHeaderForGET= useIt; -} - -exports.OAuth2.prototype._getAccessTokenUrl= function() { - return this._baseSite + this._accessTokenUrl; /* + "?" + querystring.stringify(params); */ -} - -// Build the authorization header. In particular, build the part after the colon. -// e.g. Authorization: Bearer # Build "Bearer " -exports.OAuth2.prototype.buildAuthHeader= function(token) { - return this._authMethod + ' ' + token; -}; - -exports.OAuth2.prototype._request= function(method, url, headers, post_body, access_token, callback) { - - var http_library= https; - var creds = crypto.createCredentials({ }); - var parsedUrl= URL.parse( url, true ); - if( parsedUrl.protocol == "https:" && !parsedUrl.port ) { - parsedUrl.port= 443; - } - - // As this is OAUth2, we *assume* https unless told explicitly otherwise. - if( parsedUrl.protocol != "https:" ) { - http_library= http; - } - - var realHeaders= {}; - for( var key in this._customHeaders ) { - realHeaders[key]= this._customHeaders[key]; - } - if( headers ) { - for(var key in headers) { - realHeaders[key] = headers[key]; - } - } - realHeaders['Host']= parsedUrl.host; - - if (!realHeaders['User-Agent']) { - realHeaders['User-Agent'] = 'Node-oauth'; - } - - realHeaders['Content-Length']= post_body ? Buffer.byteLength(post_body) : 0; - if( access_token && !('Authorization' in realHeaders)) { - if( ! parsedUrl.query ) parsedUrl.query= {}; - parsedUrl.query[this._accessTokenName]= access_token; - } - - var queryStr= querystring.stringify(parsedUrl.query); - if( queryStr ) queryStr= "?" + queryStr; - var options = { - host:parsedUrl.hostname, - port: parsedUrl.port, - path: parsedUrl.pathname + queryStr, - method: method, - headers: realHeaders - }; - - this._executeRequest( http_library, options, post_body, callback ); -} - -exports.OAuth2.prototype._executeRequest= function( http_library, options, post_body, callback ) { - // Some hosts *cough* google appear to close the connection early / send no content-length header - // allow this behaviour. - var allowEarlyClose= OAuthUtils.isAnEarlyCloseHost(options.host); - var callbackCalled= false; - function passBackControl( response, result ) { - if(!callbackCalled) { - callbackCalled=true; - if( response.statusCode != 200 && (response.statusCode != 301) && (response.statusCode != 302) ) { - callback({ statusCode: response.statusCode, data: result }); - } else { - callback(null, result, response); - } - } - } - - var result= ""; - - var request = http_library.request(options, function (response) { - response.on("data", function (chunk) { - result+= chunk - }); - response.on("close", function (err) { - if( allowEarlyClose ) { - passBackControl( response, result ); - } - }); - response.addListener("end", function () { - passBackControl( response, result ); - }); - }); - request.on('error', function(e) { - callbackCalled= true; - callback(e); - }); - - if( options.method == 'POST' && post_body ) { - request.write(post_body); - } - request.end(); -} - -exports.OAuth2.prototype.getAuthorizeUrl= function( params ) { - var params= params || {}; - params['client_id'] = this._clientId; - return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params); -} - -exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { - var params= params || {}; - params['client_id'] = this._clientId; - params['client_secret'] = this._clientSecret; - var codeParam = (params.grant_type === 'refresh_token') ? 'refresh_token' : 'code'; - params[codeParam]= code; - - var post_data= querystring.stringify( params ); - var post_headers= { - 'Content-Type': 'application/x-www-form-urlencoded' - }; - - - this._request("POST", this._getAccessTokenUrl(), post_headers, post_data, null, function(error, data, response) { - if( error ) callback(error); - else { - var results; - try { - // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07 - // responses should be in JSON - results= JSON.parse( data ); - } - catch(e) { - // .... However both Facebook + Github currently use rev05 of the spec - // and neither seem to specify a content-type correctly in their response headers :( - // clients of these services will suffer a *minor* performance cost of the exception - // being thrown - results= querystring.parse( data ); - } - var access_token= results["access_token"]; - var refresh_token= results["refresh_token"]; - delete results["refresh_token"]; - callback(null, access_token, refresh_token, results); // callback results =-= - } - }); -} - -// Deprecated -exports.OAuth2.prototype.getProtectedResource= function(url, access_token, callback) { - this._request("GET", url, {}, "", access_token, callback ); -} - -exports.OAuth2.prototype.get= function(url, access_token, callback) { - if( this._useAuthorizationHeaderForGET ) { - var headers= {'Authorization': this.buildAuthHeader(access_token) } - access_token= null; - } - else { - headers= {}; - } - this._request("GET", url, headers, "", access_token, callback ); -} diff --git a/lib/payroll.js b/lib/payroll.js index 4f930f04..2f0f43e8 100644 --- a/lib/payroll.js +++ b/lib/payroll.js @@ -1,22 +1,20 @@ -var _ = require('lodash') - , logger = require('./logger') +var _ = require('lodash'), + logger = require('./logger') var HELPERS = { - timesheets: { file: 'timesheets'}, - payitems: { file: 'payitems'}, - employees: { file: 'payroll_employees'} + timesheets: { file: 'timesheets' }, + payitems: { file: 'payitems' }, + employees: { file: 'payroll_employees' } }; -function Payroll(application, options) -{ +function Payroll(application, options) { var self = this; logger.debug('Payroll::constructor'); this._application = application; - _.each(HELPERS, function(entityHelper, id) - { - var instance = new (require('./entity_helpers/' + entityHelper.file))(application); - Object.defineProperty(self, id, { + _.each(HELPERS, function(entityHelper, id) { + var instance = new(require('./entity_helpers/payroll/' + entityHelper.file))(application); + Object.defineProperty(self, id, { get: function() { return instance } }) }) From 1661b878d101971a21e6f08e23d0f49ea8fb3844 Mon Sep 17 00:00:00 2001 From: Jordan Walsh Date: Tue, 14 Mar 2017 16:48:44 +1100 Subject: [PATCH 2/6] added initial reports functionality... tests currently broken --- lib/application.js | 2 +- lib/core.js | 3 +- lib/entities/accounting/report.js | 58 ++++++++++++++++++++++++ lib/entity_helpers/accounting/reports.js | 25 ++++++++++ test/accountingtests.js | 30 ++++++++++-- 5 files changed, 113 insertions(+), 5 deletions(-) create mode 100644 lib/entities/accounting/report.js create mode 100644 lib/entity_helpers/accounting/reports.js diff --git a/lib/application.js b/lib/application.js index c532f664..0c89e9a6 100644 --- a/lib/application.js +++ b/lib/application.js @@ -560,4 +560,4 @@ var PartnerApplication = RequireAuthorizationApplication.extend({ module.exports.PrivateApplication = PrivateApplication; module.exports.PublicApplication = PublicApplication; module.exports.PartnerApplication = PartnerApplication; -module.exports.Application = Application; +module.exports.Application = Application; \ No newline at end of file diff --git a/lib/core.js b/lib/core.js index 9942184e..d2227832 100644 --- a/lib/core.js +++ b/lib/core.js @@ -14,7 +14,8 @@ var HELPERS = { trackingCategories: { file: 'trackingcategories' }, users: { file: 'users' }, payments: { file: 'payments' }, - taxrates: { file: 'taxrates' } + taxrates: { file: 'taxrates' }, + reports: { file: 'reports' } }; function Core(application, options) { diff --git a/lib/entities/accounting/report.js b/lib/entities/accounting/report.js new file mode 100644 index 00000000..2b23517f --- /dev/null +++ b/lib/entities/accounting/report.js @@ -0,0 +1,58 @@ +var _ = require('lodash'), + Entity = require('../entity'), + logger = require('../../logger'); + +var ReportSchema = new Entity.SchemaObject({ + ReportID: { type: String, toObject: 'always' }, + ReportName: { type: String, toObject: 'always' }, + ReportType: { type: String, toObject: 'always' }, + ReportTitles: [ReportTitleSchema], + ReportDate: { type: String, toObject: 'always' }, + UpdatedDateUTC: { type: String, toObject: 'always' }, + Rows: [ReportRowSchema] +}); + +var ReportTitleSchema = new Entity.SchemaObject({ + ReportTitle: { type: String, toObject: 'always' } +}); + +var ReportRowSchema = new Entity.SchemaObject({ + RowType: { type: String, toObject: 'always' }, + Title: { type: String, toObject: 'always' }, + Cells: [ReportCellSchema] +}); + +var ReportCellSchema = new Entity.SchemaObject({ + Value: { type: String, toObject: 'always' }, + Attributes: [ReportAttributeSchema] +}); + +var ReportAttributeSchema = new Entity.SchemaObject({ + Value: { type: String, toObject: 'always' }, + Id: { type: String, toObject: 'always' } +}); + +var Report = Entity.extend(ReportSchema, { + constructor: function(application, data, options) { + logger.debug('Report::constructor'); + this.Entity.apply(this, arguments); + }, + initialize: function(data, options) {}, + fromXmlObj: function(obj) { + var self = this; + Object.assign(self, _.omit(obj, 'Rows', 'Cells')); + if (obj.Rows) { + _.each(obj.Rows.Row, function(row) { + _.each(row.Cells.Cell, function(cell) { + console.log(cell); + }); + self.Rows.push(row); + }); + } + + return this; + } +}); + +module.exports = Report; +module.exports.ItemSchema = ReportSchema; \ No newline at end of file diff --git a/lib/entity_helpers/accounting/reports.js b/lib/entity_helpers/accounting/reports.js new file mode 100644 index 00000000..9ae26c6e --- /dev/null +++ b/lib/entity_helpers/accounting/reports.js @@ -0,0 +1,25 @@ +var _ = require('lodash'), + logger = require('../../logger'), + EntityHelper = require('../entity_helper'), + Report = require('../../entities/accounting/report'), + util = require('util') + +var Reports = EntityHelper.extend({ + constructor: function(application, options) { + EntityHelper.call(this, application, Object.assign({ entityName: 'Report', entityPlural: 'Reports' }, options)); + }, + create: function(data, options) { + return new Report(this.application, data, options) + }, + generateReport: function(options) { + var self = this; + var clonedOptions = _.clone(options || {}); + clonedOptions.entityConstructor = function(data) { return self.create(data) }; + return this.getEntities(clonedOptions) + .then(function(reports) { + return _.first(reports); + }); + } +}) + +module.exports = Reports; \ No newline at end of file diff --git a/test/accountingtests.js b/test/accountingtests.js index 305f6ec3..13c340ef 100644 --- a/test/accountingtests.js +++ b/test/accountingtests.js @@ -66,7 +66,7 @@ describe('get access for public or partner application', function() { console.log("URL: " + authoriseUrl); console.log("token: " + requestToken); console.log("secret: " + requestSecret); - }); + }); }); describe('gets the request token from the url', function() { @@ -149,7 +149,7 @@ describe('get access for public or partner application', function() { describe('swaps the request token for an access token', function() { it('calls the access token method and sets the options', function() { return currentApp.getAccessToken(requestToken, requestSecret, verifier) - .then(function({token, secret}) { + .then(function({ token, secret }) { currentApp.setOptions({ accessToken: token, accessSecret: secret }); }); }); @@ -157,7 +157,30 @@ describe('get access for public or partner application', function() { }); }); -describe('regression tests', function() { +describe('reporting tests', function() { + this.timeout(10000); + it('generates a Balance Sheet', function(done) { + currentApp.core.reports.generateReport({ id: 'BalanceSheet' }) + .then(function(report) { + expect(report.ReportType).to.equal('BalanceSheet'); + expect(report.ReportName).to.equal('Balance Sheet'); + expect(report.Rows).to.have.length.greaterThan(0); + report.Rows.forEach(function(row) { + expect(row.RowType).to.be.oneOf(['Header', 'Section', 'Row', 'SummaryRow']); + expect(row.Cells).to.have.length.greaterThan(0); + }); + done(); + }) + .catch(function(err) { + console.log(err); + done(wrapError(err)); + }) + + }); + +}) + +describe.skip('regression tests', function() { var InvoiceID = ""; var PaymentID = ""; @@ -230,6 +253,7 @@ describe('regression tests', function() { done(); }) .catch(function(err) { + console.log(err); done(wrapError(err)); }) }) From 7e612c34ce32f4e165ae2b62ddc8376a7ce166cf Mon Sep 17 00:00:00 2001 From: Jordan Walsh Date: Wed, 15 Mar 2017 11:04:27 +1100 Subject: [PATCH 3/6] adding recursion to reports parsing --- lib/entities/accounting/report.js | 53 ++++++++++++++++++++++++++++--- test/accountingtests.js | 19 ++++++++++- 2 files changed, 67 insertions(+), 5 deletions(-) diff --git a/lib/entities/accounting/report.js b/lib/entities/accounting/report.js index 2b23517f..4017143b 100644 --- a/lib/entities/accounting/report.js +++ b/lib/entities/accounting/report.js @@ -41,16 +41,61 @@ var Report = Entity.extend(ReportSchema, { fromXmlObj: function(obj) { var self = this; Object.assign(self, _.omit(obj, 'Rows', 'Cells')); + + + if (hasMoreRows(obj)) { + logger.debug("Top Level"); + obj.Rows.Row.forEach(function(thisRow) { + + if (hasMoreRows(thisRow)) { + logger.debug("2nd Level"); + thisRow.Rows.Row.forEach(function(anotherRow) { + + if (hasMoreRows(anotherRow)) { + logger.debug("3rd Level"); + anotherRow.Rows.Row.forEach(function(lastRow) { + + if (hasMoreRows(lastRow)) { + logger.debug("You're kidding"); + } + + }); + } + + }); + } + + }); + } + + if (obj.Rows) { - _.each(obj.Rows.Row, function(row) { - _.each(row.Cells.Cell, function(cell) { - console.log(cell); - }); + obj.Rows.Row.forEach(function(row) { + row.Cells ? row.Cells = extractCells(row) : false; self.Rows.push(row); }); } return this; + + function extractRows(obj) { + + } + + function hasMoreRows(obj) { + return obj.Rows && obj.Rows.Row && obj.Rows.Row.length >= 0; + } + + function extractCells(row) { + var cells = []; + if (row.Cells) { + row.Cells.Cell.forEach(function(cell) { + cells.push(cell); + }); + row.Cells = cells; + } + return cells; + } } }); diff --git a/test/accountingtests.js b/test/accountingtests.js index 76a2e4a5..1eb3c443 100644 --- a/test/accountingtests.js +++ b/test/accountingtests.js @@ -224,9 +224,26 @@ describe('reporting tests', function() { expect(report.ReportName).to.equal('Balance Sheet'); expect(report.Rows).to.have.length.greaterThan(0); report.Rows.forEach(function(row) { + console.log(row); expect(row.RowType).to.be.oneOf(['Header', 'Section', 'Row', 'SummaryRow']); - expect(row.Cells).to.have.length.greaterThan(0); + + //Each row can have some cells, each cell should have some data. + if (row.Cells) { + expect(row.Cells).to.have.length.greaterThan(0); + row.Cells.forEach(function(cell) { + //each cell can either be a string or an object + expect(cell).to.not.equal(undefined); + expect(cell).to.satisfy(function(c) { return typeof c === "string" || typeof c === "object" }); + }); + } + + + if (row.Rows) { + //This row has nested rows + } + }); + done(); }) .catch(function(err) { From 673c805b4a337ef2c6e92a41bf1884f23cfdb88c Mon Sep 17 00:00:00 2001 From: Jordan Walsh Date: Wed, 15 Mar 2017 12:31:53 +1100 Subject: [PATCH 4/6] added reports to the sample app, not yet completed --- lib/application.js | 2 +- lib/entities/accounting/report.js | 50 +++--- sample_app/index.js | 51 ++++++ sample_app/views/index.handlebars | 6 + sample_app/views/partials/nav.handlebars | 12 ++ sample_app/views/reports.handlebars | 1 + test/accountingtests.js | 194 ++++++++++++++++++++--- 7 files changed, 264 insertions(+), 52 deletions(-) create mode 100644 sample_app/views/reports.handlebars diff --git a/lib/application.js b/lib/application.js index 8da8d59d..dd6acf79 100644 --- a/lib/application.js +++ b/lib/application.js @@ -267,7 +267,7 @@ Object.assign(Application.prototype, { function getResource(offset) { var endPointUrl = options.api === 'payroll' ? self.options.payrollAPIEndPointUrl : self.options.coreAPIEndPointUrl; var url = self.options.baseUrl + endPointUrl + path; - var params = {}; + var params = options.params || {}; if (offset) { params[options.pager.paramName || 'page'] = offset; if (options.other) { diff --git a/lib/entities/accounting/report.js b/lib/entities/accounting/report.js index 4017143b..616f89dc 100644 --- a/lib/entities/accounting/report.js +++ b/lib/entities/accounting/report.js @@ -42,46 +42,32 @@ var Report = Entity.extend(ReportSchema, { var self = this; Object.assign(self, _.omit(obj, 'Rows', 'Cells')); - if (hasMoreRows(obj)) { - logger.debug("Top Level"); - obj.Rows.Row.forEach(function(thisRow) { - - if (hasMoreRows(thisRow)) { - logger.debug("2nd Level"); - thisRow.Rows.Row.forEach(function(anotherRow) { - - if (hasMoreRows(anotherRow)) { - logger.debug("3rd Level"); - anotherRow.Rows.Row.forEach(function(lastRow) { - - if (hasMoreRows(lastRow)) { - logger.debug("You're kidding"); - } - - }); - } - + //Loop through the rows to find the next level down + obj.Rows.Row.forEach(function(level1Row) { + + if (hasMoreRows(level1Row)) { + var level2RowsArray = []; + level1Row.Rows.Row.forEach(function(level2row) { + level2row.Cells ? level2row.Cells = extractCells(level2row) : false; + level2RowsArray.push(level2row); }); + level1Row.Rows = level2RowsArray; } + level1Row.Cells ? level1Row.Cells = extractCells(level1Row) : false; + self.Rows.push(level1Row); }); - } - - - if (obj.Rows) { - obj.Rows.Row.forEach(function(row) { - row.Cells ? row.Cells = extractCells(row) : false; - self.Rows.push(row); - }); + } else { + //No more rows, but we should check for cells in this row + if (obj.Rows && obj.Rows.Row && obj.Rows.Row.Cells && obj.Rows.Row.Cells.Cell && obj.Rows.Row.Cells.Cell.length > 0) { + obj.Rows.Row.Cells = extractCells(obj.Rows.Row); + self.Rows.push(obj.Rows.Row); + } } return this; - function extractRows(obj) { - - } - function hasMoreRows(obj) { return obj.Rows && obj.Rows.Row && obj.Rows.Row.length >= 0; } @@ -100,4 +86,4 @@ var Report = Entity.extend(ReportSchema, { }); module.exports = Report; -module.exports.ItemSchema = ReportSchema; \ No newline at end of file +module.exports.ReportSchema = ReportSchema; \ No newline at end of file diff --git a/sample_app/index.js b/sample_app/index.js index 65f9e448..5165d82f 100644 --- a/sample_app/index.js +++ b/sample_app/index.js @@ -436,6 +436,57 @@ app.get('/items', function(req, res) { }) }); +app.get('/reports', function(req, res) { + authorizedOperation(req, res, '/reports', function(xeroClient) { + + var reportkeys = { + '1': 'BalanceSheet', + '2': 'TrialBalance', + '3': 'ProfitAndLoss', + '4': 'BankStatement', + '5': 'BudgetSummary', + '6': 'ExecutiveSummary', + '7': 'BankSummary', + '8': 'AgedReceivablesByContact', + '9': 'AgedPayablesByContact' + }; + + var report = req.query ? req.query.r : null; + + if (reportkeys[report]) { + var selectedReport = reportkeys[report]; + + var data = { + active: {} + }; + + data.active[selectedReport.toLowerCase()] = true; + + xeroClient.core.reports.generateReport({ + id: selectedReport + }) + .then(function(report) { + data.report = report; + res.render('reports', data); + }) + .catch(function(err) { + handleErr(err, req, res, 'reports'); + }) + + + } else { + res.render('index', { + error: { + message: "Report not found" + }, + active: { + overview: true + } + }); + } + }) +}); + app.use('/createinvoice', function(req, res) { if (req.method == 'GET') { return res.render('createinvoice'); diff --git a/sample_app/views/index.handlebars b/sample_app/views/index.handlebars index a55a7dfa..706ed320 100644 --- a/sample_app/views/index.handlebars +++ b/sample_app/views/index.handlebars @@ -1,3 +1,9 @@ +{{#if error}} +
+ Error: {{error.message}} +
+{{/if}} +

Xero Node.js - Sample App

An API wrapper for the Xero API (http://developer.xero.com).

Supports all three applications types:

diff --git a/sample_app/views/partials/nav.handlebars b/sample_app/views/partials/nav.handlebars index 31cf49ef..0101c38f 100644 --- a/sample_app/views/partials/nav.handlebars +++ b/sample_app/views/partials/nav.handlebars @@ -15,6 +15,18 @@
  • List Tracking Categories
  • List Users
  • +
    Reports
    +
    Payroll API - AU