Implementing Event Invoice Forms

This blog post elaborates on the recent addition of user billing form in Eventyay which is an open source event management solution which allows users to buy & sell tickets, organize events & promote their brand, developed by FOSSASIA. As this project moves forward with the implementation of event invoices coming up,. In the past few weeks, I have collaborated with fellow developers in planning the integration of event invoice payments and this is a necessary step for the same due to its involvement in order invoice templates. This implementation focuses on event invoices billing ( the calculated amount an event organiser has to pay to the platform for their event’s revenue ).

This form includes basic details like contact details, tax ID, billing location and additional information (if any). The following is a specimen of this form :

Tax Form Implementation

First step of this form creation is to employ the account/billing/payment-info route for serving the relevant model data to the frontend.

// app/routes/account/billing/payment-info.js
import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default class extends Route.extend(AuthenticatedRouteMixin) {
titleToken() {
  return this.l10n.t('Payment Info');
}
}

Since the field additions have been done in the user schema in the server side, the corresponding changes have to made in the ember user model as well.

// app/models/user.js
/**
  * Billing Contact Information
  */

billingContactName    : attr('string'),
billingPhone          : attr('string'),
billingCountry        : attr('string'),
company               : attr('string'),
billingAddress        : attr('string'),
billingCity           : attr('string'),
billingZipCode        : attr('string'),
billingTaxInfo        : attr('string'),
billingAdditionalInfo : attr('string'),
billingState          : attr('string'),

This form has a speciality. Instead of using the current user information directly, it uses an intermediate object and employs manipulation in current user record only when the submit button is clicked. This has been implemented in the following way : 

// app/components/user-payment-info-form.js
export default class extends Component.extend(FormMixin) {
didInsertElement() {
  super.didInsertElement(...arguments);
  this.set('userBillingInfo', pick(this.authManager.currentUser, ['billingContactName', 'billingCity', 'billingPhone', 'company', 'billingTaxInfo', 'billingCountry', 'billingState', 'billingAddress', 'billingZipCode', 'billingAdditionalInfo']));
}
@action
submit() {
  this.onValid(async() => {
    this.set('isLoading', true);
    try {
      this.authManager.currentUser.setProperties(this.userBillingInfo);
      await this.authManager.currentUser.save();
      this.notify.success(this.l10n.t('Your billing details has been updated'));
    } catch (error) {
      this.authManager.currentUser.rollbackAttributes();
      this.notify.error(this.l10n.t('An unexpected error occurred'));
    }
    this.set('isLoading', false);
  });
}
}

The usual form validations are employed as expected in this one too and works well in storing the invoice based information.

Resources

Related Work and Code Repository

Continue ReadingImplementing Event Invoice Forms

Customizing Ember CLI Notify for Badgeyay

Badgeyay project is divided into two parts i.e front-end with Ember JS and back-end with REST-API programmed in Python.

Badgeyay comes with many features for customising the process of generation of Badges. It gives freedom to user to choose Input Badge data which is to be printed on the individual badges, choosing the badge size, applying custom background to the badges and then optional features of font customization helps to generate cool badges.You have to just click on create badges and the generated badge with download link appear at bottom of form. But a problem arises with the generated badges link that after logout/login or generation of new badges just after creating badges one time, the link of the previously created badges is still there which is a bit confusing, as user might think the previous link to be the new link and press on that in order to download and find the old badges downloaded.

To resolve this issue, I have used the power of Ember notify library and customized it to show the generated badges link and disappear after a specified time in my Pull Request and after that user can always see his previously generated badges in My Badges route.

Let’s get started and understand it.

  • Customizing Notify library and making the changes in the send Badge data function to show the generated badge link just after the completion of badge generation process.

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';   

export default Controller.extend({
....
routing : service('-routing'),
notify : service('notify'), // importing Notify service
.....
sendBadge(badgeData) {
      const _this = this;
      let badgeRecord = _this.get('store').createRecord('badge', badgeData);
      badgeRecord.save()
        .then(record => {
          _this.set('badgeGenerated', true);
          _this.set('genBadge', record);
          var notify = _this.get('notify');
          var link   = record.download_link; // Assigning download link to a variable 
          var message = notify.success(  // Configuring the message of notify service
            { html:   // Adding the html in notify message
            '
Badge generated successfully.
'
+ '<p>Visit this<b>' + '<a href=' + link + '> Link </a></b> to download badge.</p>', closeAfter: 10000 }); // Specifying the time of closing the message }) .catch(err => { _this.get('notify').error('Unable to generate badge'); }); },

 

I have implemented the customized notify function to show the badge generation link for a specific time.

  • Now run the server to see the implemented changes by following command.

$ ember serve

 

  • Ember Notify service showing the generated Badges link:

Now, I am done with the implementation of customised notify function to show the badge generation link for a specific time of 10 seconds.

Resources:

  1. Ember Docs –  Link
  2. Ember Notify Docs – Link
Continue ReadingCustomizing Ember CLI Notify for Badgeyay

Integrating Ember Notify with Badgeyay

Badgeyay project is divided into two parts i.e front-end with Ember JS and back-end with REST-API programmed in Python.

Badgeyay frontend has many features like Login and Sign up features and Login with OAuth and the most important, the badge generation feature is also up and running but the important thing from the User’s perspective is to get notified of all the actions performed in the application so that user can proceed easily further after performing a specific action in the Application..

In this Blog, I will be discussing how I integrated ember-notify in Badgeyay frontend to notify user about the actions performed in my Pull Request.

Ember-notify displays a little notification message down the bottom of our application.

Let’s get started and understand it step by step.

Step 1:

This module is an ember-cli addon, so installation is easy:

npm install ember-notify --save-dev

 

Step 2:

Inject the notify service in the controller of the template. Here, I will showing how I added it in showing Log In and Logout messages and you can check the whole code in my Pull request for other controllers also.

// controllers/login.js 

import Ember from 'ember';

import Controller from '@ember/controller';

const { inject } = Ember;

export default Controller.extend({
  session : inject.service(),
  notify  : inject.service('notify'),

..........

           this_.transitionToRoute('/');
          this_.get('notify').success('Log In Successful');
        }).catch(function(err) {
          console.log(err.message);
          this_.get('notify').error('Log In Failed ! Please try again');
        });

............

              this_.transitionToRoute('/');
              this_.get('notify').success('Log In Successful');
            })
            .catch(err => {
              console.log(err);
            });
        }).catch(function(err) {
          console.log(err.message);
          this_.get('notify').error('Log In Failed ! Please try again');
        });
 ..........
// controllers/logout.js

import Ember from 'ember';

import Controller from '@ember/controller';

const { inject } = Ember;

export default Controller.extend({
  session : inject.service(),
  notify  : inject.service('notify'),
  beforeModel() {
    return this.get('session').fetch().catch(function() {});
  },
  actions: {
    logOut() {
      this.get('session').close();
      this.transitionToRoute('/');
      this.get('notify').warning('Log Out Successful');
    }
  }
});

 

I have implemented ember-notify for Logging In and Out feature & in the similar way I have implemented it for other controllers and complete code can be seen in my Pull Request.

Step 3::

Now run the server to see the implemented changes by following command.

$ ember serve

 

Navigate to localhost and perform login and logout actions to see the changes.

  •  Successful Log In

  • Successful Log out

  • Successful CSV Upload

Now, we are done with the integration of ember-notify in Badgeyay frontend to notify user about the actions performed in the Application.

Resources:

  • Ember Docs –  Link
  • Ember Notify Docs – Link
Continue ReadingIntegrating Ember Notify with Badgeyay

Implementing Sign up Feature through Email in Badgeyay

Badgeyay project is divided into two parts i.e front-end of Ember JS and back-end with REST-API programmed in Python.

We already have logging In features implemented with the help of Firebase Authentication. A User can login in the Badgeyay with the help of Google, Facebook and Twitter credentials through a single click. Now, the challenging part is to implement the sign up with Email feature in Frontend and Backend to enable the user to signup and Login with the help of Email and Password

In this blog, I will be discussing how I set up Sign up feature in Badgeyay frontend to send the data in backend besides having Oauth logging features in Badgeyay integrated with Firebase in my Pull Request.

The sign up form is already implemented and I have already mentioned in my previous blog. So we need to send the form data to backend to register user so that user can login using the registered credentials. We need an Adapter, Signup action, controller , Signup Data model  and a serializer for doing this task.

Let’s get started and understand the terminologies before implementing the feature.

What is Ember Data ?

It is a data management library for Ember Framework which help to deal with persistent application data.
We will generate Ember data model using Ember CLI in which we will define the data structure we will be requiring to provide to our application for User Signup.

Step 1 : Generate ember data model for signup.

$ ember g model user-signup

 

Step 2: Define the user-signup data model.

import DS from 'ember-data';

const { Model, attr } = DS;

export default Model.extend({
  username : attr('string'),
  email    : attr('string'),
  password : attr('string')
});

 

What are Actions ?

We already have the signup form implemented in frontend. Now we need to provide a action to the form when the user enters the data in form.

If we add the {{action}} helper to any HTML DOM element, when a user clicks the element, the named event will be sent to the template’s corresponding component or controller.

<button class="ui orange submit button" {{ action 'signUp' }}>Sign Up</button>

 

We need to add signUp action in sign-up component and controller.

// Signup Controller 
import Controller from '@ember/controller';

import { inject as service } from '@ember/service';

export default Controller.extend({
  routing : service('-routing'),
  actions : {
    signUp(email, username, password) {
      const _this = this;
      let user_ = this.get('store').createRecord('user-signup', {
        email,
        username,
        password
      });
      user_.save()
        .then(record => {
          _this.transitionToRoute('/');
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
});

// Sign up Component
import Component from '@ember/component';

export default Component.extend({
  init() {
    this._super(...arguments);
  },

  email     : '',
  password  : '',
  isLoading : false,

  actions: {
    signUp(event) {
      event.preventDefault();
      let email = '';
      let password = '';
      let username = '';
      email = this.get('email');
      password = this.get('password');
      username = this.get('username');
      this.get('signUp')(email, username, password);
    }
  },
});

 

What is an Adapter ?

An adapter determines how the data is persisted to a backend data store. We can configure the backend host, URL format and headers for REST API.

Now as we have specific Data Model for User Signup that we will be using for communicating with its backend so we have to create User-Signup Adapter with the help of Ember-CLI.

Step 1: Generate User Signup Adapter by following together.

$ ember generate adapter user-signup

 

Step 2: Extend the Adapter according to User-Signup Model.

import DS from 'ember-data';
import ENV from '../config/environment';

const { APP } = ENV;
const { JSONAPIAdapter } = DS;

export default JSONAPIAdapter.extend({
  host        : APP.backLink,
  pathForType : () => {
    return 'user/register';
  }
});

 

What are Serializers ?

Serializers format the Data sent to and received from the backend store. By default, Ember Data serializes data using the JSON API format.

Now as we have specific Data Model for User Signup that we will be using for communicating with its backend so we have to create User-Signup Serializer with the help Ember-CLI.

Step 1: Generate the User Signup Adapter by following command:

$ ember generate serializer user-signup

 

Step 2: Extend the serializer according to User-Signup Model.

import DS from 'ember-data';

const { JSONAPISerializer } = DS;

export default JSONAPISerializer.extend({

  serialize(snapshot, options) {
    let json = this._super(...arguments);
    return json;
  },

  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    return payload;
  }
});

 

We have successfully set up the User Signup in the frontend and data is communicated to backend in JSON API v1 specification with the help of serializers and Adapters.

This is how I set up Sign up feature in Badgeyay frontend to send the data in backend besides having Oauth logging features in Badgeyay integrated with Firebase in my Pull Request.

Resources:

  1. Ember Docs – Link
  2. Firebase Docs – Link
  3. Badgeyay Repository – Link
Continue ReadingImplementing Sign up Feature through Email in Badgeyay

Creating Forms and their validation using Semantic UI in Badgeyay

Badgeyay project is now divided into two parts i.e front-end of Ember JS and back-end with REST-API programmed in Python.

After a discussion, we have finalized to go with Semantic UI framework which uses simple, common language for parts of interface elements, and familiar patterns found in natural languages for describing elements. Semantic allows to build beautiful websites fast, with concise HTML, intuitive javascript and simplified debugging, helping make front-end development a delightful experience. Semantic is responsively designed allowing a web application to scale on multiple devices. Semantic is production ready and partnered with Ember framework which means we can integrate it with Ember frameworks to organize our UI layer alongside our application logic.

In this blog, I will be discussing how I added Log In and Signup Forms and their validations using Semantic UI for badgeyay frontend in my Pull Request.

Let’s get started and understand it step by step.

Step 1:

Generate ember components of Login and Sign up by using the following command :

$ ember generate component forms/login-form
$ ember generate component forms/signup-form

 

Step 2:

Generate Login and Sign up route by following commands.

$ ember generate route login
$ ember generate route signup 

 

Step 3:

Generate Login and Sign up controller by following commands.

$ ember generate controller login
$ ember generate controller signup

 

Step 4:

Now we have set up the components, routes, and controllers for adding the forms for login and Sign up. Now let’s start writing HTML in handlebars, adding validations and implementing validations for the form components. In this blog, I will be sharing the code of Login form and actions related to logging In of user. You can check the whole code my Pull Request which I have made for adding these Forms.

Step 4.1: Creating a Login Form

<div class="ui hidden divider"></div>
<div class="ui raised segment">
    <div class="ui stackable column doubling centered grid">
        <div class="ui middle aligned center aligned grid">
            <div class="row" >
                <div class="column">
                    <h1 class="ui orange header">
                        Welcome back !
                        <div class="sub header">We're happy  helping you get beautiful name badges.</div>
                    </h1>
                    <div class="ui hidden divider"></div>
                    <form class="ui form">
                        <div class="ui stacked element">
                            <div class="field required">
                                <div class="ui left icon input">
                                    <i class="mail icon"></i>
                                    {{input type="text" value=email name="email" placeholder="E-mail address"}}
                                </div>
                            </div>
                            <div class="field required">
                                <div class="ui left icon input">
                                    <i class="lock icon"></i>
                                    {{input type="password" value=password name="password" placeholder="Password"}}
                                </div>
                            </div>
                            <button class="ui button orange fluid" style="margin-bottom: 10px;" {{ action 'logIn' 'password' }}>Log In</button>
                            <a href="#" class="text muted"> Forgot your password ?</a>
                            <div class="ui divider"></div>
                            <a href="{{href-to 'signup'}}" class="text muted weight-800">Don't have an account yet? Signup</a>
                        </div>
                    </form>
                    <div class="ui horizontal divider">
                        Or
                    </div>
                    <h1 class="ui header">
                        <div class="sub header">Login with</div>
                    </h1>
                </div>
            </div>
            <div class="three column row">
                <div class="column">
                    <div class="ui vertical animated red button fluid" {{ action 'logIn' 'google' }}>
                        <div class="hidden content">Google</div>
                        <div class="visible content">
                            <i class="google plus icon"></i>
                        </div>
                    </div>
                </div>
                <div class="column">
                    <div class="ui vertical animated violet button fluid" tabindex="0" {{ action 'logIn' 'facebook' }}>
                        <div class="hidden content">Facebook</div>
                        <div class="visible content">
                            <i class="facebook f icon"></i>
                        </div>
                    </div>
                </div>
                <div class="column">
                    <div class="ui vertical animated blue button fluid" tabindex="0" {{ action 'logIn' 'twitter' }}>
                        <div class="hidden content">Twitter</div>
                        <div class="visible content">
                            <i class="twitter icon"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

 

Step 4.2: Adding Form Validations

import Component from '@ember/component';

export default Component.extend({
  init() {
    this._super(...arguments);
  },

  actions: {
    logIn(provider) {
      let email = '';
      let password = '';
      if (provider == 'password') {
        email = this.get('email');
        password = this.get('password');
      }
      this.get('login')(provider, email, password);
    },

    logOut() {
      this.get('session').close();
    }
  },

  didRender() {
    this.$('.ui.form')
      .form({
        inline : true,
        delay  : false,
        fields : {
          email: {
            identifier : 'email',
            rules      : [
              {
                type   : 'email',
                prompt : 'Please enter a valid email address'
              }
            ]
          },
          password: {
            identifier : 'password',
            rules      : [
              {
                type   : 'empty',
                prompt : 'Please enter a password'
              }
            ]
          }
        }
      })
    ;
  }
});

 

Step 4.3: Adding Login Actions

import Ember from 'ember';

import Controller from '@ember/controller';

const { inject } = Ember;

export default Controller.extend({
  session: inject.service(),
  beforeModel() {
    return this.get('session').fetch().catch(function() {});
  },
  actions: {
    login(provider, email, password) {
      const that = this;
      if (provider === 'password') {
        this.get('session').open('firebase', {
          provider: 'password',
          email,
          password
        }).then(function(userData) {
          console.log(userData);
          that.transitionToRoute('/');
        }).catch(function(err) {
          console.log(err.message);
        });
      } else {
        const that = this;
        this.get('session').open('firebase', {
          provider
        }).then(function(userData) {
          console.log(userData);
          that.transitionTo('/');
        }).catch(function(err) {
          console.log(err.message);
        });
      }
    },

    logOut() {
      this.get('session').close();
    }
  }
});

 

I have made Login form and in a similar way I implemented the SignUp form and complete code can be seen in my Pull Request.

Now, we are done with writing HTML in handlebars, adding validations and implementing validations for the form components.

Step 5:

Now run the server to see the implemented changes by the following command.

$ ember serve

 

It will show like this :

Navigate to localhost to see the changes.

  • Login Form

  • Sign up  Form

  • Form Validations

Now we are all done with setting up Log In and Signup Forms and their validations using Semantic UI in the badgeyay repository.

This is how I have added Log In and Signup Forms and their validations in my Pull Request.

Resources:

  • Semantic UI Docs – Link
  • Ember Docs – Link
Continue ReadingCreating Forms and their validation using Semantic UI in Badgeyay

Implementing Session and Speaker Creation From Event Panel In Open Event Frontend

Open-Event Front-end uses Ember data for handling Open Event Orga API which abides by JSON API specs. It allows the user to manage the event using the event panel of that event. This panel lets us create or update sessions & speakers. Each speaker must be associated with a session, therefore we save the session before saving the speaker.
In this blog we will see how to Implement the session & speaker creation via event panel. Lets see how we implemented it?

Passing the session & speaker models to the form
On the session & speaker creation page we need to render the forms using the custom form API and create new speaker and session entity. We create a speaker object here and we pass in the relationships for event and the user to it, likewise we create the session object and pass the event relationship to it.

These objects along with form which contains all the fields of the custom form, tracks which is a list of all the tracks & sessionTypes which is a list of all the session types of the event is passed in the model.

return RSVP.hash({
  event : eventDetails,
  form  : eventDetails.query('customForms', {
    'page[size]' : 50,
    sort         : 'id'
  }),
  session: this.get('store').createRecord('session', {
    event: eventDetails
  }),
  speaker: this.get('store').createRecord('speaker', {
    event : eventDetails,
    user  : this.get('authManager.currentUser')
  }),
  tracks       : eventDetails.query('tracks', {}),
  sessionTypes : eventDetails.query('sessionTypes', {})
});

We bind the speaker & session object to the template which has contains the session-speaker component for form validation. The request is only made if the form gets validated.

Saving the data

In Open Event API each speaker must be associated with a session, i.e we must define a session relationship for the speaker. To accomplish this we first save the session into the server and once it has been successfully saved we pass the session as a relation to the speaker object.

this.get('model.session').save()
  .then(session => {
    let speaker = this.get('model.speaker');
    speaker.set('session', session);
    speaker.save()
      .then(() => {
        this.get('notify').success(this.l10n.t('Your session has been saved'));
        this.transitionToRoute('events.view.sessions', this.get('model.event.id'));
      });
  })

We save the objects using the save method. After the speakers and sessions are save successfully we notify the user by showing a success message via the notify service.

Thank you for reading the blog, you can check the source code for the example here.

Resources

Continue ReadingImplementing Session and Speaker Creation From Event Panel In Open Event Frontend

Semantic-UI Validations for Forms in Open Event Frontend

Open Event Frontend requires forms at several places like at the time of login, for creation of events, taking the details of the user, creating discount codes for tickets etc.. Validations for these forms is a must, like in the above picture, we can see that many fields like discount code, amount etc. have been left empty, these null values when stored at backend can induce errors.

Semantic-UI makes our life easier and provides us with it’s own validations. Its form validation behavior checks data against a set of criteria or rules before passing it along to the server.

Let’s now dive deeper into Semantic validations, we’ll take discount code form as our example. The discount code form has many input fields and we have put checks at all of them, these checks are called rules here. We’ll discuss all the rules used in this form one by one

  1. Empty

Here we check if the input box with the identifier discount_amount is empty or not, if it is empty, a prompt is shown with the given message.

         identifier : ‘discount_amount’,
         rules      : [
           {
             type   : ’empty’,
             prompt : this.l10n.t(‘Please enter the discount amount’)
           }
         ]

2. Checked
Here, we validate whether the checkbox is checked or not and if it is not, show corresponding message

rules      : [
   {
     type   : ‘checked’,
     prompt : this.l10n.t(‘Please select the appropriate choices’)
   }]

3. RegExp

These checks are very important in input fields requiring passwords and codes, they specify the allowed input characters

rules      : [{
   type  : ‘regExp’,
   value : ‘^[a-zA-Z0-9_-]*$’
}]

4.Custom rules

Many a times, we require some rules which are by default not given by semantic, here we can create custom rules.

Like here, we want to check whether the user has not set max value lower than min.

$.fn.form.settings.rules.checkMaxMin = () => {
     if (this.get(‘data.minQuantity’) > this.get(‘data.maxQuantity’)) {
       return false;
     }
     return true;
   };

Here, we are creating our own custom rule checkMaxMin which returns boolean value depending upon minQuantity and maxQuantity. Now, this can be directly used as a rule

identifier : ‘min_order’,
optional   : true,
rules      : [
 {
  type   : ‘checkMaxMin’,
  prompt : this.l10n.t(‘Minimum value should not be greater than maximum’)
 }]

You can find the above code here

Additional Resources

Continue ReadingSemantic-UI Validations for Forms in Open Event Frontend