Implementing dynamic forms to edit a speaker using Custom Forms in Open Event Frontend

Open Event Frontend allows the organizer of an event to customise the sessions and speakers form using the custom form API. While creating the event the organiser can select the form fields which he wants to place in the sessions and speakers form. This blog will illustrate how a form to edit the details of a speaker is created. Only those fields are included which were included by the person who created the event during the sessions and speakers creation section.

The first step is to retrieve the fields of the form. Each event has custom form fields which can be enabled on the sessions-speakers page, where the organiser can include/exclude the fields for speakers & session forms.

A query is written in the javascript file of the route admin/speakers/edit to retrieve the required details and create a form. The second query helps to determine the speaker id and include the model of speaker and the attribute values of the speaker with that specific id.

import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Route.extend(AuthenticatedRouteMixin, {
 titleToken(model) {
   var speakerName = model.get('name');
   return this.get('l10n').t('Edit Speaker-'.concat(speakerName));
 },
 async model(params) {
   const eventDetails = this.modelFor('events.view');
   return {
     event : eventDetails,
     form  : await eventDetails.query('customForms', {
       'page[size]' : 50,
       sort         : 'id'
     }),
     speaker: await this.get('store').findRecord('speaker', params.speaker_id)
   };
 }
});

In the frontend we call the form of session and speakers. With the speaker-id being passed from the route, a form is created with the values entered by the user during the speaker creation and the other attributes marked included in the session-speakers wizard.

{{forms/session-speaker-form fields=model.form data=model save=(action 'save') isSpeaker=true includeSpeaker=true isSessionSpeaker=true isLoading=isLoading}}

Finally whenever user edits a speaker and clicks on the save button patch endpoint of the speakers API is called and the new details are saved.

Resources

  • Official Ember Model Table docs: http://onechiporenko.github.io/ember-models-table/v.1
  • Official Ember Data documentation: https://github.com/emberjs/data
Continue ReadingImplementing dynamic forms to edit a speaker using Custom Forms in Open Event Frontend

How forms are created and the validations are added in Open Event Frontend

This blog article will illustrate how validations are added to a form  in Open Event Frontend, in a standard format. The form to Edit a Speaker is created in the route /event/<event_identifier>/speakers/edit. For the creation of a form an ember component is generated.

$ ember g component forms/events/view/edit-speaker

This command results in the generation of:

  1. An ember component edit-speaker.js to add the validation rules of the form.
  2. A handlebar edit-speaker.hbs where the HTML code is written.

First the form for editing a speaker is created. All the fields are added.

<form class=”ui form {{if isLoading ‘loading’}}” {{action ‘submit’ on=’submit’}}>


{{input type=’text’ id=’title’ value=data.name}}

{{input type=’text’ id=’email’ value=data.email}}

{{widgets/forms/image-upload
label=(t ‘Photo’)
imageUrl=data.photoUrl
icon=’image’
hint=(t ‘Select Photo’)
maxSizeInKb=1000}}

{{input type=’text’ id=’organisation’ value=data.organisation}}

{{input type=’text’ id=’position’ value=data.position}}

{{input type=’text’ id=’country’ value=data.country}}

{{widgets/forms/rich-text-editor value=data.shortBiography name=’shortBiography’}}

{{input type=’text’ id=’website’ value=data.website}}

{{input type=’text’ id=’twitter’ value=data.twitter}}

<button type=”submit” class=”ui teal submit button update-changes”>
{{t ‘Save Speaker’}}
</button>
</form>

Then validation rules for the fields included in the form are added in the component. The validations of a form are stored as objects, where the  identifier attribute determines which field to apply the validation conditions to. The rules array contains all the rules to be applied to the determined object. Within rules, the type represents the kind of validation, whereas the prompt attribute determines what message shall be displayed in case there is a violation of the validation rule. These validations are in turn implemented by the FormMixin.

import { protocolLessValidUrlPattern, validTwitterProfileUrlPattern } from ‘open-event-frontend/utils/validators’;

export default Component.extend(FormMixin, {

getValidationRules() {
return {
inline : true,
delay  : false,
on     : ‘blur’,
fields : {
email: {
identifier : ’email’,
rules      : [
{
type   : ’empty’,
prompt : this.get(‘l10n’).t(‘Please enter your email ID’)
},
{
type   : ’email’,
prompt : this.get(‘l10n’).t(‘Please enter a valid email ID’)
}
]
},
twitter: {
identifier : ‘twitter’,
optional   : true,
rules      : [
{
type   : ‘regExp’,
value  : validTwitterProfileUrlPattern,
prompt : this.get(‘l10n’).t(‘Please enter a valid twitter url’)
},
{
type   : ‘regExp’,
value  : protocolLessValidUrlPattern,
prompt : this.get(‘l10n’).t(‘Please enter a valid url’)
}
]
},
website: {
identifier : ‘website’,
optional   : ‘true’,
rules      : [
{
type   : ‘regExp’,
value  : protocolLessValidUrlPattern,
prompt : this.get(‘l10n’).t(‘Please enter a valid url’)
}
]
}
}
};
}

Then for adding the validation for the URLs of the speaker’s website and his twitter account regular expressions are used. They are used to perform pattern-matching.

export const  validTwitterProfileUrlPattern = new RegExp(
‘^twitter\\.com\\/([a-zA-Z0-9_]+)$’
);

 

export const protocolLessValidUrlPattern = new RegExp(
‘^’
// user:pass authentication
+ ‘(?:\\S+(?::\\S*)?@)?’
+ ‘(?:’
// IP address exclusion
// private & local networks
+ ‘(?!(?:10|127)(?:\\.\\d{1,3}){3})’
+ ‘(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})’
+ ‘(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})’
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
+ ‘(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])’
+ ‘(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}’
+ ‘(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))’
+ ‘|’
// host name
+ ‘(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)’
// domain name
+ ‘(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*’
// TLD identifier
+ ‘(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))’
// TLD may end with dot
+ ‘\\.?’
+ ‘)’
// port number
+ ‘(?::\\d{2,5})?’
// resource path
+ ‘(?:[/?#]\\S*)?’
+ ‘$’, ‘i’
);

Resources

  • EmberJS Mixins–Official ember documentation: https://guides.emberjs.com/v2.2.0/models
  • Kravvitz, Regular Expression Rules: http://forums.devshed.com/javascript-development/493764-regexp-match-url-pattern-post1944160.html#post1944160
Continue ReadingHow forms are created and the validations are added in Open Event Frontend

Open Event Server – Pages API

This article illustrates how the Pages API has been designed and implemented on the server side, i.e., FOSSASIA‘s Open Event Server. Pages endpoint is used to create static pages such as “About Page” or any other page that doesn’t need to be updated frequently and only a specific content is to be shown.

Parameters

  1. name – This stores the name of the page.
      1. Type – String
      2. Required – Yes
  2. title – This stores the title of the page.
      1. Type – String
      2. Required – No
  3. url – This stores the url of the page.
      1. Type – String
      2. Required – Yes
  4. description – This stores the description of the page.
      1. Type – String
      2. Required – Yes
  5. language – This stores the language of the page.
      1. Type – String
      2. Required – No
  6. index – This stores the position of the page.
      1. Type – Integer
      2. Required – No
      3. Default – 0
  7. place – Location where the page will be placed.
      1. Type – String
      2. Required – No
      3. Accepted Values – ‘footer’ and ‘event’

These are the allowed parameters for the endpoint.

Model

Lets see how we model this API. The ORM looks like this :

__tablename__ = 'pages'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
title = db.Column(db.String)
url = db.Column(db.String, nullable=False)
description = db.Column(db.String)
place = db.Column(db.String)
language = db.Column(db.String)
index = db.Column(db.Integer, default=0)

As you can see, we created a table called “pages”. This table has 8 columns, 7 of which are the parameters that I have mentioned above. The column “id” is an Integer column and is the primary key column. This will help to differentiate between the various entries in the table.

The visualisation for this table looks as follows :

API

We support the following operations:

  1. GET all the pages in the database
  2. POST create a new page
  3. GET details of a single page as per id
  4. PATCH a single page by id
  5. DELETE a single page by id

To implement this we first add the routes in our python file as follows :

api.route(PageList, 'page_list', '/pages')
api.route(PageDetail, 'page_detail', '/pages/<int:id>')

Then we define these classes to handle the requests. The first route looks as follows:

class PageList(ResourceList):
   """
   List and create page
   """
   decorators = (api.has_permission('is_admin', methods="POST"),)
   schema = PageSchema
   data_layer = {'session': db.session,
                 'model': Page}

As can be seen above, this request requires the user to be an admin. It uses the Page model described above and handles a POST request.

The second route is:

class PageDetail(ResourceDetail):
   """
   Page detail by id
   """
   schema = PageSchema
   decorators = (api.has_permission('is_admin', methods="PATCH,DELETE"),)
   data_layer = {'session': db.session,
                 'model': Page}

This route also requires the user to be an admin. It uses the Page model and handles PATCH, DELETE requests.

To summarise our APIs are:

GET

/v1/pages{?sort,filter}

POST

/v1/pages{?sort,filter}

GET

/v1/pages/{page_id}

PATCH

/v1/pages/{page_id}

DELETE

/v1/pages/{page_id}

References

Continue ReadingOpen Event Server – Pages API

Open Event Frontend – Updating Ember Models Table from V1 to V2

FOSSASIA‘s Open Event Frontend uses the Ember Models Table for rendering all its tables. This provides features like easy sorting, pagination etc. Another major feature is that it can be modified to meet our styling needs. As we use Semantic UI for styling, we added the required CSS classes to our table.

In version 1 this was done by overriding the classes, as shown below :

const defaultMessages = {
  searchLabel            : 'Search:',
  searchPlaceholder      : 'Search',


  ..... more to follow 
};

const defaultIcons = {
  sortAsc         : 'caret down icon',
  sortDesc        : 'caret up icon',
  columnVisible   : 'checkmark box icon',
  
  ..... more to follow  
};

const defaultCssClasses = {
  outerTableWrapper              : 'ui ui-table',
  innerTableWrapper              : 'ui segment column sixteen wide inner-table-wrapper',
  table                          : 'ui tablet stackable very basic table',
  globalFilterWrapper            : 'ui row',

 ... more to follow
};

const assign = Object.assign || assign;

export default TableComponent.extend({
  layout,

  _setupMessages: observer('customMessages', function() {
    const customIcons = getWithDefault(this, 'customMessages', {});
    let newMessages = {};
    assign(newMessages, defaultMessages, customIcons);
    set(this, 'messages', O.create(newMessages));
  }),

  _setupIcons() {
    const customIcons = getWithDefault(this, 'customIcons', {});
    let newIcons = {};
    assign(newIcons, defaultIcons, customIcons);
    set(this, 'icons', O.create(newIcons));
  },

  _setupClasses() {
    const customClasses = getWithDefault(this, 'customClasses', {});
    let newClasses = {};
    assign(newClasses, defaultCssClasses, customClasses);
    set(this, 'classes', O.create(newClasses));
  },

  simplePaginationTemplate: 'components/ui-table/simple-pagination',

  ........
});

And was used in the template as follows:

<div class="{{classes.outerTableWrapper}}">
  <div class="{{classes.globalFilterDropdownWrapper}}">

But in version 2, some major changes were introduced as follows:

  1. All partials inside a models-table were replaced with components
  2. models-table can now be used with block content
  3. New themes mechanism introduced for styling

Here, I will talk about how the theming mechanism has been changed. As I mentioned above, in version 1 we used custom classes and icons. In version 2 the idea itself has changed. A new type called Theme was added. It provides four themes out of the box – SemanticUI, Bootstrap4, Bootstrap3, Default.

We can create our custom theme based on any of the predefined themes. To suit our requirements we decided to modify the SemanticUI theme. We created a separate file to keep our custom theme so that code remains clean and short.

import Default from 'ember-models-table/themes/semanticui';

export default Default.extend({
 components: {
   'pagination-simple'    : 'components/ui-table/simple-pagination',
   'numericPagination'    : 'components/ui-table/numeric-pagination',
   .....  
 },

 classes: {
   outerTableWrapper              : 'ui ui-table',
   innerTableWrapper              : 'ui segment column sixteen wide inner-table-wrapper',
   .....
 },

 icons: {
   sortAsc         : 'caret down icon',
   sortDesc        : 'caret up icon',
   ......
 },

 messages: {
   searchLabel            : 'Search:',
   .....
 }
});

So a theme mostly consists of four main parts:

  • Components
  • Classes
  • Icons
  • Messages

The last three are same as customClasses and customIcons and customMessages in version 1. Components is the map for components used internally in the models-table. In case you need to use a custom component, that can be done as follows:

Make a new JavaScript file and provide its path in your theme file.

import DefaultDropdown from '../../columns-dropdown';
import layout from 'your layout file path';
export default DefaultDropdown.extend({
  layout
});

Now just create the theme file object and pass it to themeInstance in the ui-table file (can also be passed in the template and the controller, but this has to be done for each table individually).

import TableComponent from 'ember-models-table/components/models-table';
import layout from 'open-event-frontend/templates/components/ui-table';
import Semantic from 'open-event-frontend/themes/semantic';

export default TableComponent.extend({
 layout,

 themeInstance: Semantic.create()
});

Hence, version 2 introduces many new styling options and requires some refactoring for those who were using version 1. It is totally worth it though considering how easy and well managed it is now.

References

Continue ReadingOpen Event Frontend – Updating Ember Models Table from V1 to V2

Adding the Edit Session route in Open Event Frontend

This blog article will illustrate how to edit a Session in Open Event Frontend, for which a nested route /sessions/edit/<session_id> had to be created. Further an Edit Session Form was created on that route to use the patch end-point of the sessions API of Open Event API.

To get started with it, we simply use the ember CLI to generate the routes

$  ember generate route events/view/sessions/edit

Now router.js file is changed to add the session_id. The router.js file should be looking like this now.

this.route(‘sessions’, function() {
this.route(‘list’, { path: ‘/:session_status’ });
this.route(‘create’);
this.route(‘edit’, { path: ‘/edit/:session_id’ });
});

This means that our routes and sub routes are in place. We are using ember CLI to generate these routes, that means, the template files for them generate automatically. Now these routes exist and we need to write the data in the templates of these routes which will get displayed to the end user.

The routes are nested, the content of the parent route can be made available to all the children routes via the outlet in ember js.

Next, we go to the template file of sessions/edit route which is at templates/events/view/sessions/edit.hbs which displays an Edit Session form.

<form class=”ui form {{if isLoading ‘loading’}}” {{action ‘submit’ on=’submit’}}>


{{input type=’text’ id=’title’ value=data.title}}

{{widgets/forms/rich-text-editor value=data.shortAbstract name=’shortAbstract’}}

{{widgets/forms/rich-text-editor value=data.comments name=’comments’}}

{{input type=’text’ value=data.slidesUrl}}

<button type=”submit” class=”ui teal submit button update-changes”>
{{t ‘Save Session’}}
</button>
</form>

After the editing of different attributes is done Save Session button is clicked for which the action is defined in the controller /controllers/events/view/sessions/edit.js. The patch endpoint was called and the details of the attributes changes were saved.

save() {
this.set(‘isLoading’, true);
this.get(‘model’).save()
.then(() => {
this.get(‘notify’).success(this.get(‘l10n’).t(‘Session details have been saved’));
this.transitionToRoute(‘events.view.sessions’);
})
.catch(() => {
this.get(‘notify’).error(this.get(‘l10n’).t(‘Oops something went wrong. Please try again’));
})
.finally(() => {
this.set(‘isLoading’, false);
});
}
}

Thus after editing the attributes of sessions in the Edit Session form and clicking on the Save Session button the session details are edited.

Resources

  • EmberJS Controllers: https://guides.emberjs.com/v2.12.0/controllers
  • Open Event Server, API docs: https://open-event-api.herokuapp.com
Continue ReadingAdding the Edit Session route in Open Event Frontend

How Sanitizer Service Works in Open Event Frontend

This blog article will illustrate how the sanitizer service works  in Open Event Frontend, which allows the frontend to sanitize or clean any piece of text which can cause potential vulnerabilities in the application. To quote the official ember guides:

“An Ember.Service is a long-lived Ember object that can be made available in different parts of your application.”

Thus the chief advantage the service offers is, that the service once injected in the application can be called at  any place in the templates without an explicit import.

For instance, in the route `coc`, the templates make use of the servcie as

{{sanitize model.codeOfConduct}}

The core of the sanitizer service is comprised of npm sanitize-html module. The sanitize-html is a powerful module which offers an extensive set of features and customisations to deal with cleaning of html embedded text. The service efficiently exposes these features to the app, and wraps its features in various functions to offer several methods which can be used to handle html text.

export default Service.extend({

sanitize: null,

options: {
allowedTags       : [‘b’, ‘strong’, ‘i’, ’em’, ‘u’, ‘ol’, ‘ul’, ‘li’, ‘a’, ‘p’],
allowedAttributes : {
‘a’: [‘href’, ‘rel’, ‘target’]
},
selfClosing           : [‘br’],
allowedSchemes        : [‘http’, ‘https’, ‘ftp’, ‘mailto’],
allowedSchemesByTag   : {},
allowProtocolRelative : false,
transformTags         : {
‘i’ : ’em’,
‘b’ : ‘strong’,
‘a’ : sanitizeHtml.simpleTransform(‘a’, { rel: ‘nofollow’, target: ‘_blank’ })

},

purify(string) {
return sanitizeHtml(string, this.options);
},

strip(string) {
return sanitizeHtml(string, {
allowedTags       : [],
allowedAttributes : []
});
}
});

The options parameter of the service allows properties like allowedTags and and allowedAttributes which remove the specified tags and attributes from the text respectively. The transformTags property replaces the specified left hand side tags to the corresponding right hand side tags.

These are the generic requirements of the app and hence are exposed via tha purify method of the service. The purify method returns the sanitized string based on the configuration in the options parameter. Alternatively the strip method does not make use of the options parameter and rather passes a custom set of options with empty values for allowedTags and allowedAttributes. This method is used to completely remove any html tags or attributes from the text.

The service can be used outside of the templates in a controller or a component.

For instance the css helper uses the service to clean any text of html tags passed as a css property. The CSS helper is defined as follows.

export default Helper.extend({
sanitizer: service(),

compute(params, hash) {
let style = ”;
forOwn(hash, (value, key) => {
style += `${key}: ${value};`;
});
return htmlSafe(this.get(‘sanitizer’).strip(style));

});

Resources

  • Ember Services: https://guides.emberjs.com/v2.1.0/applications/services/
  • Sanitize-HTML docs: https://www.npmjs.com/package/sanitize-html

 

Continue ReadingHow Sanitizer Service Works in Open Event Frontend

Implementing Speaker Table on Open Event Frontend by Integrating Speakers API

This blog article will illustrate how the Speakers API is integrated in Open Event Frontend, which allows for the speakers and their associated data to be displayed in the speakers table. Also, it illustrates how the basic semantic UI table is converted into an ember model table to accommodate the fetched data from the API. Our discussion primarily will involve the app/routes/events/view/speakers  route to illustrate the process.

The primary end point of Open Event API with which we are concerned with for fetching the the speaker details is:

GET /v1/events/{event_identifier}/speakers

First we need to formulate the filters options while making the API call. There are several tabs present which display all the sessions in a particular state i.e. pending, rejected, accepted and all. Thus the formulated filter options stored in the variable filterOptions are as follows:

let filterOptions = [];
if (params.speakers_sessions_state === 'pending') {
filterOptions = [
{
name : 'state',
op : 'eq',
val : 'pending'
}
];
} else if (params.speakers_sessions_state === 'accepted') {
filterOptions = [
{
name : 'state',
op : 'eq',
val : 'accepted'
}
];
} else if (params.speakers_sessions_state === 'rejected') {
filterOptions = [
{
name : 'state',
op : 'eq',
val : 'rejected'
}
];
} else {
filterOptions = [];
}

Next we need to formulate the required query to actually make the API call. It is important to note here that there is a column for sessions of the speaker in  the speaker table. Sessions are a related field for a user and hence we will make use of the include clause while generating the query, Similarly we will make use of the filter clause to pass on the filter options we generated above in filterOptions.

Since the speakers are being fetched for a particular event, and we are in that event’s dashboard, the speakers in question have a hasMany relationship with the aforementioned event. Thus we can make use of the model already fetched in the view route. So the final query call will be as follows:

 return this.modelFor('events.view').query('speakers', {
include      : 'sessions,event',
filter       : filterOptions,
'page[size]' : 10
});

The page[size] option in the query is for implementing pagination, it ensures that at max 10 speakers are returned at once.

Next, we need to convert the existing table to an ember model table. For this the first step is to delete the entire original table along with the dummy data in it. The events-table ember table component will be re-used to form the base structure of the table as follows:

{{events/events-table columns=columns data=model
useNumericPagination=true
showGlobalFilter=true
showPageSize=true
}}

Final steps of conversion table to ember table involve defining the columns of the table. They will be defined in the usual manner, with mandatory title and name attributes. In case the display requirements of the data are in mere simple text, calling a template for displaying the text is not required, however for more complex natured values in the columns, it is advisable to make use of the component, and the technical logic can be handled in the component template itself. For instance, one such field on the speakers table is sessions which are related records and were included especially in the query call. They are not directly accessible by their field names. Thus they must be referred as a child of the record object.

{{#each record.sessions as |session|}}
       {{session.title}}
{{/each}}

Similarly the template for the actions column will have to be created as it requires complex logic to implement actions on those buttons. After defining all the columns in the controller, the final columns are as follows:

columns: [
{
propertyName : 'name',
title       : 'Name'
},
{
propertyName : 'email',
title       : 'Email'
},
{
propertyName : 'mobile',
title       : 'Phone'
},
{
propertyName   : 'sessions',
title         : 'Submitted Sessions',
template       : 'components/ui-table/cell/events/view/speakers/cell-simple-sessions',
disableSorting : true
},
{
propertyName : '',
title       : 'Actions',
template     : 'components/ui-table/cell/events/view/speakers/cell-buttons'
}
]

After performing all these steps, the static table which was holding dummy data has been converted into an ember table and thus features like inbuilt pagination, searching etc. can be used.

Resources

 

Continue ReadingImplementing Speaker Table on Open Event Frontend by Integrating Speakers API

Open Event Server – Change a Column from NULL to NOT NULL

FOSSASIA‘s Open Event Server uses alembic migration files to handle all database operations and updating. Whenever the database is changed a corresponding migration python script is made so that the database will migrate accordingly for other developers as well. But often we forget that the automatically generated script usually just add/deletes columns or alters the column properties. It does not handle the migration of existing data in that column. This can lead to huge data loss or error in migration as well.

For example :

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('ticket_holders', 'lastname',
                    existing_type=sa.VARCHAR(),
                    nullable=False)
    # ### end Alembic commands ###

Here, the goal was to change the column “ticket_holders” from nullable to not nullable. The script that alembic autogenerated just uses op.alter_column().

It does not count for the already existing data. So, if the column has any entries which are null, this migration will lead to an error saying that the column contains null entries and hence cannot be “NOT NULL”.

How to Handle This?

Before altering the column definition we can follow the following steps :

  1. Look for all the null entries in the column
  2. Give some arbitrary default value to those
  3. Now we can safely alter the column definition

Let’s see how we can achieve this. For connecting with the database we will use SQLAlchemy. First, we get a reference to the table and the corresponding column that we wish to alter.

ticket_holders_table = sa.sql.table('ticket_holders',
                                        sa.Column('lastname', sa.VARCHAR()))

 

Since we need the “last_name” column from the table “ticket_holders”, we specify it in the method argument.

Now, we will give an arbitrary default value to all the originally null entries in the column. In this case, I chose to use a space character.

op.execute(ticket_holders_table.update()
               .where(ticket_holders_table.c.lastname.is_(None))
               .values({'lastname': op.inline_literal(' ')}))

op.execute() can execute direct SQL commands as well but we chose to go with SQLAlchemy which builds an optimal SQL command from our modular input. One such example of a complex SQL command being directly executed is :

op.execute('INSERT INTO event_types(name, slug) SELECT DISTINCT event_type_id, lower(replace(regexp_replace(event_type_id, \'& |,\', \'\', \'g\'), \' \', \'-\')) FROM events where not exists (SELECT 1 FROM event_types where event_types.name=events.event_type_id) and event_type_id is not null;'))

Now that we have handled all the null data, it is safe to alter the column definition. So we proceed to execute the final statement –

op.alter_column('ticket_holders', 'lastname',
                    existing_type=sa.VARCHAR(),
                    nullable=False)

Now the entire migration script will run without any error. The final outcome would be –

  1. All the null “last_name” entries would be replaced by a space character
  2. The “last_name” column would now be a NOT NULL column.

References

Continue ReadingOpen Event Server – Change a Column from NULL to NOT NULL

FOSSASIA Internship Program 2018

Are you interested to participate in the development of Open Source projects in a summer internship? Build up your developer profile with FOSSASIA and spend your summer coding on an open source project.  Contribute to SUSI.AIOpen EventBadgeyayYaydoc, Meilix or PSLab and join us at a workshop week and Jugaadfest in India. Please find the details below and submit your application to our form. Be sure to check out FOSSASIA’s program guidelines.

1. Program Details

  • Sign up on our dedicated form at fossasia.org/internship (Interns need to become members of the org and sign up on its social channels)
  • Internships are 3 months with monthly evaluations
  • plus preparation onboarding after acceptance
  • Eligible are contributors above 18 years of age. Any contributor is eligible including students, professionals, university staff etc. Prefered are contributors who have participated in the community previously.
  • Benefits of the program include Shirts, Swag, certificates. All participants who pass the final evaluation will be eligible to participate in a workshop week and Jugaadfest in September 2018 in Hyderabad. Travel grants and accommodation will be provided.
  • The program is intended as a full-time program. However, if contributors would like to participate who have a day job, they can still join and pass the program if they fulfill all program requirements. All contributors who pass the program will be able to receive funding for workshops and Jugaadfest participation.

2. Timeline

  • Application period ongoing until May 12
  • Acceptance ongoing until May 12
  • Start of pre-period:  May
  • Start of Internship: 1st June
  • Evaluation 1: July
  • Evaluation 2: August
  • Evaluation 3: September
  • End of Internship:  September, 2018
  • Issuing of Certificates: September 2018
  • FOSSASIA Workshop Week /Jugaadfest: September/October

3. Deliverables

  • Daily scrum email to project mailing list answering three questions: What did I do yesterday? What is my plan for today? Is there anything preventing me from achieving my goals, e.g. blockers?
  • Work according to pull requests and issues (submit code on Github and match it with issues)
  • Daily code submissions (software, hardware)
  • Documentation: Text, YouTube videos
  • 1 technical blog post a month with details on solving a problem in a FOSSASIA project (Monthly – 1: by Monday of second week)
  • Design items (in open formats, e.g. XCF, SVG, EPS)

4. Participating Projects

5. Best Practices

Please follow best practices as defined here: https://blog.fossasia.org/open-source-developer-guide-and-best-practices-at-fossasia/

6. Participant Benefits/Support

Participants will receive Swag, certificates and travel support to the FOSSASIA Workshop week and Jugaadfest.

  • Evaluation 1: July, 2018: Successful Participants receive a FOSSASIA Tshirt (sent out together with bag in evaluation 2)
  • Evaluation 2: August: Successful Participants receive a beautiful FOSSASIA bag
  • Evaluation 3: September: Successful Participants receive the following support to participate in the FOSSASIA India Workshop Week and Jugaadfest:
    • 100 SGD travel support from within India and 200 SGD support if coming from outside India
    • One week accommodation in Hyderabad (organized by FOSSASIA)
    • Catering during workshops
Continue ReadingFOSSASIA Internship Program 2018

How Errors from Server Side are Handled On Open Event Frontend

This blog article will illustrate how the various error or status codes are handled  in  Open Event Frontend, and how the appropriate response is generated corresponding to those error codes. Open Event Frontend, relies on Open Event Server for all server operations. Open Event Server exposes  a well documented JSON:API Spec Compliant REST API. The clients using the api primarily interact with it using GET, POST , PATCH and DELETE requests. And thus for each request the API returns corresponding data as response along with it’s status code.

For instance whenever the app opens, for the landing page, all the events are fetched by making a GET request to the end point v1/events. If the request is successful and events data is returned, the status code is 200 which stands for OK in the http standard set by IANA.

Fig 1: Screenshot of google chrome developer consoles’ networking tab while making a request.

Since Open Event server is compliant with JSON:API Spec, to quote it’s official documentation, “Error objects MUST be returned as an array keyed by errors in the top level of a JSON API document.” Thus whenever there is an error, or the request is unsuccessful due to a variety of reasons, the server has a predefined format to convey the information to the front end.

The process is illustrated by the reset password form on open event frontend. When a user forgets his password, he/she has the option to reset it, using his email address. Thus the form just takes in the email address of the user and makes a POST request to the reset-password API endpoint of the server.

  • Once the request is made there are 3 possibilities (check references for error code significance):
    The request is successful and a status code of 200 is returned.
  • The email address user entered doesn’t exists and no record is found in the database. 422 status code should be returned.
  • The server is down, or the request is invalid (something unexpected has occurred). In all such scenarios error code 404 should be returned.

this.get('loader')
         .post('auth/reset-password', payload)
         .then(() => {
           this.set('successMessage', this.l10n.t('Please go to the link sent to your     

           email to reset your password'));
         })
         .catch(reason => {
           if (reason && reason.hasOwnProperty('errors') && reason.errors[0].status

               === 422) {
             this.set('errorMessage', this.l10n.t('No account is registered with this

                      email address.'));
           } else {
             this.set('errorMessage', this.l10n.t('An unexpected error occurred.'));
           }
         })
         .finally(()=> {
           this.set('isLoading', false);
         }
         );
Figure 2 : The reset password UI

Thus as mentioned in the JSON:API docs, the errors property is expected to contain the status code and error message(optional) , which ember handles via the the catch block. The catch block is executed whenever the response from the request is not successful. The contents of the response are present in the reason property. If the status of the error is 422, the corresponding message is stored inside the errorMessage property of the component which is further used to display the alert by rendering an error block on the forgot password form.

In case there is no error, the errorMessage is undefined, and the error block is not rendered at all. In case of any other unexpected error, the standard text is displayed by initialising the errorMessage property to it.

Resources

Continue ReadingHow Errors from Server Side are Handled On Open Event Frontend