connect-admin/src/app/pages/community-info/profile/edit-community/edit-community.component.ts

325 lines
14 KiB
TypeScript

import {Component} from "@angular/core";
import {UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {EnvProperties} from "../../../../openaireLibrary/utils/properties/env-properties";
import {properties} from "../../../../../environments/environment";
import {CommunityInfo} from "../../../../openaireLibrary/connect/community/communityInfo";
import {Session, User} from "../../../../openaireLibrary/login/utils/helper.class";
import {CommunityService} from "../../../../openaireLibrary/connect/community/community.service";
import {UtilitiesService} from "../../../../openaireLibrary/services/utilities.service";
import {UserManagementService} from "../../../../openaireLibrary/services/user-management.service";
import {StringUtils} from "../../../../openaireLibrary/utils/string-utils.class";
import {Subscription} from "rxjs";
import {Option} from "../../../../openaireLibrary/sharedComponents/input/input.component";
import {NotificationHandler} from "../../../../openaireLibrary/utils/notification-handler";
import {ClearCacheService} from "../../../../openaireLibrary/services/clear-cache.service";
@Component({
selector: 'edit-community',
template: `
<form *ngIf="communityFb" [formGroup]="communityFb" class="uk-margin-xlarge-bottom">
<div class="uk-grid uk-grid-large" uk-grid>
<div class="uk-width-1-2@m">
<div input id="name" [formInput]="communityFb.get('name')"
placeholder="Name of the community profile."></div>
</div>
<div class="uk-width-1-2@m">
<div input [formInput]="communityFb.get('shortName')"
placeholder="Short name of the community."></div>
</div>
<div class="uk-width-1-1">
<div class="uk-text-bold uk-margin-bottom uk-form-hint">Description of the community</div>
<ckeditor [readonly]="false"
debounce="500"
[formControl]="communityFb.get('description')"
[config]="{ extraAllowedContent: '* [uk-*](*) ; span', disallowedContent: 'script; *[on*]',
removeButtons: 'Save,NewPage,DocProps,Preview,Print,' +
'Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,' +
'CreateDiv,Flash,PageBreak,' +
'Subscript,Superscript,Anchor,Smiley,Iframe,Styles,Font,About,Language',
extraPlugins: 'divarea'}">
</ckeditor>
</div>
<div class="uk-width-1-1">
<input #file id="photo" type="file" class="uk-hidden" (change)="fileChangeEvent($event)"/>
<div *ngIf="!communityFb.get('isUpload').value" class="uk-grid uk-grid-column-large" uk-grid>
<div class="uk-margin-xsmall-top uk-width-auto@l uk-width-1-1">
<div class="uk-grid uk-grid-column-large uk-flex-middle" uk-grid>
<div class="uk-width-auto@l uk-width-1-1 uk-flex uk-flex-center">
<button class="uk-button uk-button-primary uk-flex uk-flex-middle uk-flex-wrap"
(click)="file.click()">
<icon name="cloud_upload" [flex]="true"></icon>
<span class="uk-margin-small-left">Upload a file</span>
</button>
</div>
<div class="uk-text-center uk-text-bold uk-width-expand">
OR
</div>
</div>
</div>
<div input class="uk-width-expand" type="logoURL" [placeholder]="'Link to the logo'"
[formInput]="communityFb.get('logoUrl')"></div>
</div>
<div *ngIf="communityFb.get('isUpload').value" class="uk-width-1-1 uk-flex uk-flex-middle">
<div class="uk-card uk-card-default uk-text-center uk-border-circle">
<img class="uk-position-center uk-blend-multiply" [src]="photo">
</div>
<div class="uk-margin-left">
<button (click)="remove()" class="uk-button-danger uk-icon-button uk-icon-button-small">
<icon [flex]="true" ratio="0.8" name="delete"></icon>
</button>
</div>
<div class="uk-margin-small-left">
<button class="uk-button-secondary uk-icon-button uk-icon-button-small" (click)="file.click()">
<icon [flex]="true" ratio="0.8" name="edit"></icon>
</button>
</div>
</div>
<!-- Full width error message -->
<div *ngIf="uploadError" class="uk-text-danger uk-margin-small-top uk-width-1-1">{{uploadError}}</div>
</div>
<div class="uk-width-1-3@m">
<div input [formInput]="communityFb.get('status')"
placeholder="Visibility status for your community's profile."
[options]="statuses" type="select"></div>
</div>
<div class="uk-width-1-3@m">
<div input [formInput]="communityFb.get('claim')"
placeholder="Who can create links for your community"
[options]="claimOptions" type="select"></div>
</div>
<div class="uk-width-1-3@m">
<div input [formInput]="communityFb.get('membership')"
placeholder="Who can join"
[options]="membershipOptions" type="select"></div>
</div>
</div>
</form>
`,
styleUrls: ['edit-community.component.less']
})
export class EditCommunityComponent {
public communityFb: UntypedFormGroup;
public statuses: Option[] = [
// {label: 'Visible', value: 'all'},
{label: 'Visible', value: 'PUBLIC'},
// {label: 'Visible to managers', value: 'manager'},
{label: 'Visible to managers', value: 'RESTRICTED'},
{label: 'Hidden', value: 'hidden'}
]
public claimOptions: Option[] = [
{label: 'Logged in users', value: 'all'},
{label: 'Members only', value: 'membersOnly'},
{label: 'Managers only', value: 'managersOnly'}
]
public membershipOptions: Option[] = [
{label: 'Anyone can join', value: 'open'},
{label: 'By invitation', value: 'byInvitation'}
]
public community: CommunityInfo;
public isNew: boolean;
public properties: EnvProperties = properties
;
private subscriptions: any[] = [];
/**
* Photo upload
* */
public file: File;
public photo: string | ArrayBuffer;
public uploadError: string;
public deleteCurrentPhoto: boolean = false;
private maxsize: number = 200 * 1024;
user: User;
constructor(private fb: UntypedFormBuilder,
private communityService: CommunityService,
private utilsService: UtilitiesService,
private userManagementService: UserManagementService,
private _clearCacheService: ClearCacheService) {
}
ngOnDestroy() {
this.reset();
}
public init(community: CommunityInfo, isNew: boolean = false) {
this.reset();
this.deleteCurrentPhoto = false;
this.community = community;
this.isNew = isNew;
this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
this.user = user;
this.communityFb = this.fb.group({
communityId: this.fb.control(this.community.communityId),
name: this.fb.control(this.community.title, Validators.required),
shortName: this.fb.control(this.community.shortTitle, Validators.required),
description: this.fb.control(this.community.description),
status: this.fb.control(this.community.status),
claim: this.fb.control(this.community.claim),
membership: this.fb.control(this.community.membership),
managers: this.fb.control(this.community.managers),
isUpload: this.fb.control(this.community.isUpload),
logoUrl: this.fb.control(this.community.logoUrl)
});
if (this.community.isUpload) {
this.communityFb.get('logoUrl').clearValidators();
this.communityFb.get('logoUrl').updateValueAndValidity();
} else {
this.communityFb.get('logoUrl').setValidators([StringUtils.urlValidator()]);
this.communityFb.get('logoUrl').updateValueAndValidity();
}
this.subscriptions.push(this.communityFb.get('isUpload').valueChanges.subscribe(value => {
if (value == true) {
this.communityFb.get('logoUrl').clearValidators();
this.communityFb.updateValueAndValidity();
} else {
this.communityFb.get('logoUrl').setValidators([StringUtils.urlValidator()]);
this.communityFb.updateValueAndValidity();
}
}));
this.initPhoto();
if (!isNew) {
if (!this.isAdmin) {
setTimeout(() => {
this.communityFb.get('shortName').disable();
}, 0);
}
}
}
));
}
public get isAdmin() {
return Session.isPortalAdministrator(this.user);
}
public get disabled(): boolean {
return (this.communityFb && this.communityFb.invalid) ||
(this.communityFb && this.communityFb.pristine && !this.isNew && !this.file) ||
(this.uploadError && this.uploadError.length > 0);
}
public get dirty(): boolean {
return this.communityFb && this.communityFb.dirty;
}
reset() {
this.uploadError = null;
this.communityFb = null;
this.subscriptions.forEach(subscription => {
if (subscription instanceof Subscription) {
subscription.unsubscribe();
}
});
}
public save(callback: Function, errorCallback: Function = null) {
if (this.file) {
this.subscriptions.push(this.utilsService.uploadPhoto(this.properties.utilsService + "/upload/community/" + encodeURIComponent(this.community.communityId), this.file).subscribe(res => {
this.deletePhoto();
this.communityFb.get('logoUrl').setValue(res.filename);
this.removePhoto();
this.saveCommunity(callback, errorCallback);
}, error => {
this.uploadError = "An error has been occurred during upload your image. Try again later";
this.saveCommunity(callback, errorCallback);
}));
} else if (this.deleteCurrentPhoto) {
this.deletePhoto();
this.saveCommunity(callback, errorCallback);
} else {
this.saveCommunity(callback, errorCallback);
}
}
public saveCommunity(callback: Function, errorCallback: Function = null) {
if (this.isNew) {
this.removePhoto();
this.subscriptions.push(this.communityService.updateCommunity(
this.properties.communityAPI + this.community.communityId, this.communityFb.getRawValue()).subscribe(() => {
this._clearCacheService.clearCache("Community saved");
this._clearCacheService.purgeBrowserCache("Community saved", this.community.communityId);
this.communityService.getCommunity(this.community.communityId, true).subscribe(community => {
NotificationHandler.rise(community.shortTitle + ' has been <b>successfully created</b>');
callback(community);
});
}, error => {
NotificationHandler.rise('An error has occurred. Please try again later', 'danger');
if (errorCallback) {
errorCallback(error)
}
}));
} else {
this.subscriptions.push(this.communityService.updateCommunity(this.properties.communityAPI + this.community.communityId, this.communityFb.getRawValue()).subscribe(() => {
this._clearCacheService.clearCache("Community updated");
this._clearCacheService.purgeBrowserCache("Community updated", this.community.communityId);
this.communityService.getCommunity(this.community.communityId, true).subscribe(community => {
NotificationHandler.rise(community.shortTitle + ' has been <b>successfully saved</b>');
callback(community);
});
}, error => {
NotificationHandler.rise('An error has occurred. Please try again later', 'danger');
}));
}
}
fileChangeEvent(event) {
if (event.target.files && event.target.files[0]) {
this.file = event.target.files[0];
if (this.file.type !== 'image/png' && this.file.type !== 'image/jpeg') {
this.uploadError = 'You must choose a file with type: image/png or image/jpeg!';
this.communityFb.get('isUpload').setValue(false);
this.communityFb.get('isUpload').markAsDirty();
this.removePhoto();
} else if (this.file.size > this.maxsize) {
this.uploadError = 'File exceeds size\'s limit! Maximum resolution is 256x256 pixels.';
this.communityFb.get('isUpload').setValue(false);
this.communityFb.get('isUpload').markAsDirty();
this.removePhoto();
} else {
this.uploadError = null;
const reader = new FileReader();
reader.readAsDataURL(this.file);
reader.onload = () => {
this.photo = reader.result;
this.communityFb.get('isUpload').setValue(true);
this.communityFb.get('isUpload').markAsDirty();
};
}
}
}
initPhoto() {
if (this.communityFb.value.isUpload) {
this.photo = this.properties.utilsService + "/download/" + this.communityFb.get('logoUrl').value;
}
}
removePhoto() {
if (this.file) {
if (typeof document != 'undefined') {
(<HTMLInputElement>document.getElementById("photo")).value = "";
}
this.initPhoto();
this.file = null;
}
}
remove() {
this.communityFb.get('isUpload').setValue(false);
this.communityFb.get('isUpload').markAsDirty();
this.removePhoto();
this.communityFb.get('logoUrl').setValue(null);
if (this.community.isUpload) {
this.deleteCurrentPhoto = true;
}
}
public deletePhoto() {
if (this.community.logoUrl && this.community.isUpload) {
this.subscriptions.push(this.utilsService.deletePhoto(this.properties.utilsService + '/delete/community/' +
encodeURIComponent(this.community.communityId) + '/' + this.community.logoUrl).subscribe());
}
}
}