Skip to content

Commit

Permalink
Work on adding getUserProfileSettings and changeUserProfileSettings f…
Browse files Browse the repository at this point in the history
…or the /users/{accountId} endpoint
  • Loading branch information
natereprogle committed Jul 3, 2024
1 parent 48aee76 commit 86d5694
Show file tree
Hide file tree
Showing 5 changed files with 267 additions and 33 deletions.
6 changes: 0 additions & 6 deletions .idea/jsLibraryMappings.xml

This file was deleted.

105 changes: 102 additions & 3 deletions src/RequestService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
/*
* Copyright (c) TerrorByte 2024.
* This program is free software: You can redistribute it and/or modify it under the terms of the
* Mozilla Public License 2.0 as published by the Mozilla under the Mozilla Foundation.
*
* This program is distributed in the hope that it will be useful, but provided on an "as is" basis,
* without warranty of any kind, either expressed, implied, or statutory, including,
* without limitation, warranties that the Covered Software is free of defects, merchantable,
* fit for a particular purpose or non-infringing. See the MPL 2.0 license for more details.
*
* For a full copy of the license in its entirety, please visit <https://www.mozilla.org/en-US/MPL/2.0/>
*/

import {
AccountSettingsResponse,
AccountUpdateConfig,
AlertSeveritiesResponse,
AlertsNotesResponse,
AlertsResponse,
Expand All @@ -7,6 +22,7 @@ import {
GetMetersResponse,
HawkAuthResponse,
HawkConfig,
RequireAtLeastOne,
SortType,
ThresholdAlertSettingsConfig,
TimeseriesMetrics,
Expand Down Expand Up @@ -206,10 +222,14 @@ class RequestService {
return response.data
}

async getCurrentAlertSettings(): Promise<ThresholdAlertSettingsConfig> {
async getCurrentAlertSettings(accountId?: string): Promise<ThresholdAlertSettingsConfig> {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

const accountId = this._authService.getAuthInfo().body.activeUser?.attributes.accountIdArray[0]
// If one wasn't provided we'll try to retrieve it from the accountIdArray in the AuthInfo body
if (!accountId) {
accountId = this._authService.getAuthInfo().body.activeUser?.attributes.accountIdArray[0]
}

if (accountId) {
const meters = await this._instance.get<GetMetersResponse>('/meters', {
params: {
Expand Down Expand Up @@ -251,7 +271,7 @@ class RequestService {

return convertToFriendlyConfig(accounts.data, meters.data)
} else {
throw new Error('Failed to get current account settings, an accountId could not be retrieved from previous auth requests')
throw new Error('Failed to get current alerting settings, an accountId could not be retrieved from previous auth requests nor was one wasn\'t provided')
}
}

Expand Down Expand Up @@ -307,6 +327,85 @@ class RequestService {
async refreshSession(): Promise<HawkAuthResponse> {
return await this._authService.authenticate(this._config.username, this._config.password, this._instance)
}

async getUserProfileSettings(accountId?: string): Promise<AccountSettingsResponse> {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

// If one wasn't provided we'll try to retrieve it from the accountIdArray in the AuthInfo body
if (!accountId) {
accountId = this._authService.getAuthInfo().body.activeUser?.attributes.accountIdArray[0]
}

if (accountId) {
const response = await this._instance.get<AccountSettingsResponse>(`/users/${accountId}`, {
params: {
'_dc': Date.now(),
},
})

return response.data
} else {
throw new Error('Failed to get current account settings, an accountId could not be retrieved from previous auth requests nor was one wasn\'t provided')
}
}

async changeUserProfileSettings(contactPreference: 'cellPhone' | 'homePhone' | 'email' | 'workPhone' | 'doNotContact' | 'text', updateInfo: RequireAtLeastOne<AccountUpdateConfig, 'cellPhone' | 'homePhone' | 'workPhone'>, accountId?: string): Promise<AccountSettingsResponse> {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

// If one wasn't provided we'll try to retrieve it from the accountIdArray in the AuthInfo body
if (!accountId) {
accountId = this._authService.getAuthInfo().body.activeUser?.attributes.accountIdArray[0]
}

const data = await this.getUserProfileSettings(accountId);
const updatedInfo = Object.assign({}, data.users, updateInfo)
updatedInfo.contactPreference = { [contactPreference]: true }

if (accountId) {
const response = await this._instance.put<AccountSettingsResponse>(`/users/${accountId}`, updatedInfo, {
params: {
'_dc': Date.now(),
'notify': 1
},
}).catch((error: unknown) => {
throw new Error(`An error occurred while updating your account: ${error as string}`)
})

return response.data
} else {
throw new Error('Failed to get current account settings, an accountId could not be retrieved from previous auth requests nor was one wasn\'t provided')
}
}

async registerAccounts() {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

return Promise.resolve(undefined)
}

async exportDataToCsv() {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

return Promise.resolve(undefined)
}

async getExportedData() {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

return Promise.resolve(undefined)
}

async changePassword() {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

return Promise.resolve(undefined)
}

async getReports() {
if (this.checkIfAuthNeeded()) await this._authService.authenticate(this._config.username, this._config.password, this._instance)

return Promise.resolve(undefined)
}
}

export default RequestService
13 changes: 13 additions & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
/*
* Copyright (c) TerrorByte 2024.
* This program is free software: You can redistribute it and/or modify it under the terms of the
* Mozilla Public License 2.0 as published by the Mozilla under the Mozilla Foundation.
*
* This program is distributed in the hope that it will be useful, but provided on an "as is" basis,
* without warranty of any kind, either expressed, implied, or statutory, including,
* without limitation, warranties that the Covered Software is free of defects, merchantable,
* fit for a particular purpose or non-infringing. See the MPL 2.0 license for more details.
*
* For a full copy of the license in its entirety, please visit <https://www.mozilla.org/en-US/MPL/2.0/>
*/

import {
AlertSeveritiesResponse,
AlertsNotesResponse,
Expand Down
72 changes: 57 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
// This causes a warning when removed that the import can be shorter but, if it is shorter, then it will throw a warning due to circular references
// noinspection ES6PreferShortImport
import {
AccountUpdateConfig,
AlertSeveritiesResponse,
AlertsNotesResponse,
AlertsResponse,
Expand All @@ -23,6 +24,7 @@ import {
GetMetersResponse,
HawkAuthResponse,
HawkConfig,
RequireAtLeastOne,
SortType,
ThresholdAlertSettingsConfig,
TimeseriesMetrics,
Expand All @@ -42,7 +44,7 @@ import { AuthService } from './AuthService'
* If you have access to Water or Natural Gas through Utility/AquaHawk, please open an issue so we can work with you and add support.
*/
export class HawkClient {
constructor(private requestService: RequestService) {
constructor(private _requestService: RequestService) {
}

/**
Expand All @@ -66,7 +68,7 @@ export class HawkClient {
* @throws {Error} An error is thrown if authentication hasn't happened yet
*/
public getSessionInformation(): HawkAuthResponse {
return this.requestService.getSessionInformation()
return this._requestService.getSessionInformation()
}

/**
Expand All @@ -76,7 +78,7 @@ export class HawkClient {
* @returns {Promise<HawkAuthResponse>} The new session information
*/
public async forceSessionRefresh(): Promise<HawkAuthResponse> {
if (this.requestService.checkIfAuthNeeded()) await this.requestService.refreshSession()
if (this._requestService.checkIfAuthNeeded()) await this._requestService.refreshSession()
return this.getSessionInformation()
}

Expand All @@ -85,7 +87,7 @@ export class HawkClient {
* @returns {Promise<number>} The token's expiration time in Epoch (milliseconds)
*/
public async getTokenExpirationTime(): Promise<number> {
if (this.requestService.checkIfAuthNeeded()) await this.requestService.refreshSession()
if (this._requestService.checkIfAuthNeeded()) await this._requestService.refreshSession()

const cookieParts: string[] = this.getSessionInformation().sessionCookie.split(';')
const dateString = cookieParts[2]?.split('=')[1]
Expand Down Expand Up @@ -122,7 +124,7 @@ export class HawkClient {
temperature: true,
rainfall: true,
}): Promise<TimeseriesResponse> {
return this.requestService.getTimeseriesData(accountNumber, startTime, endTime, interval, extraStartTime, extraEndTime, metrics)
return this._requestService.getTimeseriesData(accountNumber, startTime, endTime, interval, extraStartTime, extraEndTime, metrics)
}

/**
Expand All @@ -137,7 +139,7 @@ export class HawkClient {
* @returns {Promise<GetAccountsResponse>}
*/
public async getAccounts(sort: SortType = 'alertSeverityRank', secondarySort: SortType = 'lastActiveTime', dir: 'asc' | 'desc' = 'desc', secondaryDir: 'asc' | 'desc' = 'desc', page = 1, start = 0, limit = 100): Promise<GetAccountsResponse> {
return this.requestService.getAccounts(sort, secondarySort, dir, secondaryDir, page, start, limit)
return this._requestService.getAccounts(sort, secondarySort, dir, secondaryDir, page, start, limit)
}

/**
Expand All @@ -148,7 +150,7 @@ export class HawkClient {
* @returns {Promise<AlertTypes>}
*/
public async getAlertTypes(page = 1, start = 0, limit = 25): Promise<AlertTypes> {
return this.requestService.getAlertTypes(page, start, limit)
return this._requestService.getAlertTypes(page, start, limit)
}

/**
Expand All @@ -162,7 +164,7 @@ export class HawkClient {
* @returns {Promise<AlertsResponse>}
*/
public async getAlerts(accountNumber: string, sort: SortType = 'updatedTime', dir: 'asc' | 'desc' = 'desc', page = 1, start = 0, limit = 100): Promise<AlertsResponse> {
return this.requestService.getAlerts(accountNumber, sort, dir, page, start, limit)
return this._requestService.getAlerts(accountNumber, sort, dir, page, start, limit)
}

/**
Expand All @@ -176,7 +178,7 @@ export class HawkClient {
* @returns {Promise<AlertsNotesResponse>}
*/
public async getAlertNotes(accountNumber: string, sort: SortType = 'savedTime', dir: 'asc' | 'desc' = 'desc', page = 1, start = 0, limit = 100): Promise<AlertsNotesResponse> {
return this.requestService.getAlertNotes(accountNumber, sort, dir, page, start, limit)
return this._requestService.getAlertNotes(accountNumber, sort, dir, page, start, limit)
}

/**
Expand All @@ -187,7 +189,7 @@ export class HawkClient {
* @returns {Promise<AlertSeveritiesResponse>}
*/
public async getAlertSeverities(page = 1, start = 0, limit = 25): Promise<AlertSeveritiesResponse> {
return this.requestService.getAlertSeverities(page, start, limit)
return this._requestService.getAlertSeverities(page, start, limit)
}

/**
Expand All @@ -202,7 +204,7 @@ export class HawkClient {
* @param limit Limit. Defaults to 100
*/
public async getMeterByAccountID(accountId: string, sort: SortType = 'alertSeverityRank', secondarySort: SortType = 'lastActiveTime', dir: 'asc' | 'desc' = 'desc', secondaryDir: 'asc' | 'desc' = 'desc', page = 1, start = 0, limit = 100) {
return this.requestService.getMeterByAccountID(accountId, sort, secondarySort, dir, secondaryDir, page, start, limit)
return this._requestService.getMeterByAccountID(accountId, sort, secondarySort, dir, secondaryDir, page, start, limit)
}

/**
Expand All @@ -216,15 +218,17 @@ export class HawkClient {
* @returns {Promise<GetMetersResponse>}
*/
public async getMeterByAccountNumber(accountNumber: string, sort: SortType = 'lastActiveTime', dir: 'asc' | 'desc', page: number, start: number, limit: number): Promise<GetMetersResponse> {
return this.requestService.getMeterByAccountNumber(accountNumber, sort, dir, page, start, limit)
return this._requestService.getMeterByAccountNumber(accountNumber, sort, dir, page, start, limit)
}

/**
* Get current account and meter alerting settings. See {@link updateAlertSettings} to update these settings
* @param accountId An optional userId to pass in to specify which accountId you want to query alert settings for.
* If none is specified, hawk-js will default to the first one returned in the AuthBody
* @returns {Promise<ThresholdAlertSettingsConfig>}
*/
public async getCurrentAlertSettings(): Promise<ThresholdAlertSettingsConfig> {
return this.requestService.getCurrentAlertSettings()
public async getCurrentAlertSettings(accountId?: string): Promise<ThresholdAlertSettingsConfig> {
return this._requestService.getCurrentAlertSettings(accountId)
}

/**
Expand All @@ -236,6 +240,44 @@ export class HawkClient {
* @returns {Promise<UpdateAlertSettingsResponse>}
*/
public async updateAlertSettings(config: ThresholdAlertSettingsConfig, meterId?: string): Promise<UpdateAlertSettingsResponse> {
return this.requestService.updateAlertSettings(config, meterId)
return this._requestService.updateAlertSettings(config, meterId)
}

/**
*
* @param accountId
*/
public async getUserProfileSettings(accountId?: string) {
return this._requestService.getUserProfileSettings(accountId)
}

/**
*
* @param settings
* @param updateInfo
* @param accountId
*/
public async changeUserProfileSettings(settings: 'cellPhone' | 'homePhone' | 'email' | 'workPhone' | 'doNotContact' | 'text', updateInfo: RequireAtLeastOne<AccountUpdateConfig, 'cellPhone' | 'homePhone' | 'workPhone'>, accountId?: string) {
return this._requestService.changeUserProfileSettings(settings, updateInfo, accountId);
}

public async registerAccounts() {
return this._requestService.registerAccounts()
}

public async exportDataToCsv() {
return this._requestService.exportDataToCsv()
}

public async getExportedData() {
return this._requestService.getExportedData()
}

public async changePassword() {
return this._requestService.changePassword()
}

public async getReports() {
return this._requestService.getReports()
}
}
Loading

0 comments on commit 86d5694

Please sign in to comment.