File

src/app/modules/workspace/components/draft/draft.component.ts

Description

The draft component search for all the drafts

Extends

WorkSpace

Implements

OnInit AfterViewInit

Metadata

Index

Properties
Methods

Constructor

constructor(modalService: SuiModalService, searchService: SearchService, workSpaceService: WorkSpaceService, frameworkService: FrameworkService, paginationService: PaginationService, activatedRoute: ActivatedRoute, route: Router, userService: UserService, toasterService: ToasterService, resourceService: ResourceService, config: ConfigService, navigationhelperService: NavigationHelperService)

Constructor to create injected service(s) object Default method of Draft Component class

Parameters :
Name Type Optional Description
modalService SuiModalService No
searchService SearchService No
workSpaceService WorkSpaceService No
frameworkService FrameworkService No
paginationService PaginationService No

Reference of PaginationService

activatedRoute ActivatedRoute No

Reference of ActivatedRoute

route Router No

Reference of Router

userService UserService No
toasterService ToasterService No
resourceService ResourceService No
config ConfigService No

Reference of ConfigService

navigationhelperService NavigationHelperService No

Methods

contentClick
contentClick(param)

This method launch the content editior

Parameters :
Name Optional
param No
Returns : void
Public deleteConfirmModal
deleteConfirmModal(contentIds)
Parameters :
Name Optional
contentIds No
Returns : void
fetchDrafts
fetchDrafts(limit: number, pageNumber: number, bothParams?: object)

This method sets the make an api call to get all drafts with page No and offset

Parameters :
Name Type Optional
limit number No
pageNumber number No
bothParams object Yes
Returns : void
inview
inview(event)

get inview Data

Parameters :
Name Optional
event No
Returns : void
navigateToPage
navigateToPage(page: number)

This method helps to navigate to different pages. If page number is less than 1 or page number is greater than total number of pages is less which is not possible, then it returns.

Parameters :
Name Type Optional Description
page number No

Variable to know which page has been clicked

Example :
navigateToPage(1)
Returns : undefined | void
ngAfterViewInit
ngAfterViewInit()
Returns : void
ngOnInit
ngOnInit()
Returns : void
Public onCloseLockInfoPopup
onCloseLockInfoPopup()
Returns : void
delete
delete(contentIds)
Inherited from WorkSpace
Defined in WorkSpace:111

Delete Api call .

Parameters :
Name Optional
contentIds No
Returns : any
getBatches
getBatches(searchParams)
Inherited from WorkSpace
Defined in WorkSpace:128

Batchlist Api call

Parameters :
Name Optional
searchParams No
Returns : any
getChannelDetails
getChannelDetails(channelId)
Inherited from WorkSpace
Defined in WorkSpace:164

get channel Api call

Parameters :
Name Optional
channelId No
Returns : any
getLinkedCollections
getLinkedCollections(contentId: ContentIDParam)
Inherited from WorkSpace
Defined in WorkSpace:157

search collection Api call

Parameters :
Name Type Optional
contentId ContentIDParam No
Returns : any
handleContentLockError
handleContentLockError(errObj)
Inherited from WorkSpace
Defined in WorkSpace:142

handle content lock api error

Parameters :
Name Optional
errObj No
Returns : string
lockContent
lockContent(content)
Inherited from WorkSpace
Defined in WorkSpace:97

this call will prepare reuest object and call lock api

Parameters :
Name Optional
content No
Returns : any
removeContent
removeContent(contentList, requestData)
Inherited from WorkSpace
Defined in WorkSpace:120

Method to remove content localcaly

Parameters :
Name Optional
contentList No
requestData No
Returns : any
search
search(searchParams)
Inherited from WorkSpace
Defined in WorkSpace:33

Search Api call

Parameters :
Name Optional
searchParams No
Returns : any
searchContentWithLockStatus
searchContentWithLockStatus(searchParams)
Inherited from WorkSpace
Defined in WorkSpace:40

Search Api call and returns contents with lock status of each one

Parameters :
Name Optional
searchParams No
Returns : any
UserList
UserList(searchParams)
Inherited from WorkSpace
Defined in WorkSpace:135

userList Api call

Parameters :
Name Optional
searchParams No
Returns : any

Properties

Private activatedRoute
Type : ActivatedRoute

To send activatedRoute.snapshot to router navigation service for redirection to draft component

Public config
Type : ConfigService

To get url, app configs

contentIds
Type : string

Contains unique contentIds id

draftList
Type : Array<ICard>
Default value : []

Contains list of published course(s) of logged-in user

Public frameworkService
Type : FrameworkService
inviewLogs
Type : []
Default value : []

inviewLogs

Public isQuestionSetEnabled
Type : boolean

To check if questionSet enabled

loaderMessage
Type : ILoaderMessage

loader message

lockInfoPopupContent
Type : object
Default value : {headerTitle: ''}

Contains static data of popup like header label , submit button label etc

lockPopupData
Type : object

lock popup data for locked contents

Public modalService
Type : SuiModalService
Public modalTemplate
Type : ModalTemplate<literal type | string | string>
Decorators :
@ViewChild('modalTemplate')
Public navigationhelperService
Type : NavigationHelperService
noResult
Default value : false

To show / hide no result message when no result found

noResultMessage
Type : INoResultMessage

no result message

pageLimit
Type : number

Contains page limit of inbox list

pageNumber
Type : number
Default value : 1

Current page number of inbox list

pager
Type : IPagination

Contains returned object of the pagination service which is needed to show the pagination on inbox view

Private paginationService
Type : PaginationService

For showing pagination on draft list

query
Type : string
queryParams
Type : object
Public resourceService
Type : ResourceService

To call resource service which helps to use language constant

route
Type : Router

To navigate to other pages

Public searchService
Type : SearchService
Inherited from WorkSpace
Defined in WorkSpace:163
showError
Default value : false

To show / hide error

showLoader
Default value : true

To show / hide loader

showLockedContentModal
Default value : false

To show content locked modal

sort
Type : object
state
Type : string

state for content editior

telemetryImpression
Type : IImpressionEventInput

telemetryImpression

Private telemetryInteractObject
Type : IInteractEventObject
Private toasterService
Type : ToasterService

To show toaster(error, success etc) after any API calls

totalCount
Type : Number

totalCount of the list

Public workSpaceService
Type : WorkSpaceService
Inherited from WorkSpace
Defined in WorkSpace:164
Public userService
Type : UserService
Inherited from WorkSpace
Defined in WorkSpace:26
import { debounceTime, map } from 'rxjs/operators';
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import {combineLatest } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { WorkSpace } from '../../classes/workspace';
import { SearchService, UserService, FrameworkService } from '@sunbird/core';
import {
    ServerResponse, PaginationService, ConfigService, ToasterService, IPagination,
    ResourceService, ILoaderMessage, INoResultMessage, ICard, NavigationHelperService
} from '@sunbird/shared';
import { WorkSpaceService } from '../../services';
import * as _ from 'lodash-es';
import { SuiModalService, TemplateModalConfig, ModalTemplate } from 'ng2-semantic-ui-v9';
import { IImpressionEventInput, IInteractEventObject } from '@sunbird/telemetry';

/**
 * The draft component search for all the drafts
*/

@Component({
    selector: 'app-draft',
    templateUrl: './draft.component.html'
})
export class DraftComponent extends WorkSpace implements OnInit, AfterViewInit {

    @ViewChild('modalTemplate')
    public modalTemplate: ModalTemplate<{ data: string }, string, string>;
    /**
     * state for content editior
    */
    state: string;

    /**
     * To navigate to other pages
     */
    route: Router;

    /**
     * To send activatedRoute.snapshot to router navigation
     * service for redirection to draft  component
    */
    private activatedRoute: ActivatedRoute;

    /**
     * Contains unique contentIds id
    */
    contentIds: string;

    /**
     * Contains static data of popup like header label , submit button label etc
    */
    lockInfoPopupContent: object = {headerTitle: ''};

    /**
     * Contains list of published course(s) of logged-in user
    */
    draftList: Array<ICard> = [];

    /**
     * To show / hide loader
    */
    showLoader = true;

    /**
     * lock popup data for locked contents
    */
    lockPopupData: object;

    /**
     * loader message
    */
    loaderMessage: ILoaderMessage;

    /**
     * To show / hide no result message when no result found
    */
    noResult = false;

    /**
     * To show / hide error
    */
    showError = false;

    /**
     * To show content locked modal
    */
    showLockedContentModal = false;

    /**
     * no result  message
    */
    noResultMessage: INoResultMessage;

    /**
      * For showing pagination on draft list
    */
    private paginationService: PaginationService;

    /**
    * To get url, app configs
    */
    public config: ConfigService;
    /**
       * Contains page limit of inbox list
    */
    pageLimit: number;

    /**
      * Current page number of inbox list
    */
    pageNumber = 1;

    /**
      * totalCount of the list
    */
    totalCount: Number;

    /**
      * Contains returned object of the pagination service
    * which is needed to show the pagination on inbox view
      */
    pager: IPagination;

    /**
    * To show toaster(error, success etc) after any API calls
    */
    private toasterService: ToasterService;


    /**
    * To call resource service which helps to use language constant
   */
    public resourceService: ResourceService;

    private telemetryInteractObject: IInteractEventObject ;
    /**
     * inviewLogs
    */
    inviewLogs = [];
    /**
     * telemetryImpression
    */
    telemetryImpression: IImpressionEventInput;

    queryParams: object;

    query: string;
    sort: object;
    /**
      * To check if questionSet enabled
     */
     public isQuestionSetEnabled: boolean;
    /**
      * Constructor to create injected service(s) object
      Default method of Draft Component class
      * @param {SearchService} SearchService Reference of SearchService
      * @param {UserService} UserService Reference of UserService
      * @param {Router} route Reference of Router
      * @param {PaginationService} paginationService Reference of PaginationService
      * @param {ActivatedRoute} activatedRoute Reference of ActivatedRoute
      * @param {ConfigService} config Reference of ConfigService
    */
    constructor(public modalService: SuiModalService, public searchService: SearchService,
        public workSpaceService: WorkSpaceService,
        public frameworkService: FrameworkService,
        paginationService: PaginationService,
        activatedRoute: ActivatedRoute,
        route: Router, userService: UserService,
        toasterService: ToasterService, resourceService: ResourceService,
        config: ConfigService, public navigationhelperService: NavigationHelperService) {
        super(searchService, workSpaceService, userService);
        this.paginationService = paginationService;
        this.route = route;
        this.activatedRoute = activatedRoute;
        this.toasterService = toasterService;
        this.resourceService = resourceService;
        this.config = config;
        this.state = 'draft';
        this.loaderMessage = {
            'loaderMessage': this.resourceService.messages.stmsg.m0011,
        };
    }
    ngOnInit() {
        this.workSpaceService.questionSetEnabled$.subscribe(
            (response: any) => {
              this.isQuestionSetEnabled = response?.questionSetEnablement;
            }
        );
        combineLatest(
            this.activatedRoute.params,
            this.activatedRoute.queryParams).pipe(
              debounceTime(100),
              map(([params, queryParams]) => ({ params, queryParams })
            ))
            .subscribe(bothParams => {
              if (bothParams.params.pageNumber) {
                this.pageNumber = Number(bothParams.params.pageNumber);
              }
              this.queryParams = bothParams.queryParams;
              this.query = this.queryParams['query'];
              this.fetchDrafts(this.config.appConfig.WORKSPACE.PAGE_LIMIT, this.pageNumber, bothParams);
            });
    }
    /**
     * This method sets the make an api call to get all drafts with page No and offset
     */
    fetchDrafts(limit: number, pageNumber: number, bothParams?: object) {
        this.showLoader = true;
        this.pageNumber = pageNumber;
        this.pageLimit = limit;
        this.draftList = [];
        this.totalCount = 0;
        this.noResult = false;
        const primaryCategories = _.compact(_.concat(this.frameworkService['_channelData'].contentPrimaryCategories, this.frameworkService['_channelData'].collectionPrimaryCategories));
        if (bothParams['queryParams'].sort_by) {
            const sort_by = bothParams['queryParams'].sort_by;
            const sortType = bothParams['queryParams'].sortType;
            this.sort = {
              [sort_by]: _.toString(sortType)
            };
          } else {
            this.sort = { lastUpdatedOn: this.config.appConfig.WORKSPACE.lastUpdatedOn };
          }
        const searchParams = {
            filters: {
                status: ['Draft', 'FlagDraft'],
                createdBy: this.userService.userid,
                // tslint:disable-next-line:max-line-length
                primaryCategory: _.get(bothParams, 'queryParams.primaryCategory') || (!_.isEmpty(primaryCategories) ? primaryCategories : this.config.appConfig.WORKSPACE.primaryCategory),
                board: bothParams['queryParams'].board,
                subject: bothParams['queryParams'].subject,
                medium: bothParams['queryParams'].medium,
                gradeLevel: bothParams['queryParams'].gradeLevel
            },
            limit: this.pageLimit,
            offset: (this.pageNumber - 1) * (this.pageLimit),
            query: _.toString(bothParams['queryParams'].query),
            sort_by: this.sort
        };
        /**
         * mimeType is not passed when isQuestionSetEnabled is set to true to get QuestionSets along with content
         */
        if(!this.isQuestionSetEnabled) {
            searchParams.filters["mimeType"] = this.config.appConfig.WORKSPACE.mimeType;
        }
        this.searchContentWithLockStatus(searchParams).subscribe(
            (data: ServerResponse) => {
                const allContent= this.workSpaceService.getAllContent(data, this.isQuestionSetEnabled);
                if (allContent.length > 0) {
                    this.totalCount = data.result.count;
                    this.pager = this.paginationService.getPager(data.result.count, this.pageNumber, this.pageLimit);
                    const constantData = this.config.appConfig.WORKSPACE.Draft.constantData;
                    const metaData = this.config.appConfig.WORKSPACE.Draft.metaData;
                    const dynamicFields = this.config.appConfig.WORKSPACE.Draft.dynamicFields;
                    this.draftList = this.workSpaceService.getDataForCard(allContent, constantData, dynamicFields, metaData);
                    this.showLoader = false;
                } else {
                    this.showError = false;
                    this.noResult = true;
                    this.showLoader = false;
                    this.noResultMessage = {
                        'messageText': 'messages.stmsg.m0125'
                    };
                }
            },
            (err: ServerResponse) => {
                this.showLoader = false;
                this.noResult = false;
                this.showError = true;
                this.toasterService.error(this.resourceService.messages.fmsg.m0006);
            }
        );
    }
    /**
     * This method launch the content editior
    */
    contentClick(param) {
        if (_.size(param.data.lockInfo) && this.userService.userid !== param.data.lockInfo.createdBy) {
            this.lockPopupData = param.data;
            this.showLockedContentModal = true;
        } else {
            if (param.action.eventName === 'delete') {
                this.telemetryInteractObject = {
                    id: param.data.metaData.identifier,
                    type: param.data.metaData.contentType,
                    ver: '1.0'
                };
                this.deleteConfirmModal(param.data.metaData.identifier);
            } else {
                this.workSpaceService.navigateToContent(param.data.metaData, this.state);
            }
        }
    }

    public onCloseLockInfoPopup () {
        this.showLockedContentModal = false;
    }

    public deleteConfirmModal(contentIds) {
        const config = new TemplateModalConfig<{ data: string }, string, string>(this.modalTemplate);
        config.isClosable = false;
        config.size = 'small';
        config.transitionDuration = 0;
        config.mustScroll = true;
        setTimeout(() => {
            let element = document.getElementsByTagName('sui-modal');
            if(element && element.length > 0)
              element[0].className = 'sb-modal';
          }, 10);
        this.modalService
            .open(config)
            .onApprove(result => {
                this.showLoader = true;
                this.loaderMessage = {
                    'loaderMessage': this.resourceService.messages.stmsg.m0034,
                };
                this.delete(contentIds).subscribe(
                    (data: ServerResponse) => {
                        this.showLoader = false;
                        this.draftList = this.removeContent(this.draftList, contentIds);
                        // after delete if current page results are zero
                        if (this.draftList.length === 0) {
                            this.fetchDrafts(this.config.appConfig.WORKSPACE.PAGE_LIMIT, this.pageNumber);
                        }
                        this.toasterService.success(this.resourceService.messages.smsg.m0006);
                    },
                    (err: ServerResponse) => {
                        this.showLoader = false;
                        this.toasterService.error(this.resourceService.messages.fmsg.m0022);
                    }
                );
            })
            .onDeny(result => {
            });
    }

    /**
   * This method helps to navigate to different pages.
   * If page number is less than 1 or page number is greater than total number
   * of pages is less which is not possible, then it returns.
     *
     * @param {number} page Variable to know which page has been clicked
     *
     * @example navigateToPage(1)
     */
    navigateToPage(page: number): undefined | void {
        if (page < 1 || page > this.pager.totalPages) {
            return;
        }
        this.pageNumber = page;
        this.route.navigate(['workspace/content/draft', this.pageNumber], { queryParams: this.queryParams });
    }

    ngAfterViewInit () {
        setTimeout(() => {
            this.telemetryImpression = {
                context: {
                    env: this.activatedRoute.snapshot.data.telemetry.env
                },
                edata: {
                    type: this.activatedRoute.snapshot.data.telemetry.type,
                    pageid: this.activatedRoute.snapshot.data.telemetry.pageid,
                    uri: this.activatedRoute.snapshot.data.telemetry.uri + '/' + this.activatedRoute.snapshot.params.pageNumber,
                    visits: this.inviewLogs,
                    duration: this.navigationhelperService.getPageLoadTime()
                }
            };
            this.inview({ inview: [] });
        });
    }
    /**
    * get inview  Data
    */
    inview(event) {
        _.forEach(event.inview, (inview, key) => {
            const obj = _.find(this.inviewLogs, (o) => {
                return o.objid === inview.data.metaData.identifier;
            });
            if (obj === undefined) {
                this.inviewLogs.push({
                    objid: inview.data.metaData.identifier,
                    objtype: inview.data.metaData.contentType,
                    index: inview.id
                });
            }
        });
        this.telemetryImpression.edata.visits = this.inviewLogs;
        this.telemetryImpression.edata.subtype = 'pageexit';
        this.telemetryImpression = Object.assign({}, this.telemetryImpression);
    }
}
<app-workspace-content-filter ></app-workspace-content-filter>
<!-- Loader -->
<div class="twelve wide column mt-20" *ngIf="showLoader">
  <app-loader [data] = "loaderMessage" ></app-loader>
</div>

<div class="ui grid" *ngIf="!showLoader">
  <div class="twelve wide column" [appTelemetryImpression]="telemetryImpression">
    <div class="ui stackable three column grid" [throttle]="[1000]" [trigger]="draftList">
      <div *ngFor="let content of draftList;trackBy:identifier;let i = index;" [id]="i" [data]="content" class="column py-5 pl-10">
        <app-card-creation [data]="content" (clickEvent)="contentClick($event)"></app-card-creation>
      </div>
    </div>
   <div *ngIf="noResult">
      <app-no-result [data]="noResultMessage"></app-no-result>
    </div>
  </div>
</div>
<div class="ui grid">
  <div class="two wide column"></div>
  <div class="ten wide column pt-0">
    <div class="pb-10" *ngIf="draftList && totalCount > config.appConfig.WORKSPACE.PAGE_LIMIT && !showLoader && !showError">
      <div class="ui pagination menu mt-10 right-floated pt-0" *ngIf="pager.pages.length ">
        <a [ngClass]="{disabled:pager.currentPage===1 }" class="item " tabindex="0" (click)="navigateToPage(1) ">First</a>
        <a [ngClass]="{disabled:pager.currentPage===1 }" class="item " tabindex="0" (click)="navigateToPage(pager.currentPage - 1)">Previous</a>
        <a *ngFor="let page of pager.pages" [ngClass]="{active:pager.currentPage===page}" tabindex="0" (click)="navigateToPage(page)" class="item">{{page}}</a>
        <a [ngClass]="{disabled:pager.currentPage=== pager.totalPages}" tabindex="0" (click)="navigateToPage(pager.currentPage + 1)" class="item">Next</a>
        <a [ngClass]="{disabled:pager.currentPage=== pager.totalPages}" tabindex="0" (click)="navigateToPage(pager.totalPages)" class="item ">Last</a>
      </div>
    </div>
  </div>
</div>

<ng-template let-context let-modal="modal" #modalTemplate>
  <div class="sb-modal sb-error">
    <div class="ui modal visible active small">
      <i class="icon close" (click)="modal.deny('denied')" tabindex="0"></i>

      <!--Header-->
      <div class="sb-modal-header">
        {{resourceService?.frmelmnts?.lbl?.deletecontent}}
      </div>
      <!--/Header-->

      <!--Content-->
      <div class="sb-modal-content">
        <p>{{resourceService?.frmelmnts?.lbl?.deleteconfirm}}</p>
      </div>
      <!--/Content-->

      <!--Actions-->
      <div class="sb-modal-actions">
        <button 
          class="sb-btn sb-btn-normal sb-btn-error" 
          tabindex="0" (click)="modal.approve('approved')" 
          autofocus
          appTelemetryInteract [telemetryInteractObject]="telemetryInteractObject" [telemetryInteractEdata]="{id:'yes' , type:'click' , pageid:'draft'}"
        >
          {{resourceService?.frmelmnts?.btn?.yes}}
        </button>
        <button 
          class="sb-btn sb-btn-normal sb-btn-outline-error" 
          tabindex="0" (click)="modal.deny('denied')"
          appTelemetryInteract [telemetryInteractObject]="telemetryInteractObject" [telemetryInteractEdata]="{id:'no' , type:'click' , pageid:'draft'}"
        >
          {{resourceService?.frmelmnts?.btn?.no}}
        </button>
      </div>
      <!--/Actions-->

    </div>
  </div>
</ng-template>

<app-contentlock-info-popup [content]="lockPopupData" (closeEvent)="onCloseLockInfoPopup($event)" *ngIf="showLockedContentModal"></app-contentlock-info-popup>
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""