added subscription edit

This commit is contained in:
Fran Jurmanovic
2021-07-30 19:56:56 +02:00
parent 4a69e8c370
commit e73e5b025b
13 changed files with 369 additions and 38 deletions

View File

@@ -43,7 +43,7 @@
"uglify-js": "^3.13.9",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
}
}

View File

@@ -33,6 +33,7 @@ class AppDropdownElement extends BaseComponentElement {
page: number = 1;
rpp: number = 30;
validator: Validator;
itemValue: any = null;
constructor() {
super();
@@ -119,7 +120,10 @@ class AppDropdownElement extends BaseComponentElement {
};
get selectedItem() {
const { value, valuekey, items } = this;
const { value, valuekey, items, itemValue } = this;
if (itemValue) {
return itemValue;
}
const item = items?.find((item) => {
return value == item[valuekey];
});
@@ -173,6 +177,7 @@ class AppDropdownElement extends BaseComponentElement {
itemSelected = (e) => {
const value = (e.target as HTMLSpanElement).getAttribute('data-value');
this.itemValue = null;
this.setValue(value);
this.setOpen(false);
this.appForm?.inputChange(e);
@@ -183,6 +188,11 @@ class AppDropdownElement extends BaseComponentElement {
this.update();
};
setItemValue = (itemValue) => {
this.itemValue = itemValue;
this.update();
}
render = () => {
const { label, error, errorMessage, isOpen, searchPhrase, items, selectedItem, displaykey, valuekey } = this;

View File

@@ -77,13 +77,27 @@ class AppFormElement extends BaseComponentElement {
formObject[input.name] = input._value;
});
this.appDropdown?.forEach((input: AppDropdownElement) => {
if (input.required && input.value) {
formObject[input.name] = input._value;
}
});
return formObject;
}
set = (data): any => {
for (let i = 0; i < this.inputField.length; i++) {
const input = this.inputField[i];
if(data?.[input.name]) {
input._value = data[input.name]
this.update()
}
}
this.appDropdown?.forEach((input: AppDropdownElement) => {
if(data?.[input.name]) {
input.setValue(data[input.name])
this.update()
}
});
}
getInput = (name: string): InputFieldElement | AppDropdownElement => {
let formObject;
this.inputField.forEach((input: InputFieldElement) => {

View File

@@ -18,6 +18,7 @@ class InputFieldElement extends BaseComponentElement {
@target main: HTMLElement;
@target inp: HTMLElement;
@closest appForm: AppFormElement;
@attr disabled: string;
valid: boolean;
displayError: boolean;
randId: string;
@@ -36,12 +37,16 @@ class InputFieldElement extends BaseComponentElement {
//this.validate();
};
attributeChangedCallback() {
this.update();
}
setError = (error) => {
this.validator.error = error;
};
get error(): string {
return this.validator.error;
return this.validator?.error;
}
get isValid(): boolean {
@@ -53,9 +58,24 @@ class InputFieldElement extends BaseComponentElement {
}
get _value() {
if (this.type == 'checkbox') {
return (this.inp as HTMLInputElement)?.checked;
}
return (this.inp as HTMLInputElement)?.value;
}
get _disabled() {
return this.disabled == "true"
}
set _value(value) {
if (this.type == 'checkbox') {
(this.inp as HTMLInputElement).checked = (value as boolean);
} else {
(this.inp as HTMLInputElement).value = (value as string);
}
}
validate = (): boolean => {
const valid = this.validator.validate();
if (valid && this.displayError) {
@@ -88,7 +108,6 @@ class InputFieldElement extends BaseComponentElement {
};
render = (): TemplateResult => {
console.log('e');
const renderMessage = (label: string) => {
if (this.label) {
return html`<label for="${this.randId}">${this.label}${this.required ? ' (*)' : ''}</label>`;
@@ -113,6 +132,7 @@ class InputFieldElement extends BaseComponentElement {
step="0.01"
data-target="input-field.inp"
id="${this.randId}"
?disabled=${this._disabled}
app-action=" input:input-field#inputChange blur:input-field#validateDisplay
${this.customAction ? this.customAction : ''} "
/>`;
@@ -122,6 +142,7 @@ class InputFieldElement extends BaseComponentElement {
autocomplete="${this.name}"
type="${this.type}"
data-target="input-field.inp"
?disabled=${this._disabled}
id="${this.randId}"
app-action="
input:input-field#inputChange

View File

@@ -50,7 +50,7 @@ class AppService {
}
};
delete = async (url: string, data: Object, headersParam: HeadersInit): Promise<any> => {
delete = async (url: string, data?: Object, headersParam?: HeadersInit): Promise<any> => {
headersParam = {
...headersParam,
Authorization: `BEARER ${this.appMain?.authStore?.token}`,

View File

@@ -7,20 +7,20 @@ class BaseService {
return this.appService.get(this.endpoint, params, headers);
};
get = (params?: Object, headers?: HeadersInit) => {
return this.appService.get(this.endpoint, params, headers);
get = (id: string, params?: Object, headers?: HeadersInit) => {
return this.appService.get(this.endpoint + `/${id}`, params, headers);
};
put = (data?: Object, headers?: HeadersInit) => {
return this.appService.put(this.endpoint, data, headers);
put = (id: string, data?: any, headers?: HeadersInit) => {
return this.appService.put(this.endpoint + `/${id || data?.id || ''}`, data, headers);
};
post = (data?: Object, headers?: HeadersInit) => {
return this.appService.post(this.endpoint, data, headers);
};
delete = (data?: Object, headers?: HeadersInit) => {
return this.appService.delete(this.endpoint, data, headers);
delete = (id:string, data?: any, headers?: HeadersInit) => {
return this.appService.delete(this.endpoint + `/${id || data?.id || ''}`, data, headers);
};
}

View File

@@ -10,3 +10,4 @@ export * from './transaction-create/TransactionCreateElement';
export * from './subscription-create/SubscriptionCreateElement';
export * from './subscription-list/SubscriptionListElement';
export * from './wallet-page/WalletPageElement';
export * from './subscription-edit/SubscriptionEditElement';

View File

@@ -142,18 +142,18 @@ class SubscriptionCreateElement extends BasePageElement {
if (response?.id) {
this.appMain.triggerTransactionUpdate();
this.appMain.pushToast('success', 'Transaction created successfully!');
this.appMain.pushToast('success', 'Subscription created successfully!');
if (walletData.walletId) {
this.appMain?.closeModal();
} else {
this.routerService.goTo('/history', {
this.routerService.goTo('/subscriptions', {
walletId: response.walletId,
});
}
}
} catch (err) {
this.errorMessage = 'Unable to create transaction!';
this.errorMessage = 'Unable to create subscription!';
this.update();
}
};

View File

@@ -0,0 +1,259 @@
import { targets, controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'core/utils';
import {
AuthService,
SubscriptionService,
SubscriptionTypeService,
TransactionTypeService,
WalletService,
} from 'services/';
import { AppFormElement, InputFieldElement } from 'components/';
import { BasePageElement } from 'common/';
import { AppDropdownElement } from 'components/app-dropdown/AppDropdownElement';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);
@controller
class SubscriptionEditElement extends BasePageElement {
@targets inputs: Array<InputFieldElement | AppDropdownElement>;
@target appForm: AppFormElement;
private subscriptionService: SubscriptionService;
private transactionTypeService: TransactionTypeService;
private subscriptionTypeService: SubscriptionTypeService;
private walletService: WalletService;
walletData: any = null;
authService: AuthService;
errorMessage: string;
private initial: boolean = false;
constructor() {
super({
title: 'Edit Subscription',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.subscriptionService = new SubscriptionService(this.appMain?.appService);
this.transactionTypeService = new TransactionTypeService(this.appMain?.appService);
this.subscriptionTypeService = new SubscriptionTypeService(this.appMain?.appService);
this.authService = new AuthService(this.appMain.appService);
this.walletData = this.getData();
this.getSubscription(this.walletData.id);
this.update();
if (this.walletData && this.walletData.walletId) {
this.setTransactionType();
} else {
this.initial = true;
}
};
get hasEndCheck(): InputFieldElement | AppDropdownElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == 'hasEnd') {
return this.inputs[i];
}
}
}
get nameInput(): InputFieldElement | AppDropdownElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == 'name') {
return this.inputs[i];
}
}
}
get values(): any {
const formObject: any = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
setTransactionType = async () => {
this.appForm.isValid = false;
try {
const response = await this.transactionTypeService.getAll();
this.walletData.transactionTypeId = response?.find((type) => type.type == this.walletData.transactionType)?.id;
} catch (err) {
} finally {
this.appForm.isValid = true;
}
};
getSubscription = async (id) => {
try {
const response = await this.subscriptionService.get(id, {
embed: 'Wallet'
});
const wallet = this.appForm.getInput('wallet');
if (wallet) {
(wallet as AppDropdownElement).setItemValue(response.wallet);
}
response.wallet = response.walletId
response.endDate = dayjs(response.endDate).format('YYYY-MM-DD')
this.appForm.set(response);
} catch (err) {
}
}
getWallets = async (options): Promise<void> => {
try {
const response = await this.walletService.getAll(options);
return response;
} catch (err) {}
};
getTypes = async (options): Promise<void> => {
try {
const response = await this.transactionTypeService.getAll(options);
return response;
} catch (err) {}
};
getSubs = async (options): Promise<void> => {
try {
const response = await this.subscriptionTypeService.getAll(options);
return response;
} catch (err) {}
};
onSubmit = async (values): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const {
description: description,
wallet: walletId,
amount,
endDate,
} = values;
const endDateFormat = dayjs(endDate).utc(true).format();
const walletData = this.walletData;
const formData = {
description,
amount,
hasEnd: (this.hasEndCheck?.inp as HTMLInputElement)?.checked,
endDate: endDateFormat,
walletId: walletData && walletData.walletId ? walletData.walletId : walletId,
};
const response = await this.subscriptionService.put(this.walletData.id, formData);
if (response?.id) {
this.appMain.triggerTransactionUpdate();
this.appMain.pushToast('success', 'Subscription edited successfully!');
if (walletData.walletId) {
this.appMain?.closeModal();
} else {
this.routerService.goTo('/subscriptions', {
walletId: response.walletId,
});
}
}
} catch (err) {
this.errorMessage = 'Unable to edit subscription!';
this.update();
}
};
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
onCheck = () => {
this.appForm.update();
this.appForm.validate();
this.appForm.update();
};
renderForms = () => {
const renderInput = (type, name, label, rules, hide?, customAction?) => {
return html`<input-field
data-type="${type}"
data-name="${name}"
data-label="${label}"
data-targets="subscription-edit.inputs"
data-rules="${rules}"
data-custom-action="${customAction || ''}"
data-disabled="${hide}"
></input-field>`;
};
const renderNumericInput = (pattern, name, label, rules, hide?, customAction?) => {
if (hide) {
return html``;
}
return html`<input-field
data-type="number"
data-pattern="${pattern}"
data-name="${name}"
data-label="${label}"
data-targets="subscription-edit.inputs"
data-rules="${rules}"
custom-action="${customAction}"
></input-field>`;
};
const renderDropdown = (fetch, name, label, rules, hide?) => {
if (hide) {
return html``;
}
return html`<app-dropdown
data-name="${name}"
data-label="${label}"
data-targets="subscription-edit.inputs"
data-rules="${rules}"
data-fetch="${fetch}"
></app-dropdown>`;
};
return html`
<div slot="inputs">
${renderNumericInput('^d+(?:.d{1,2})?$', 'amount', 'Amount', 'required', false)}
${renderInput('text', 'description', 'Description', 'required')}
${renderInput('checkbox', 'hasEnd', 'Existing End Date', '', false, 'change:subscription-edit#onCheck')}
${renderInput(
'date',
'endDate',
'End date',
'required',
!(this.hasEndCheck?.inp as HTMLInputElement)?.checked
)}
${renderDropdown(
'subscription-edit#getWallets',
'wallet',
'Wallet',
'required',
this.walletData && this.walletData.walletId
)}
${this.errorMessage ? html`<div>${this.errorMessage}</div>` : html``}</template
>`;
};
render = (): TemplateResult => {
return html`
<app-form
data-custom="subscription-edit#onSubmit"
data-has-cancel="true"
data-target="subscription-edit.appForm"
data-render-input="subscription-edit#renderForms"
>
</app-form>
`;
};
}
export type { SubscriptionEditElement };

View File

@@ -33,6 +33,23 @@ class SubscriptionListElement extends BasePageElement {
this.pagination?.executeFetch();
};
subscriptionEdit = (id) => {
const _modal = this.appMain.appModal;
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal('subscription-edit', {
id: id
});
}
}
subscriptionEnd = (id) => {
if (confirm('Are you sure you want to end this subscription?')) {
this.subscriptionService.endSubscription(id);
}
}
renderSubscription = (item) => html`<tr class="col-subscription">
<td class="--left">${dayjs(item.lastTransactionDate).format("MMM DD 'YY")}</td>
<td class="--left">every ${item.customRange} ${item.rangeName}</td>
@@ -50,6 +67,10 @@ class SubscriptionListElement extends BasePageElement {
</span>
<span class="currency">(${item.currency ? item.currency : 'USD'})</span>
</td>
<td class="--left">
<span><button @click=${() => this.subscriptionEdit(item.id)}}>Edit</button></span>
<span><button @click=${() => this.subscriptionEnd(item.id)}}>End</button></span>
</td>
</tr>`;
getSubscriptions = async (options): Promise<any> => {

View File

@@ -1,9 +1,13 @@
import { AppService, BaseService } from 'core/services';
class SubscriptionService extends BaseService {
constructor(appService: AppService) {
constructor(public appService: AppService) {
super('/subscription', appService);
}
endSubscription = (id) => {
return this.appService.put(this.endpoint + `/end/${id || ''}`, null, null);
};
}
export default SubscriptionService;

View File

@@ -138,13 +138,14 @@ app-pagination {
grid-template-columns: repeat(6, 1fr);
}
&.col-subscription {
grid-template-columns: 1fr 2fr 10fr 1fr 2fr;
grid-template-columns: 1fr 2fr 10fr 1fr 2fr 1fr;
}
td,
th {
margin: 0 12px;
overflow: hidden; // Or flex might break
list-style: none;
align-self: center;
&.--left {
text-align: left;
}

View File

@@ -1207,22 +1207,22 @@
"@webassemblyjs/ast" "1.11.0"
"@xtuc/long" "4.2.2"
"@webpack-cli/configtest@^1.0.3":
version "1.0.3"
resolved "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.0.3.tgz"
integrity sha512-WQs0ep98FXX2XBAfQpRbY0Ma6ADw8JR6xoIkaIiJIzClGOMqVRvPCWqndTxf28DgFopWan0EKtHtg/5W1h0Zkw==
"@webpack-cli/configtest@^1.0.4":
version "1.0.4"
resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-1.0.4.tgz#f03ce6311c0883a83d04569e2c03c6238316d2aa"
integrity sha512-cs3XLy+UcxiP6bj0A6u7MLLuwdXJ1c3Dtc0RkKg+wiI1g/Ti1om8+/2hc2A2B60NbBNAbMgyBMHvyymWm/j4wQ==
"@webpack-cli/info@^1.2.4":
version "1.2.4"
resolved "https://registry.npmjs.org/@webpack-cli/info/-/info-1.2.4.tgz"
integrity sha512-ogE2T4+pLhTTPS/8MM3IjHn0IYplKM4HbVNMCWA9N4NrdPzunwenpCsqKEXyejMfRu6K8mhauIPYf8ZxWG5O6g==
"@webpack-cli/info@^1.3.0":
version "1.3.0"
resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-1.3.0.tgz#9d78a31101a960997a4acd41ffd9b9300627fe2b"
integrity sha512-ASiVB3t9LOKHs5DyVUcxpraBXDOKubYu/ihHhU+t1UPpxsivg6Od2E2qU4gJCekfEddzRBzHhzA/Acyw/mlK/w==
dependencies:
envinfo "^7.7.3"
"@webpack-cli/serve@^1.4.0":
version "1.4.0"
resolved "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.4.0.tgz"
integrity sha512-xgT/HqJ+uLWGX+Mzufusl3cgjAcnqYYskaB7o0vRcwOEfuu6hMzSILQpnIzFMGsTaeaX4Nnekl+6fadLbl1/Vg==
"@webpack-cli/serve@^1.5.1":
version "1.5.1"
resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-1.5.1.tgz#b5fde2f0f79c1e120307c415a4c1d5eb15a6f278"
integrity sha512-4vSVUiOPJLmr45S8rMGy7WDvpWxfFxfP/Qx/cxZFCfvoypTYpPPL1X8VIZMe0WTA+Jr7blUxwUSEZNkjoMTgSw==
"@xtuc/ieee754@^1.2.0":
version "1.2.0"
@@ -6595,15 +6595,15 @@ wbuf@^1.1.0, wbuf@^1.7.3:
dependencies:
minimalistic-assert "^1.0.0"
webpack-cli@^4.7.0:
version "4.7.0"
resolved "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.7.0.tgz"
integrity sha512-7bKr9182/sGfjFm+xdZSwgQuFjgEcy0iCTIBxRUeteJ2Kr8/Wz0qNJX+jw60LU36jApt4nmMkep6+W5AKhok6g==
webpack-cli@^4.7.2:
version "4.7.2"
resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-4.7.2.tgz#a718db600de6d3906a4357e059ae584a89f4c1a5"
integrity sha512-mEoLmnmOIZQNiRl0ebnjzQ74Hk0iKS5SiEEnpq3dRezoyR3yPaeQZCMCe+db4524pj1Pd5ghZXjT41KLzIhSLw==
dependencies:
"@discoveryjs/json-ext" "^0.5.0"
"@webpack-cli/configtest" "^1.0.3"
"@webpack-cli/info" "^1.2.4"
"@webpack-cli/serve" "^1.4.0"
"@webpack-cli/configtest" "^1.0.4"
"@webpack-cli/info" "^1.3.0"
"@webpack-cli/serve" "^1.5.1"
colorette "^1.2.1"
commander "^7.0.0"
execa "^5.0.0"