Integrating Event Roles API in Open Event Frontend

The Eventyay system supports different type of roles for an event like Attendee, organizer, co-organizer, track-organizer, moderator and the registrar. Every role has certain set of permissions such as Create, Read, Update, Delete. The Admin of the system is allowed to change the permissions for any role. The interface for updating the even role permissions was already available on the server but was not integrated on the frontend. The system is now integrated with the API and allows admin to change event role permission for any role.

Adding model for event role permissions

The model for event role permissions is added to the models directory. The model contains the attributes like canDelete, canUpdate, canCreate, canRead and the relationship with event role and the service.

export default ModelBase.extend({
 canDelete : attr('boolean'),
 canUpdate : attr('boolean'),
 canCreate : attr('boolean'),
 canRead   : attr('boolean'),

 role        : belongsTo('role'),
 service     : belongsTo('service'),
 serviceName : computed.alias('service.name')
});

The above defined model ensures that every permission belongs to a role and service. An alias is declared in the model using the computed property which is later used in the controller to sort the permissions according to service name in lexicographical order.

Adding route for event roles

The route for event role is created which contains model returning an object containing the list of roles, services and permissions. The model is defined as async so that the execution is paused while fetching the data from the store by adding the await expression.

export default Route.extend({
 titleToken() {
   return this.get('l10n').t('Event Roles');
 },
 async model() {
   return {
     roles       : ['Attendee', 'Co-organizer', 'Moderator', 'Organizer', 'Track Organizer', 'Registrar'],
     services    : await this.get('store').query('service', {}),
     permissions : await this.get('store').query('event-role-permission', { 'page[size]': 30 })
   };
 }
});

The route created above queries the data for roles, services and permissions which is later used by the template for rendering of the data obtained.

Adding controller for event roles

The controller for event roles is added to the controllers/admin/permissions directory. The computed property is used to sort the services obtained from model lexicographically and the permissions are sorted by the help of alias created in the model.

services: computed('model', function() {
 return this.get('model.services').sortBy('name');
}),
sortDefinition : ['serviceName'],
permissions    : computed.sort('model.permissions', 'sortDefinition'),
actions        : {
 updatePermissions() {
   this.set('isLoading', true);
   this.get('model.permissions').save()
     .then(() => {
       // Notify success and add Error handler
      }
   }
}

An action named updatePermissions is defined which is triggered when the admin updates and saves the permissions for any role where a PATCH request is made to the server in order to update the permissions.

Rendering data in the template

The data obtained from the model is manipulated in the controller and is rendered to the table in the event-roles template. Every role is fetched from the model and added to the template, all the permissions in sorted order are obtained from the controller and matched with the current role name. The relationship of permissions with role is used to check if its title is equal to the the current role. The permissions are updated accordingly, if the role title is equal to current role.

<tbody>
 {{#each model.roles as |role|}}
   <tr>
     <td>{{role}}</td>
     {{#each permissions as |permission|}}
       {{#if (eq permission.role.titleName role)}}
         <td>
           {{ui-checkbox label=(t 'Create') checked=permission.canCreate onChange=(action (mut permission.canCreate))}}
           <br>
           {{ui-checkbox label=(t 'Read') checked=permission.canRead onChange=(action (mut permission.canRead))}}
           <br>
           {{ui-checkbox label=(t 'Update') checked=permission.canUpdate onChange=(action (mut permission.canUpdate))}}
           <br>
           {{ui-checkbox label=(t 'Delete') checked=permission.canDelete onChange=(action (mut permission.canDelete))}}
         </td>
       {{/if}}
     {{/each}}
   </tr>
 {{/each}}
</tbody>

After rendering the data as shown above, the checkbox for permissions of different services for different roles are checked or unchecked depending upon the bool value of corresponding permission. The admin can update the permissions by checking or unchecking the checkbox and saving the changes made.

Resources

Continue ReadingIntegrating Event Roles API in Open Event Frontend

Adding Speakers Page in Open Event Frontend

Open Event Frontend earlier displayed all the speakers of an event on the main info page only, now a separate route for speakers is created and a separate page is added to display the speakers of an event. The design and layout of speakers page is kept similar to that on Open Event Web app. The info page only shows the featured speakers for an event and the complete list of speakers with additional information is present on speakers route.

Getting the event speakers data

The event data is obtained from the public model and a query is made for the speakers to get the required data. The speakers are fetched only for the sessions which are accepted, this is done by applying a filter while the query is made.

async model() {
 const eventDetails = this.modelFor('public');
 return {
   event    : eventDetails,
   speakers : await eventDetails.query('speakers', {
     filter: [
       {
         name : 'sessions',
         op   : 'any',
         val  : {
           name : 'state',
           op   : 'eq',
           val  : 'accepted'
         }
       }
     ]
   })
 };
}

Adding template for displaying speakers

A template is added to display three speakers in a row. The speakers data obtained from the model is looped through and details of every speaker is passed to the speaker-item component, which handles the design and layout for every item in the speakers list.

<div class="ui stackable grid container">
 {{#each model.speakers as |speaker|}}
   <div class="five wide column speaker-column">
     {{public/speaker-item speaker=speaker}}
   </div>
 {{/each}}
</div>

Adding component for speaker-item

A component for displaying the speaker-item is added to templates/component/public directory. The component contains of an accordion which displays the speaker details like biography, social links and the sessions that would be taken by him.

{{#ui-accordion}}
 <div class="title">
   <div class="ui">
     <img alt="speaker" class="ui medium rounded image" src="{{if speaker.photo.iconImageUrl speaker.image '/images/placeholders/avatar.png'}}">
    ...
    ... 
    ...
    // Speaker Details
   </div>
 </div>
{{/ui-accordion}}

The accordion with speaker image and other details appears for every speaker of an event.

Resources

Continue ReadingAdding Speakers Page in Open Event Frontend

Implementing the PDF download of Schedule in Open Event Web app

Open Event Web app now provides an option to its users to download the PDF of event schedule. Earlier it supported the download of list-view only, now it provides the support to download calendar-view as well. The problem incurred while downloading the calendar-view was that the view gets cropped due to limitations with the library used for PDF generation, thus only some parts of the calendar remained in the PDF. The problem is resolved by creating an image for every date in the schedule and adding the generated image to the PDF.

Selecting and adding the data for PDF generation

The data to be added to PDF depending on the filters and date-selectors applied is chosen from the DOM. Selection of data is done by looping through all the dates and adding only the ones which do not have ‘hide’ class added to them. The selected dates are first expanded such that their complete view is available while generating the image. The complete data is stored in a variable depending on if the complete schedule is requested for download or some filter is applied, which is later used for generating the image.

let fullScheduler = true;
let mapValue = '';

pdf = new jsPDF('l', 'pt', 'a1');
$('.calendar').each(function() {
 let hidePresent = $(this).attr('class').split(' ').indexOf('hide') <= 0;

 if (hidePresent) {
   $timeline = $(this);

  // Expanding the schedule for current date
  ...
  ...
 }
 fullScheduler = hidePresent && fullScheduler;
});

if(fullScheduler) {
 $timeline = $('.calendar').parent();
 mapValue = $timeline.children();
}

Adding the notification while generating the PDF

A loader with the notification is added to provide better user experience, as the PDF generation takes place at the time of request itself it may take some time depending on the size of the schedule. The notifications are added using ‘sweetalert’ library already added for Add to calendar notifications.

swal("Generating the PDF",{
 icon: "./images/loader.gif",
 buttons: false
});

Downloading the PDF

The selected dates are stored in an array named ‘schedArr’ whose data sequentially is passed for canvas generation. A new page is added to the PDF of size equal to canvas and the generated canvas is added to that page. With every new page added to the calendar a count is increased to keep a track if all the selected dates are added to PDF.

async.eachSeries(schedArr, function (child, callback) {
 html2canvas(child, {
   onrendered: function (canvas) {
     pdf.addPage(canvas.width, canvas.height);
     child.style.width = initialWidth[count] + 'px';
     pdf.addImage(canvas, 'png', 0, 0, canvas.width, canvas.height);
     currDate++;
     if(currDate === schedArr.length){
       pdf.deletePage(1);
       swal.close();
       pdf.save(scheduleDate + '.pdf');
     }
     count++;
     callback();
   }
 });
});

When the last page is added, the notification is closed and user is prompted to download pop-box.

Resources

Continue ReadingImplementing the PDF download of Schedule in Open Event Web app

Integrating Google Calendar API in Open Event Web app

Open Event Web app allows organizers to add a feature which enables the users to add any session to their google calendar. The organizer is required to generate an API key and client ID on Google developers console and add the generated credentials to web app generator. The credentials are added to the generated application and every session is added with an Add to calendar button, which on click makes the request to add the corresponding session to the calendar.

Creating Client ID and API key

Enable the Google calendar API from Google developers console. Go to `Create Credentials` tab and generate an API key and client ID for your app. While creating the client ID, an input field is present which requires Authorised javascript origins, mention the domains where the generated application would be deployed.

Adding Client ID and API key to the generator

The Client ID and API key obtained from the developer console is added to the web app generator. The event generated uses these credentials to make a request to the server for adding any session to the calendar.

The added credentials are used to initialise the client in the procedure `initClient()` –

function initClient() {
 let id = document.getElementById('gcalendar-id').value;
 let key = document.getElementById('gcalendar-key').value;
 let CLIENT_ID = id;
 let API_KEY = key;
 let DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
 let SCOPES = "https://www.googleapis.com/auth/calendar";

 gapi.client.init({
   apiKey: API_KEY,
   clientId: CLIENT_ID,
   discoveryDocs: DISCOVERY_DOCS,
   scope: SCOPES
 })
}

Adding session to the Google calendar

Every Google calendar enabled event is provided a button with every session, so that corresponding session can be added to the calendar. A procedure named `handleAuthClick` is called with the details of session being passed as parameter when the user clicks on the button. This function handles the authentication required for adding session to the calendar.

function handleAuthClick(title, location, calendarStart, calendarEnd, timezone, description) {
 let isSignedIn = gapi.auth2.getAuthInstance().isSignedIn.get();
 if (!isSignedIn) {
   gapi.auth2.getAuthInstance().signIn().then(function() {
     main.listUpcomingEvents(title, location, calendarStart, calendarEnd, timezone, description);
   });
 } else {
   main.listUpcomingEvents(title, location, calendarStart, calendarEnd, timezone, description);
 }
}

A function named `listUpcomingEvents` makes the request to insert the event object with details of the session to the calendar.

function listUpcomingEvents(title, location, calendarStart, calendarEnd, timezone, description) {
 let event = {
  ... // Event details  


  ... // Code for notifications
  ...
  ...
   'colorId': '5'
 };

 let request = gapi.client.calendar.events.insert({
   'calendarId': 'primary',
   'resource': event
 });
 request.execute(function(event) {
  // Success notification
 });
}

When the session with the corresponding data is added to calendar, an alert box notifying successful addition of session is shown up on the screen.

Resources

Continue ReadingIntegrating Google Calendar API in Open Event Web app

Adding a Countdown to Orders Page in Open Event Frontend

This blog post will illustrate how you can add a countdown to orders page which on finishing expires the ticket in Open Event. In Open Event we allow some predefined time for users to fill in their details and once the time expires order gets expired and tickets get released. Users can order the tickets again if they want.

We start by adding a createdAt field to orders model so that we can keep track of remaining time. To calculate the time when the order should expire we add predefined time in which user should fill their details to createdAt time. In this way, we get the time when the order will expire.

So now to calculate the remaining time we just subtract the expiring time from current time. And then we render this data into the template. We define getRemainingTime property in our template and fetch the data for that property with help of javascript.

To see the template code visit this link.

The challenge here is to update the time remaining after every second. For this, we take the help of ember runloop. The run.later() function of ember runloop helps us to calculate the property after every second and set it. Code for setting the remaining time with the help of javascript is given below.

// app/components/forms/orders/order-form.js

getRemainingTime: computed('data', function() {
    let willExpireAt = this.get('data.createdAt').add(10, 'minutes');
    this.timer(willExpireAt, this.get('data.identifier'));
  }),

  timer(willExpireAt, orderIdentifier) {
    run.later(() => {
      let currentTime = moment();
      let diff = moment.duration(willExpireAt.diff(currentTime));
      this.set('getRemainingTime', moment.utc(diff.asMilliseconds()).format('mm:ss'));
      if (diff > 0) {
        this.timer(willExpireAt, orderIdentifier);
      } else {
        this.get('data').reload();
        this.get('router').transitionTo('orders.expired', orderIdentifier);
      }
    }, 1000);
  }

 

As given in the code. We pass expiring time and order’s model instance to the timer function. Timer function calculates the remaining time and sets it to getRemainingTime property of template. Timer function runs after every second with the help of run.later() function of ember runloop. To format the remaining time into MM:SS we take help of moment.js library and format the data accordingly.

Once the remaining time is less than zero (time expires) we reload the model and transition current route to expired route. We do not have to set order status as expired inside the FE. Server sets the order as expired after the predefined time. So we just reload the model from the server and we get the updated status of the order.

Resources:
Continue ReadingAdding a Countdown to Orders Page in Open Event Frontend

Adding Helper and Adding Action Buttons to Orders List in Open Event Frontend

This blog post will illustrate how to add a helper to orders list and add action buttons to orders list to delete and cancel an order in Open Event Frontend. To cancel or delete an order item we need to communicate to the server. The API endpoints to which we communicate are:

  • PATCH        /v1/orders/{order_identifier}
  • DELETE    /v1/orders/{orders_identifier}

We will define the action buttons in ui-table component of open event frontend. We will use the cell-actions file to define the cell buttons that will be present in cell-actions column. The following handlebars code will render the buttons on website.

//components/ui-table/cell/events/view/tickets/orders/cell-actions.hbs

class="ui vertical compact basic buttons"> {{#if (and (not-eq record.status 'cancelled') (can-modify-order record))}} {{#ui-popup content=(t 'Cancel order') click=(action (confirm (t 'Are you sure you would like to cancel this Order?') (action cancelOrder record))) class='ui icon button' position='left center'}} class="delete icon"> {{/ui-popup}} {{/if}} {{#if (can-modify-order record)}} {{#ui-popup content=(t 'Delete order') click=(action (confirm (t 'Are you sure you would like to delete this Order?') (action deleteOrder record))) class='ui icon button' position='left center'}} class="trash icon"> {{/ui-popup}} {{/if}} {{#ui-popup content=(t 'Resend order confirmation') class='ui icon button' position='left center'}} class="mail outline icon"> {{/ui-popup}}

 

In above code you can see two things. First is can-modify-order which is a helper. Helper is used to simplify conditional logics which cannot be easily placed in handlebars. Second thing is action. There are two actions defined: cancelOrder and deleteOrder. We will see implementation of these later. First let’s see how we define can-modify-order helper.

In can-modify-order helper we want to return true or false in case we want cancel button and delete button to display or not respectively. We write the code of can-modify-order in helpers/can-modify-order.js file. When we want to get result from this helper we call it from handlebars file and pass any parameter that we want to use in helper. Code for can-modify-order helper is given below.

// helpers/can-modify-order.js

import Helper from '@ember/component/helper';

export function canModifyOrder(params) {
 let [order] = params;
 if (order.amount !== null && order.amount > 0) {
   // returns false if order is paid and completed
   return order.status !== 'completed';
 }
 // returns true for free ticket
 return true;
}

export default Helper.helper(canModifyOrder);

 

We extract the parameter and store it in order variable. We see if it satisfies our conditions we return true else false.

Now lets see how we can define actions to perform delete and cancel action on a order. We define these actions in controllers section of app. After performing suitable operation with order we call save to update modified order and destroyRecord() to delete an order. Let see the code implementation for these actions.

actions: {
   deleteOrder(order) {
     this.set('isLoading', true);
     order.destroyRecord()
       .then(() => {
         this.get('model').reload();
         this.notify.success(this.get('l10n').t('Order has been deleted successfully.'));
       })
       .catch(() => {
         this.notify.error(this.get('l10n').t('An unexpected error has occurred.'));
       })
       .finally(() => {
         this.set('isLoading', false);
       });
   },
   cancelOrder(order) {
     this.set('isLoading', true);
     order.set('status', 'cancelled');
     order.save()
       .then(() => {
         this.notify.success(this.get('l10n').t('Order has been cancelled successfully.'));
       })
       .catch(() => {
         this.notify.error(this.get('l10n').t('An unexpected error has occurred.'));
       })
       .finally(() => {
         this.set('isLoading', false);
       });
   }

 
After defining these actions, buttons in the orders list start working. In this way, we can make use of helper to simplify the conditional logic inside templates and define proper actions.

Resources:
Continue ReadingAdding Helper and Adding Action Buttons to Orders List in Open Event Frontend

Implementing Accepting and Rejecting Proposals in Open Event Frontend

This blog post will illustrate how to add buttons to accept and reject proposal and making them functional. Sessions tab in event dashboard communicates with the following APIs of Open Event Server.

  • GET                    /v1/sessions
  • PATCH              /v1/sessions
What is meant by accepting or rejecting a session in open event?

Sessions are part of event which include one or many speakers. Speakers can propose one or many sessions for a event. Now it is duty of organizer to accept some proposals and reject others. Open event provides two options to accept or reject a proposal i.e. with email or without email.

For this we need to send a key value pair which includes whether we want to send email or not along with other parameters which include current state of session and other important properties. A typical request to alter state of session looks like this.

{
  "data": {
    "attributes": {
      "title": "Micropython Session",
      "level": 1,
      "starts-at": "2017-06-01T10:00:00.500127+00:00",
      "ends-at": "2017-06-01T11:00:00.500127+00:00",
      "created-at": "2017-05-01T01:24:47.500127+00:00",
      "is-mail-sent": false,
      "send-email": true,
    },
    "type": "session",
    "id": "1"
  }
}
Implementing in frontend

We start by providing two buttons for a pending session. One to accept the session and other to reject the session.

On clicking either accept or reject button we get two options to choose i.e. with email and without email. Depending on what organizer chooses a action is fired from the template and sent to controller. Template code for these buttons looks something like this.

class=“ui vertical compact basic buttons”> {{#unless (eq record.state ‘accepted’)}} {{#ui-dropdown class=‘ui icon bottom right pointing dropdown button’}} class=“green checkmark icon”>

class=“menu”>

class=“item” {{action acceptProposal record true}}>{{t ‘With email’}}

 


class=“item” {{action acceptProposal record false}}>{{t ‘Without email’}}

 

      </div>
    {{/ui-dropdown}}
  {{/unless}}
  {{#unless (eq record.state 'rejected')}}
    {{#ui-dropdown class='ui icon bottom right pointing dropdown button'}}
      <i class="red remove icon"></i>

class=“menu”>

class=“item” {{action rejectProposal record true}}>{{t ‘With email’}}

 


class=“item” {{action rejectProposal record false}}>{{t ‘Without email’}}

 

      </div>
    {{/ui-dropdown}}
  {{/unless}}
</div>

We can see that for with email button we trigger accept proposal button with two parameters record and true. Record contains the instance of session and true signifies that we are sending email. Similar is the case with without email button. Controller for these actions looks something like this.

acceptProposal(session, sendEmail) {
      session.set('sendEmail', sendEmail);
      session.set('state', 'accepted');
      session.set('isMailSent', sendEmail);
      this.set('isLoading', true);
      session.save()
        .then(() => {
          sendEmail ? this.notify.success(this.get('l10n').t('Session has been accepted and speaker has been notified via email.'))
            : this.notify.success(this.get('l10n').t('Session has been accepted'));
        })
        .catch(() => {
          this.notify.error(this.get('l10n').t('An unexpected error has occurred.'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    },
    rejectProposal(session, sendEmail) {
      session.set('sendEmail', sendEmail);
      session.set('state', 'rejected');
      session.set('isMailSent', sendEmail);
      this.set('isLoading', true);
      session.save()
        .then(() => {
          sendEmail ? this.notify.success(this.get('l10n').t('Session has been rejected and speaker has been notified via email.'))
            : this.notify.success(this.get('l10n').t('Session has been rejected'));
        })
        .catch(() => {
          this.notify.error(this.get('l10n').t('An unexpected error has occurred.'));
        })
        .finally(() => {
          this.set('isLoading', false);
        });
    }

For accepting with email we set sendEmail field to true and send the query to server. Similarly for reject proposal action we follow same procedure.

Conclusion

Implementing buttons like these, and defining proper actions like these we are able to change the state of session with options to send email or not.

Resources

Continue ReadingImplementing Accepting and Rejecting Proposals in Open Event Frontend

Adding Online Payment Support in Online Event Frontend via Stripe

Open Event Frontend involves ticketing system which supports both paid and free tickets. To buy a paid ticket Open Event provides several options such as debit card, credit card, cheque, bank transfer and onsite payments. So to add support for debit and credit card payments Open Event uses stripe checkout. Using stripe users can enter their card details and pay for their ticket.

Given below are some steps which are to be followed for successfully charging a user for ticket using his/her card.

  • We get publishable key for organizer’s stripe account using OAuth. See this blog.
  • We render stripe checkout button using stripe publishable key. This helps us identify which user to credit after payment.
  • After clicking checkout button user is prompted to enter his/her card details and verify payment.
  • After user’s verification stripe generates a payment token is which is used by open event frontend to charge the user for stipulated amount.
  • We send this token to open event server which processes the token and charge the user.
  • We get error or success message from open event server as per the process outcome.

To render the stripe checkout button we use ember-cli-stripe. Below is the code which helps us to understand how stripe checkout button is rendered.

// app/templates/orders/placed.hbs 

{{stripe-checkout
    locale='auto'
    name="Open Event"
    description=paymentDescription
    amount=paymentAmount
    key=model.event.stripeAuthorization.stripePublishableKey
    onToken=(action "processStripeToken")
    onClosed=(action "checkoutClosed")
    onOpened=(action "checkoutOpened")
}}

 

Full code can be seen here.

We see that we pass different parameters to stripe button which helps stripe identify how to render the button and what information to display. We have also passed the actions onToken(), onClosed() and onOpened(). All these actions are triggered at different instances based on what event occurs.

onToken(): This action is triggered when user has verified his/her purchase and we stripe has generated the payment token. Stripe passes the token back to client (open event frontend server) to process. We have handled this error via different name “processStripeToken()”. We will see cose for these actions below.

onClosed(): This action is called when checkout prompt is closed. We have not used this action in open event frontend. But this can be used to trigger some event in case your application need some action when checkout prompt is closed.

onOpened(): This action is called when checkout prompt is opened. We have not used this action in open event frontend. But this can be used to trigger some event in case your application need some action when checkout prompt is opened.

Code for these actions are given below. Full code file can be seen here.

//  app/controllers/orders/placed.js 

processStripeToken(token) {
   // Send this token to server to process payment
   let order = this.get('model');
   let chargePayload = {
     'data': {
       'attributes': {
         'stripe'            : token.id,
         'paypal_payer_id'   : null,
         'paypal_payment_id' : null
       },
       'type': 'charge'
     }
   };
   let config = {
     skipDataTransform: true
   };
   chargePayload = JSON.stringify(chargePayload);
   return this.get('loader').post(`orders/${order.identifier}/charge`, chargePayload, config)
     .then(charge => {
       if (charge.data.attributes.status) {
         this.get('notify').success(charge.data.attributes.message);
         this.transitionToRoute('orders.view', order.identifier);
       } else {
         this.get('notify').error(charge.data.attributes.message);
       }
     });
 }

 

In above code snippet for processStipeToken() we are processing the stripe payment token received from stripe after user verifies his/her payment. We pass this token to charge endpoint of open event server. After charging the user server send a response which is displayed on frontend.

In this way we achieve the functionality of adding stripe payment support in open event frontend. Please follow the links below for further clarification and detailed overview.

Resources:
Continue ReadingAdding Online Payment Support in Online Event Frontend via Stripe

Adding an Edit Route for Access Codes in Open Event Frontend

This blog post will illustrate how to add edit route to access code to allow organizers editing an access code. Editing access codes deals with the following API on Open Event Server.

PATCH          /v1/access-codes/{id}

First of all we need to add a route to allow editing of access codes. Our route will be /events/{event_id}/tickets/access-codes/edit/{access_code_id}. To generate a new route we need to run the command

ember g route events/view/tickets/access-codes/edit

This will generate new routes files and templates. Also this will add this route in router.js. In router.js we need to specify what we are passing as a parameter to route. For this we specify access_code_id to let ember know that this parameter will be passed with the URL. This is done so as to know which access code to update. Our route should look something like this /events/{event_id}/tickets/access-codes/edit/{access_code_id}. Final router.js file for access-codes part is given below:

//  app/router.js
 
this.route('access-codes', function() {
   this.route('list', { path: '/:access_status' });
   this.route('create');
   this.route('edit', { path: '/edit/:access_code_id' });
});

 

Next we need to pass model (data) to our edit route template. In our model we will be looking for a particular access code with an id and event tickets. After we get our event tickets, we then look for the event tickets which are already present in that access code. This is done so as to check the tickets in the template which are already present in that access code. So for this in afterModel hook we loop over all event tickets and whichever ticket is included in the access code tickets array we mark its isChecked property as true. This helps us to mark those tickets as checked in multiple select checkboxes of template.

// app/routes/events/view/tickets/access-codes/edit.js

model(params) {
   return RSVP.hash({
     accessCode : this.store.findRecord('access-code', params.access_code_id, {}),
     tickets    : this.modelFor('events.view').query('tickets', {})
   });
 },

 async afterModel(model) {
   let tickets = await model.accessCode.tickets;
   let allTickets = model.tickets;
   allTickets.forEach(ticket => {
     if (tickets.includes(ticket)) {
       ticket.set('isChecked', true);
     } else {
       ticket.set('isChecked', false);
     }
   });

 

The information about multiple select checkboxes in frontend has been discussed in this blog post. Now after we are done setting our edit route we need to redirect user to edit page when he/she clicks on the edit button in access code list. For this we define the necessary actions in template which will be triggered when user clicks on the icon. Code for the edit icon in access code list is given below.

// templates/components/ui-table/cell/events/view/tickets/access-codes/cell-actions.hbs

class="ui vertical compact basic buttons"> {{#ui-popup content=(t 'Edit') click=(action editAccessCode record.id) class='ui icon button' position='left center'}} class="edit icon"> {{/ui-popup}}

 

The editAccessCode action looks something like this.

// controller/events/view/tickets/access-codes/edit.js

editAccessCode(id) {
     this.transitionToRoute('events.view.tickets.access-codes.edit', id);
}

 

After clicking on the edit icon user is redirected to edit route where he/she can edit access code choosen. We use the same component that we chose for creating access code. To know more about create access code template component refer to this blog. Finally when saving the edited access code we call save action. This action is defined in the controllers. The action looks something like this.

// controllers/events/view/tickets/access-codes/edit.js

export default Controller.extend({
 actions: {
   save(accessCode) {
     accessCode.save()
       .then(() => {
         this.get('notify').success(this.get('l10n').t('Access code has been successfully updated.'));
         this.transitionToRoute('events.view.tickets.access-codes');
       })
       .catch(() => {
         this.get('notify').error(this.get('l10n').t('An unexpected error has occured. Discount code cannot be created.'));
       });
   }
 }
});

 

After the access code is saved. We redirect user back to access code list.

Resources

Continue ReadingAdding an Edit Route for Access Codes in Open Event Frontend

Integrating Orders API to Allow User Select Tickets for Placing Order in Open Event Frontend

In Open Event Frontend organizer has option to sell tickets for his event. Tickets which are available to public are listed in public page of event for users to buy. In this blog post we will learn how to integrate orders API and manage multiple tickets of varying quantity under an order.

For orders we mainly interact with three API endpoints.

  1. Orders API endpoint
  2. Attendees API endpoint
  3. Tickets API endpoint

Orders and attendees have one to many relationship and similarly orders and tickets also have one to many relationship. Every attendee is related to one ticket. In simple words one attendee has one ticket and one order can contain many tickets of different quantity each meant for different attendee.

// routes/public/index.js

order: this.store.createRecord('order', {
  event     : eventDetails,
  user      : this.get('authManager.currentUser'),
  tickets   : [],
  attendees : []
})

 

We need to create instance of order model to fill in data in that record. We do this in our routes folder of public route. Code snippet is given below.

We create a empty array for tickets and attendees so that we can add their record instances as relationship to order.

As given in screenshot we have a dropdown for each ticket to select quantity of each ticket. To allow user select quantity of a ticket we use #ui-dropdown component of ember-semantic-ui in our template. The code snippet of that is given below.

// templates/components/public/ticket-list.js

{{#ui-dropdown class='compact selection' forceSelection=false onChange=(action 'updateOrder' ticket) as |execute mapper|}}
  {{input type='hidden' id=(concat ticket.id '_quantity') value=ticket.orderQuantity}}
    <i class="dropdown icon"></i>
    
class="default text">0
class="menu">
class="item" data-value="{{map-value mapper 0}}">{{0}}
{{#each (range ticket.minOrder ticket.maxOrder) as |count|}}
class="item" data-value="{{map-value mapper count}}">{{count}}
{{/each}} </div> {{/ui-dropdown}}

 

For every change in quantity of ticket selected we call a action named updateOrder. The code snippet for this action is given below.

// components/public/ticket-list.js

updateOrder(ticket, count) {
      let order = this.get('order');
      ticket.set('orderQuantity', count);
      order.set('amount', this.get('total'));
      if (count > 0) {
        order.tickets.addObject(ticket);
      } else {
        if (order.tickets.includes(ticket)) {
          order.tickets.removeObject(ticket);
        }
      }
    },

 

Here we can see that if quantity of selected ticket is more than 0 we add that ticket to our order otherwise we remove that ticket from the order if it already exists.

Once user selects his tickets for the order he/she can order the tickets. On clicking Order button we call placeOrder action. With help of this we add all the relations and finally send the order information to the server. Code snippet is given below.

// components/public/ticket-list.js
    
placeOrder() {
   let order = this.get('order');
   let event = order.get('event');
   order.tickets.forEach(ticket => {
     let attendee = ticket.orderQuantity;
     let i;
     for (i = 0; i < attendee; i++) {
       order.attendees.addObject(this.store.createRecord('attendee', {
         firstname : 'John',
         lastname  : 'Doe',
         email     : 'johndoe@example.com',
         event,
         ticket
       }));
     }
   });
   this.sendAction('save');
 }

 

Here for each ticket placed under an order we create a dummy attendee related to ticket and event. And then we call save action to save all the models. Code snippet for save is given:

actions: {
    async save() {
      try {
        this.set('isLoading', true);
        let order = this.get('model.order');
        let attendees = order.get('attendees');
        await order.save();
        attendees.forEach(async attendee => {
          await attendee.save();
        });
        await order.save()
          .then(order => {
            this.get('notify').success(this.get('l10n').t('Order created.'));
            this.transitionToRoute('orders.new', order.id);
          });
      } catch (e) {
        this.get('notify').error(this.get('l10n').t('Oops something went wrong. Please try again'));
      }
    }
  }

 

Here we finally save all the models and transition to orders page to enable user fill the attendees details.

Resources:
Continue ReadingIntegrating Orders API to Allow User Select Tickets for Placing Order in Open Event Frontend