<commit_before>function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");
}
function hideSidebar() {
    $('body').addClass('page-sidebar-closed');
    $('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
}

function showSidebar() {
    $('body').removeClass('page-sidebar-closed');
    $('.page-sidebar-menu').removeClass('page-sidebar-menu-closed');
}

function showAlert(type, message, title) {
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "positionClass": "toast-bottom-right",
        "onclick": null,
        "showDuration": "1000",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    toastr[type](message, title);
}

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i].trim() === obj.trim()) {
            return true;
        }
    }
    return false;
};

function initHiddabbleControls() {
    // find all cond item
    $('[data-cond-item]').each(function() {
        var box = $(this).parents('form');

        var class_name = $(this).attr('data-cond-item');
        var control = box.find(class_name);

        if(control.hasClass('icheck')) {
            control.each(function() {
                var control_item = $(this);
                control_item.on("ifChecked", function() {
                    value = $(this).val();
                    box.find('[data-cond-item="' + class_name + '"]').each(function() {
                        if(!$(this).attr('data-cond-value').split(',').contains(value)) {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                });
                if(control_item.is(':checked')) {
                    value = control_item.val();
                    box.find('[data-cond-item="' + class_name + '"]').each(function() {
                        if(!$(this).attr('data-cond-value').split(',').contains(value)) {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                }
            });

        } else {
            control.on("change", function() {
                value = $(this).val();
                box.find('[data-cond-item="' + class_name + '"]').each(function() {
                    if(!$(this).attr('data-cond-value').split(',').contains(value)) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            });
            control.trigger('change');
        }
    });
}

function jsForAjaxContent(container) {
    // date picker
    container.find('.date-picker-erp').each(function() {
      $(this).datepicker({
          rtl: App.isRTL(),
          orientation: "left",
          autoclose: true,
          format: LANG_DATE_FORMAT_JS
      });
    });

    // icheck
    container.find('.icheck').each(function() {
      var checkboxClass = $(this).attr('data-checkbox') ? $(this).attr('data-checkbox') : 'icheckbox_minimal-grey';
      var radioClass = $(this).attr('data-radio') ? $(this).attr('data-radio') : 'iradio_minimal-grey';

      if (checkboxClass.indexOf('_line') > -1 || radioClass.indexOf('_line') > -1) {
          $(this).iCheck({
              checkboxClass: checkboxClass,
              radioClass: radioClass,
              insert: '

' + $(this).attr("data-label")
          });
      } else {
          $(this).iCheck({
              checkboxClass: checkboxClass,
              radioClass: radioClass
          });
      }
    });

    // hiddable field control
    initHiddabbleControls();

    // for related dataselect
    initParentControls();

    // auto crop image input helper
    container.find('.fileinput-preview').bind("DOMSubtreeModified",function(){
        if(!$(this).find('span').length) {
            $(this).find('img').wrap('');

            // get real size of image
            var imgs = $(this).find('img');
            var img = $(this).find('img')[0]; // Get my img elem
            var pic_real_width, pic_real_height;
            var span = $(this).find('span');
            $("") // Make in memory copy of image to avoid css issues
                .attr("src", $(img).attr("src"))
                .load(function() {
                    pic_real_width = this.width;   // Note: $(this).width() will not
                    pic_real_height = this.height; // work for in memory images.

                    //
                    var box_width = span.width();
                    var box_height = span.height();

                    if(box_width/box_height > pic_real_width/pic_real_height) {
                        imgs.css('width', box_width);

                        var m_top = -((pic_real_height*(box_width/pic_real_width)) - box_height)/2;
                        imgs.css('margin-top', m_top);
                    } else {
                        imgs.css('height', box_height);

                        var m_left = -((pic_real_width*(box_height/pic_real_height)) - box_width)/2;
                        imgs.css('margin-left', m_left);
                    }
                });
        }
    });
    container.find('.fileinput-preview').trigger("DOMSubtreeModified");

    // hightlight tab if has error form
    container.find('.form-group.has-error').each(function() {
        var tab = $(this).parents('.tab-pane');
        var tab_id = tab.attr('id');

        $('[href="#' + tab_id + '"], [data-target="#' + tab_id + '"]').addClass('has_error');
    });

    // input number helper
    container.find('.numberic').each(function() {
        var min = $(this).attr("min");
        var max = $(this).attr("max");
        var digit = $(this).attr("digit");
        var type = $(this).attr("number-type");

        $(this).inputmask(type, {min:parseFloat(min), max: parseFloat(max), digits: parseFloat(digit), groupSeparator: ","});
    });

    // select helper
    container.find('.select2').each(function() {
        $(this).select2();
    });

    // For tooltip
    container.find('.tooltips').tooltip();

    // Row has child ajax content
    container.find('.has-child-table .expand').bind("click", function() {
        var row = $(this).closest('tr');
        var url = row.attr('data-url');
        var cols = row.find('td').length;

        $.ajax({
            url: url,
            method: 'GET'
        }).done(function( result ) {
            var exist = row.next();
            if(!exist.hasClass('child-row')) {
                row.after(
                    '
' +
                        '' +
                            result +
                        '	' +
                    '
'
                );
                row.addClass('opened');

                child = row.next();
                jsForAjaxContent(child);
            } else {
                if(exist.is(':visible')) {
                    exist.remove();
                    row.removeClass('opened');
                } else {
                    exist.show();
                    row.addClass('opened');
                }
            }
        });
    });
}

//scroll to jquery element
function scrollToElement(element, top) {
  if(typeof(top) === 'undefined') {
    top = 0;
  }

  $('html,body').animate({
    scrollTop: element.offset().top - top
  }, 'slow');
}

// Generate unique id
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

// function
function ajaxLinkRequest(link) {
    var method = link.attr('data-method');
    if(typeof(method) === 'undefined' || method.trim() === '') {
        method = 'GET';
    }

    var url = link.attr("href");
    var link_item = link;

    $.ajax({
        url: url,
        method: method,
        data: {
            'authenticity_token': AUTH_TOKEN,
            'format': 'json'
        }
    }).done(function( result ) {
        swal({
            title: result.message,
            text: '',
            type: result.type,
            allowOutsideClick: true,
            confirmButtonText: LANG_OK
        });

        // find outer datalist if exists
        if(link_item.parents('.datalist').length) {
            datalistFilter(link_item.parents('.datalist'));
        }
    });
}

// Init vars
var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');

// Main js execute when loaded page
$(document).ready(function() {
    // Datalist action link with message return
    $(document).on('click', 'a[data-confirm]', function(e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        var message = $(this).attr("data-confirm");
        var link = $(this);

        bootbox.confirm({
            message: message,
            buttons: {
                'cancel': {
                    label: LANG_CANCEL,
                },
                'confirm': {
                    label: LANG_OK,
                }
            },
            callback: function(result) {
                if (result) {
                    if (link.parents('.datalist-list-action').length) {
                        listActionProccess(link);
                    } else if(link.hasClass('ajax-link')) {
                        ajaxLinkRequest(link);
                    } else if(link.hasClass('link-method')) {
                        link.removeAttr('data-confirm');
                        link.trigger('click');
                    } else {
                        window.location = link.attr('href');
                    }
                }
            }
        });
    });

    // Datalist action link with message return
    $(document).on('click', 'a.ajax-link', function(e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        ajaxLinkRequest($(this));
    });

    // Grap link with data-method attribute
    $(document).on('click', 'a.link-method[data-method]', function(e) {

        // return if this is list action
        if($(this).parents('.datalist-list-action').length) {
            return;
        }

        e.preventDefault();

        var method = $(this).attr("data-method");
        var action = $(this).attr("href");

        var newForm = jQuery('<form>', {
            'action': action,
            'method': 'POST',
            'target': '_top'
        });
        newForm.append(jQuery('<input>', {
            'name': 'authenticity_token',
            'value': AUTH_TOKEN,
            'type': 'hidden'
        }));
        newForm.append(jQuery('<input>', {
            'name': '_method',
            'value': method,
            'type': 'hidden'
        }));
        $(document.body).append(newForm);
        newForm.submit();
    });

    // Grap link with data-method attribute
    jsForAjaxContent($('body'));

    // images uploader event
    $(document).on('click', '.images-upload .image-box .thumbnail', function() {
        $(this).parents('.image-box').find('input[type=file]').trigger('click');
    });
    $(document).on('click', '.images-upload .image-box .remove-image', function() {
        $(this).parents('.image-box').find('.destroy_input').val('1');
    });
    // remove destroy if has new image
    setInterval(function() {
        $('.images-upload .image-box.fileinput-exists').each(function() {
            $(this).find('.destroy_input').val('');
        });
    }, 1000);

    // Modal link
    $(document).on('click', '.modal-link', function(e) {
        e.preventDefault();

        var url = $(this).attr('href');

        // create new modal if not exist
        var modal_uid = "link-modal-" + guid();
        var modal_size = 'full';
        var title = 'Title';

        var modal = $('#' + modal_uid);
        if(!modal.length) {
            var html = '
' +
                '
' +
                    '
' +
                        '
' +
                            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>' +
                            '
' + title + '
' +
                        '
' +
                        '
' +
                            '' +
                        '
' +
                    '
' +
                '
' +
            '
';
            $('body').append(html);

            modal = $('#' + modal_uid);
        }

        modal.modal('show');

        $.ajax({
            url: url
        }).done(function( html ) {
            modal.find('.modal-body').html(html);
        });
    });

    // Save current sidebar state
    $(document).on('click', '.menu-toggler.sidebar-toggler', function(e) {
        if($('body').hasClass('page-sidebar-closed')) {
            Cookies.set('sidebar_state', 'hide');
        } else {
            Cookies.set('sidebar_state', 'show');
        }
    });
    // show hide sidebar
    var sidebar_state = Cookies.get('sidebar_state');
    if(typeof(sidebar_state) !== 'undefined' && sidebar_state === 'hide') {
        hideSidebar();
    }

    // Product property form
    // $('.product-property-container').
    $(document).on('change', '[name="product[category_id]"]', function() {
        var input = $(this);
        var value = input.val();
        var container = input.parents('form').find('.product-property-container');
        var url = container.attr('data-url');

        if(value == '') {
            container.html('');
        } else {
            $.ajax({
                url: url,
                method: 'GET',
                data: {
                    category_id: value
                }
            }).done(function( data ) {
                container.html(data);
            });
        }
    });

    // show alert for input errors
    $('.help-block.alert').each(function() {
        showAlert('error', $(this).html());
    });

    // global_filter_action
    $(document).on('click', '.global_filter_action', function(e) {
        e.preventDefault();

        var form = $(this).parents('form');
        var url = $(this).attr('href');

        form.attr('action', url);

        form.submit();
    })

    // Auto list
    $('.autolist').autolist();
});
<commit_msg>auto count quantity for addableform table<commit_after>function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");
}
function hideSidebar() {
    $('body').addClass('page-sidebar-closed');
    $('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
}

function showSidebar() {
    $('body').removeClass('page-sidebar-closed');
    $('.page-sidebar-menu').removeClass('page-sidebar-menu-closed');
}

function showAlert(type, message, title) {
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "positionClass": "toast-bottom-right",
        "onclick": null,
        "showDuration": "1000",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    toastr[type](message, title);
}

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i].trim() === obj.trim()) {
            return true;
        }
    }
    return false;
};

function initHiddabbleControls() {
    // find all cond item
    $('[data-cond-item]').each(function() {
        var box = $(this).parents('form');

        var class_name = $(this).attr('data-cond-item');
        var control = box.find(class_name);

        if(control.hasClass('icheck')) {
            control.each(function() {
                var control_item = $(this);
                control_item.on("ifChecked", function() {
                    value = $(this).val();
                    box.find('[data-cond-item="' + class_name + '"]').each(function() {
                        if(!$(this).attr('data-cond-value').split(',').contains(value)) {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                });
                if(control_item.is(':checked')) {
                    value = control_item.val();
                    box.find('[data-cond-item="' + class_name + '"]').each(function() {
                        if(!$(this).attr('data-cond-value').split(',').contains(value)) {
                            $(this).hide();
                        } else {
                            $(this).show();
                        }
                    });
                }
            });

        } else {
            control.on("change", function() {
                value = $(this).val();
                box.find('[data-cond-item="' + class_name + '"]').each(function() {
                    if(!$(this).attr('data-cond-value').split(',').contains(value)) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            });
            control.trigger('change');
        }
    });
}

function jsForAjaxContent(container) {
    // date picker
    container.find('.date-picker-erp').each(function() {
      $(this).datepicker({
          rtl: App.isRTL(),
          orientation: "left",
          autoclose: true,
          format: LANG_DATE_FORMAT_JS
      });
    });

    // icheck
    container.find('.icheck').each(function() {
      var checkboxClass = $(this).attr('data-checkbox') ? $(this).attr('data-checkbox') : 'icheckbox_minimal-grey';
      var radioClass = $(this).attr('data-radio') ? $(this).attr('data-radio') : 'iradio_minimal-grey';

      if (checkboxClass.indexOf('_line') > -1 || radioClass.indexOf('_line') > -1) {
          $(this).iCheck({
              checkboxClass: checkboxClass,
              radioClass: radioClass,
              insert: '

' + $(this).attr("data-label")
          });
      } else {
          $(this).iCheck({
              checkboxClass: checkboxClass,
              radioClass: radioClass
          });
      }
    });

    // hiddable field control
    initHiddabbleControls();

    // for related dataselect
    initParentControls();

    // auto crop image input helper
    container.find('.fileinput-preview').bind("DOMSubtreeModified",function(){
        if(!$(this).find('span').length) {
            $(this).find('img').wrap('');

            // get real size of image
            var imgs = $(this).find('img');
            var img = $(this).find('img')[0]; // Get my img elem
            var pic_real_width, pic_real_height;
            var span = $(this).find('span');
            $("") // Make in memory copy of image to avoid css issues
                .attr("src", $(img).attr("src"))
                .load(function() {
                    pic_real_width = this.width;   // Note: $(this).width() will not
                    pic_real_height = this.height; // work for in memory images.

                    //
                    var box_width = span.width();
                    var box_height = span.height();

                    if(box_width/box_height > pic_real_width/pic_real_height) {
                        imgs.css('width', box_width);

                        var m_top = -((pic_real_height*(box_width/pic_real_width)) - box_height)/2;
                        imgs.css('margin-top', m_top);
                    } else {
                        imgs.css('height', box_height);

                        var m_left = -((pic_real_width*(box_height/pic_real_height)) - box_width)/2;
                        imgs.css('margin-left', m_left);
                    }
                });
        }
    });
    container.find('.fileinput-preview').trigger("DOMSubtreeModified");

    // hightlight tab if has error form
    container.find('.form-group.has-error').each(function() {
        var tab = $(this).parents('.tab-pane');
        var tab_id = tab.attr('id');

        $('[href="#' + tab_id + '"], [data-target="#' + tab_id + '"]').addClass('has_error');
    });

    // input number helper
    container.find('.numberic').each(function() {
        var min = $(this).attr("min");
        var max = $(this).attr("max");
        var digit = $(this).attr("digit");
        var type = $(this).attr("number-type");

        $(this).inputmask(type, {min:parseFloat(min), max: parseFloat(max), digits: parseFloat(digit), groupSeparator: ","});
    });

    // select helper
    container.find('.select2').each(function() {
        $(this).select2();
    });

    // For tooltip
    container.find('.tooltips').tooltip();

    // Row has child ajax content
    container.find('.has-child-table .expand').bind("click", function() {
        var row = $(this).closest('tr');
        var url = row.attr('data-url');
        var cols = row.find('td').length;

        $.ajax({
            url: url,
            method: 'GET'
        }).done(function( result ) {
            var exist = row.next();
            if(!exist.hasClass('child-row')) {
                row.after(
                    '
' +
                        '' +
                            result +
                        '	' +
                    '
'
                );
                row.addClass('opened');

                child = row.next();
                jsForAjaxContent(child);
            } else {
                if(exist.is(':visible')) {
                    exist.remove();
                    row.removeClass('opened');
                } else {
                    exist.show();
                    row.addClass('opened');
                }
            }
        });
    });
}

//scroll to jquery element
function scrollToElement(element, top) {
  if(typeof(top) === 'undefined') {
    top = 0;
  }

  $('html,body').animate({
    scrollTop: element.offset().top - top
  }, 'slow');
}

// Generate unique id
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

// function
function ajaxLinkRequest(link) {
    var method = link.attr('data-method');
    if(typeof(method) === 'undefined' || method.trim() === '') {
        method = 'GET';
    }

    var url = link.attr("href");
    var link_item = link;

    $.ajax({
        url: url,
        method: method,
        data: {
            'authenticity_token': AUTH_TOKEN,
            'format': 'json'
        }
    }).done(function( result ) {
        swal({
            title: result.message,
            text: '',
            type: result.type,
            allowOutsideClick: true,
            confirmButtonText: LANG_OK
        });

        // find outer datalist if exists
        if(link_item.parents('.datalist').length) {
            datalistFilter(link_item.parents('.datalist'));
        }
    });
}

// Auto count quantity for addableform-table (line-form)
function autoAddItemsLine(container) {
    var rows = container.find('table tbody tr:visible');
    var qtytotal = 0;
    rows.each(function() {
        var row = $(this);
        var quantity = parseFloat(row.find('.line_quantity').val());
        // Update items total
        if(quantity) {
            qtytotal += quantity;
        }
    });
    // update line total
    container.find('.quantity_total').html(qtytotal);
}

// Init vars
var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');

// Main js execute when loaded page
$(document).ready(function() {
    // Datalist action link with message return
    $(document).on('click', 'a[data-confirm]', function(e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        var message = $(this).attr("data-confirm");
        var link = $(this);

        bootbox.confirm({
            message: message,
            buttons: {
                'cancel': {
                    label: LANG_CANCEL,
                },
                'confirm': {
                    label: LANG_OK,
                }
            },
            callback: function(result) {
                if (result) {
                    if (link.parents('.datalist-list-action').length) {
                        listActionProccess(link);
                    } else if(link.hasClass('ajax-link')) {
                        ajaxLinkRequest(link);
                    } else if(link.hasClass('link-method')) {
                        link.removeAttr('data-confirm');
                        link.trigger('click');
                    } else {
                        window.location = link.attr('href');
                    }
                }
            }
        });
    });

    // Datalist action link with message return
    $(document).on('click', 'a.ajax-link', function(e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        ajaxLinkRequest($(this));
    });

    // Grap link with data-method attribute
    $(document).on('click', 'a.link-method[data-method]', function(e) {

        // return if this is list action
        if($(this).parents('.datalist-list-action').length) {
            return;
        }

        e.preventDefault();

        var method = $(this).attr("data-method");
        var action = $(this).attr("href");

        var newForm = jQuery('<form>', {
            'action': action,
            'method': 'POST',
            'target': '_top'
        });
        newForm.append(jQuery('<input>', {
            'name': 'authenticity_token',
            'value': AUTH_TOKEN,
            'type': 'hidden'
        }));
        newForm.append(jQuery('<input>', {
            'name': '_method',
            'value': method,
            'type': 'hidden'
        }));
        $(document.body).append(newForm);
        newForm.submit();
    });

    // Grap link with data-method attribute
    jsForAjaxContent($('body'));

    // images uploader event
    $(document).on('click', '.images-upload .image-box .thumbnail', function() {
        $(this).parents('.image-box').find('input[type=file]').trigger('click');
    });
    $(document).on('click', '.images-upload .image-box .remove-image', function() {
        $(this).parents('.image-box').find('.destroy_input').val('1');
    });
    // remove destroy if has new image
    setInterval(function() {
        $('.images-upload .image-box.fileinput-exists').each(function() {
            $(this).find('.destroy_input').val('');
        });
    }, 1000);

    // Modal link
    $(document).on('click', '.modal-link', function(e) {
        e.preventDefault();

        var url = $(this).attr('href');

        // create new modal if not exist
        var modal_uid = "link-modal-" + guid();
        var modal_size = 'full';
        var title = 'Title';

        var modal = $('#' + modal_uid);
        if(!modal.length) {
            var html = '
' +
                '
' +
                    '
' +
                        '
' +
                            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>' +
                            '
' + title + '
' +
                        '
' +
                        '
' +
                            '' +
                        '
' +
                    '
' +
                '
' +
            '
';
            $('body').append(html);

            modal = $('#' + modal_uid);
        }

        modal.modal('show');

        $.ajax({
            url: url
        }).done(function( html ) {
            modal.find('.modal-body').html(html);
        });
    });

    // Save current sidebar state
    $(document).on('click', '.menu-toggler.sidebar-toggler', function(e) {
        if($('body').hasClass('page-sidebar-closed')) {
            Cookies.set('sidebar_state', 'hide');
        } else {
            Cookies.set('sidebar_state', 'show');
        }
    });
    // show hide sidebar
    var sidebar_state = Cookies.get('sidebar_state');
    if(typeof(sidebar_state) !== 'undefined' && sidebar_state === 'hide') {
        hideSidebar();
    }

    // Product property form
    // $('.product-property-container').
    $(document).on('change', '[name="product[category_id]"]', function() {
        var input = $(this);
        var value = input.val();
        var container = input.parents('form').find('.product-property-container');
        var url = container.attr('data-url');

        if(value == '') {
            container.html('');
        } else {
            $.ajax({
                url: url,
                method: 'GET',
                data: {
                    category_id: value
                }
            }).done(function( data ) {
                container.html(data);
            });
        }
    });

    // show alert for input errors
    $('.help-block.alert').each(function() {
        showAlert('error', $(this).html());
    });

    // global_filter_action
    $(document).on('click', '.global_filter_action', function(e) {
        e.preventDefault();

        var form = $(this).parents('form');
        var url = $(this).attr('href');

        form.attr('action', url);

        form.submit();
    });

    // Auto list
    $('.autolist').autolist();

    // -- Auto count quantity for addableform-table (line-form)
    $('.add-items-line').each(function() {
        autoAddItemsLine($(this));
    });

    // Change event on order line
    $(document).on('change keyup', '.add-items-line input', function(e) {
        var container = $(this).parents('.add-items-line');
        autoAddItemsLine(container);
    });

    // Click event nested remove button
    $(document).on('click', '.nested-remove-button', function(e) {
        var container = $(this).parents('.add-items-line');
        setTimeout(function() {autoAddItemsLine(container);}, 100);
    });
    // -END- Auto count quantity for addableform-table (line-form)
});
<|endoftext|>


<commit_before>
var openspending = angular.module('openspending', ['templates-app','templates-common', 'ngCookies', 'ui.router', 'ui.bootstrap', 'localytics.directives', 'openspending.modeler']);

openspending.controller('AppCtrl', ['$scope', '$location', '$http', '$cookies', '$window', '$sce', 'flash',
  function($scope, $location, $http, $cookies, $window, $sce, flash) {

  $scope.flash = flash;

  // Allow SCE escaping in the app
  $scope.trustAsHtml = function(text) {
    return $sce.trustAsHtml('' + text);
  };

}]);

openspending.factory('flash', ['$rootScope', function($rootScope) {
  // Message flashing.
  var currentMessage = null;

  $rootScope.$on("$routeChangeSuccess", function() {
    currentMessage = null;
  });

  return {
    setMessage: function(message, type) {
      currentMessage = [message, type];
    },
    getMessage: function() {
      return currentMessage;
    }
  };
}]);

openspending.factory('OSAPIservice', function($http) {

    var OSAPI = {};

    OSAPI.getDatasets = function(dataset_params) {
      //options include
      //fields=field1,feidl2, and getsources=true
      return $http({
        url: '/api/3/datasets',
        params: dataset_params
      });
    };
    return OSAPI;
  });

openspending.factory('validation', ['flash', function(flash) {
  // handle server-side form validation errors.
  return {
    handle: handle = function(form) {
      return function(res) {
        if (res.status == 400 || !form) {
            var errors = [];
            for (var field in res.data.errors) {
                form[field].$setValidity('value', false);
                form[field].$message = res.data.errors[field];
                errors.push(field);
            }
            if (angular.isDefined(form._errors)) {
                angular.forEach(form._errors, function(field) {
                    if (errors.indexOf(field) == -1) {
                        form[field].$setValidity('value', true);
                    }
                });
            }
            form._errors = errors;
        } else {
          console.log(res);
          flash.setMessage(res.data.message || res.data.title || 'Server error', 'danger');
        }
      };
    }
  };
}]);

openspending.factory('referenceData', ['$http', function($http) {
  /* This is used to cache reference data once it has been retrieved from the
  server. Reference data includes the canonical lists of country names,
  currencies, etc. */
  var referenceData = $http.get('/api/3/reference');

  var getData = function(cb) {
    referenceData.then(function(res) {
      cb(res.data);
    });
  };

  return {'get': getData};
}]);

openspending.controller('DatasetNewCtrl', ['$scope', '$http', '$window', '$location', '$stateParams', 'referenceData', 'validation',
  function($scope, $http, $window, $location, $stateParams, referenceData, validation) {
  /* This controller is not activated via routing, but explicitly through the
  dataset.new flask route. */

  $scope.reference = {};
  $scope.permissions = {"create":false};
  $scope.dataset = {};
  $scope.errors = [];

  referenceData.get(function(reference) {
    $scope.reference = reference;
  });

  var saveExistingDataSet = function(form) {
                          //validate this for the dataorg can be set later anyway?
                          postdata = {};
                          $.extend(postdata, $scope.dataset, {'csrf_token': csrf_token});
                          var dfd = $http.post('/api/3/datasets/' + $stateParams.datasetname, postdata);
                          dfd.then(function(res) {
                            //$location.path('/' + res.data.name + '/manage/meta');
                            if (res.data.success === true){
                              //flash message
                              $location.path('/datasetlist');
                            }
                            else{
                              $scope.errors = res.data.errors;
                              // maybe set error here
                              //error message
                            }
                          }, validation.handle(form));
                        };

  var saveNewDataSet = function(form) {
                        postdata = {};
                        $.extend(postdata, $scope.dataset, {'csrf_token': csrf_token});
                        var dfd = $http.post('/api/3/datasets', postdata);
                        dfd.then(function(res) {
                            if (res.data.success === true){
                              //flash message
                              $location.path('/datasetlist');
                            }
                            else{
                              $scope.errors = res.data.errors;
                              // maybe set error here
                              //error message
                            }

                          //$location.path('/' + res.data.name + '/manage/meta');

                        }, validation.handle(form));
                      };

  if ($stateParams.datasetname){
    //get dataset info and update the scope
    //checks permission as well
    $http.get('/api/3/datasets/' + $stateParams.datasetname)
      .then(function(res){

        //error handling

        $scope.dataset = res.data;
        //need to add in error catch here
        $scope.permissions.create = true;

        $scope.save = saveExistingDataSet;

      });

  }
  else{
    $http.get('/api/3/permissions?dataset=new').then(function(res) {
      $scope.permissions = res.data;
    });
    $scope.save = saveNewDataSet;
  }

}]);

openspending.controller('SourceFormCtrl', ['$scope', '$http', '$window', '$location', '$stateParams', 'referenceData', 'validation',
  function($scope, $http, $window, $location, $stateParams, referenceData, validation) {
    // if $stateProvider.sourcename then populate with data
    // muse have $stateProvider.dataset as dataset name

    $scope.permissions = {"create" : false};
    $scope.reference = {'frequpdate' : [
        {'code': 'never', 'label': 'Never'},
        {'code': 'daily', 'label': 'Daily'},
        {'code': 'weekly', 'label': 'Weekly'},
        {'code': 'monthly', 'label': 'Monthly'}
        ]
      };

    $scope.source = {"label":null, "url": null, "frequpdate":null};

    if (! $stateParams.sourcename){
      //check that user has permission
      $http.get('/api/3/permissions?dataset=new').then(function(res) {
        $scope.permissions = res.data;
      });
    }
    else{
      //populate the form with a call
    }

  $scope.save = function(form) {
    postdata = {};
    $.extend(postdata, $scope.dataset, {'csrf_token': csrf_token});
    var dfd = $http.post('/api/3/datasets', postdata);
    dfd.then(function(res) {
      $location.path('/' + res.data.name + '/manage/meta');
    }, validation.handle(form));
  };

// can check this as we

}]);

var getDataTableOptions = function(resobj){

  var basekeys = _.keys(resobj[0]);
  var headers = [{data:"loaddata", title:"load link"}];
  _.each(basekeys, function(val, key){
    //backslash per https://datatables.net/reference/option/columns.render
	if(val!='description'&&val!='name'&&val!='source'){
    headers.push({data:val.replace('.', '\\.'), title:val.replace('.', '\\.')});
	}
  });

  _.each(resobj, function(val, key){
    val['loaddata'] = ' **Edit Data***';
	val['has_data'] = ''+val['has_data']+'';

  });

  return {data: resobj,
          columns: headers,
          destroy: true};
};

openspending.controller('datasetListCrl', ['$scope', '$http', 'OSAPIservice', '$location',
  function($scope, $http, OSAPIservice, $location) {

    $scope.table_loading= "Loading....";

    $scope.datasets = [];
    OSAPIservice.getDatasets({'fields':"name,label"})
    .success(function (response) {
      $scope.datasets = response;

      var dtops = getDataTableOptions(response);
      //$scope.table_obj = getTablefromDict(response.cells);

      if ($scope.table_obj){
        $scope.table_obj.destroy();
        $(".datatable-preview").empty();
      }
      $scope.table_obj = $(".datatable-preview").DataTable(dtops);
      $scope.table_loading = null;
    });

    $scope.deleteSource = function(datasetname, sourcename){
      //delete is a reserved word
      var req = {
       method: 'DELETE',
       url: '/api/3/datasets/' + datasetname + '/sources/' + sourcename
      };

      $http(req)
      .then(function(res){
        if (res.data){
          $scope.datasets = res.data;
        }
        //remove it from the set or rerun dataListCrl
      });

    };

    $scope.newDatasource = function(){
      $location.path("dataform");
    };

}]);

openspending.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) {
  $urlRouterProvider.otherwise( '/datasetlist' );
});

openspending.config(function OSStateProvider( $stateProvider ) {
  $stateProvider.state('datasetlist', {
    url: '/datasetlist',
    views: {
      "main": {
        controller: 'datasetListCrl',
        templateUrl: 'templates/dataset-list.tpl.html'
      }
    }
  })
  //create a new dataset
  .state('dataform', {
    url: '/dataform',
    views: {
      "main": {
        //controller: 'CubeOptionsCtrl',
        templateUrl: 'templates/data_form.tpl.html'
      }
    }
  })
  //manage an existing dataset
  .state('dataform_edit', {
    url: '/:datasetname/manage',
    views: {
      "main": {
        //controller: 'DatamanagerCrl',
        templateUrl: 'templates/data_form.tpl.html'
      }
    }
  });

});

<commit_msg>link if has_data=true<commit_after>
var openspending = angular.module('openspending', ['templates-app','templates-common', 'ngCookies', 'ui.router', 'ui.bootstrap', 'localytics.directives', 'openspending.modeler']);

openspending.controller('AppCtrl', ['$scope', '$location', '$http', '$cookies', '$window', '$sce', 'flash',
  function($scope, $location, $http, $cookies, $window, $sce, flash) {

  $scope.flash = flash;

  // Allow SCE escaping in the app
  $scope.trustAsHtml = function(text) {
    return $sce.trustAsHtml('' + text);
  };

}]);

openspending.factory('flash', ['$rootScope', function($rootScope) {
  // Message flashing.
  var currentMessage = null;

  $rootScope.$on("$routeChangeSuccess", function() {
    currentMessage = null;
  });

  return {
    setMessage: function(message, type) {
      currentMessage = [message, type];
    },
    getMessage: function() {
      return currentMessage;
    }
  };
}]);

openspending.factory('OSAPIservice', function($http) {

    var OSAPI = {};

    OSAPI.getDatasets = function(dataset_params) {
      //options include
      //fields=field1,feidl2, and getsources=true
      return $http({
        url: '/api/3/datasets',
        params: dataset_params
      });
    };
    return OSAPI;
  });

openspending.factory('validation', ['flash', function(flash) {
  // handle server-side form validation errors.
  return {
    handle: handle = function(form) {
      return function(res) {
        if (res.status == 400 || !form) {
            var errors = [];
            for (var field in res.data.errors) {
                form[field].$setValidity('value', false);
                form[field].$message = res.data.errors[field];
                errors.push(field);
            }
            if (angular.isDefined(form._errors)) {
                angular.forEach(form._errors, function(field) {
                    if (errors.indexOf(field) == -1) {
                        form[field].$setValidity('value', true);
                    }
                });
            }
            form._errors = errors;
        } else {
          console.log(res);
          flash.setMessage(res.data.message || res.data.title || 'Server error', 'danger');
        }
      };
    }
  };
}]);

openspending.factory('referenceData', ['$http', function($http) {
  /* This is used to cache reference data once it has been retrieved from the
  server. Reference data includes the canonical lists of country names,
  currencies, etc. */
  var referenceData = $http.get('/api/3/reference');

  var getData = function(cb) {
    referenceData.then(function(res) {
      cb(res.data);
    });
  };

  return {'get': getData};
}]);

openspending.controller('DatasetNewCtrl', ['$scope', '$http', '$window', '$location', '$stateParams', 'referenceData', 'validation',
  function($scope, $http, $window, $location, $stateParams, referenceData, validation) {
  /* This controller is not activated via routing, but explicitly through the
  dataset.new flask route. */

  $scope.reference = {};
  $scope.permissions = {"create":false};
  $scope.dataset = {};
  $scope.errors = [];

  referenceData.get(function(reference) {
    $scope.reference = reference;
  });

  var saveExistingDataSet = function(form) {
                          //validate this for the dataorg can be set later anyway?
                          postdata = {};
                          $.extend(postdata, $scope.dataset, {'csrf_token': csrf_token});
                          var dfd = $http.post('/api/3/datasets/' + $stateParams.datasetname, postdata);
                          dfd.then(function(res) {
                            //$location.path('/' + res.data.name + '/manage/meta');
                            if (res.data.success === true){
                              //flash message
                              $location.path('/datasetlist');
                            }
                            else{
                              $scope.errors = res.data.errors;
                              // maybe set error here
                              //error message
                            }
                          }, validation.handle(form));
                        };

  var saveNewDataSet = function(form) {
                        postdata = {};
                        $.extend(postdata, $scope.dataset, {'csrf_token': csrf_token});
                        var dfd = $http.post('/api/3/datasets', postdata);
                        dfd.then(function(res) {
                            if (res.data.success === true){
                              //flash message
                              $location.path('/datasetlist');
                            }
                            else{
                              $scope.errors = res.data.errors;
                              // maybe set error here
                              //error message
                            }

                          //$location.path('/' + res.data.name + '/manage/meta');

                        }, validation.handle(form));
                      };

  if ($stateParams.datasetname){
    //get dataset info and update the scope
    //checks permission as well
    $http.get('/api/3/datasets/' + $stateParams.datasetname)
      .then(function(res){

        //error handling

        $scope.dataset = res.data;
        //need to add in error catch here
        $scope.permissions.create = true;

        $scope.save = saveExistingDataSet;

      });

  }
  else{
    $http.get('/api/3/permissions?dataset=new').then(function(res) {
      $scope.permissions = res.data;
    });
    $scope.save = saveNewDataSet;
  }

}]);

openspending.controller('SourceFormCtrl', ['$scope', '$http', '$window', '$location', '$stateParams', 'referenceData', 'validation',
  function($scope, $http, $window, $location, $stateParams, referenceData, validation) {
    // if $stateProvider.sourcename then populate with data
    // muse have $stateProvider.dataset as dataset name

    $scope.permissions = {"create" : false};
    $scope.reference = {'frequpdate' : [
        {'code': 'never', 'label': 'Never'},
        {'code': 'daily', 'label': 'Daily'},
        {'code': 'weekly', 'label': 'Weekly'},
        {'code': 'monthly', 'label': 'Monthly'}
        ]
      };

    $scope.source = {"label":null, "url": null, "frequpdate":null};

    if (! $stateParams.sourcename){
      //check that user has permission
      $http.get('/api/3/permissions?dataset=new').then(function(res) {
        $scope.permissions = res.data;
      });
    }
    else{
      //populate the form with a call
    }

  $scope.save = function(form) {
    postdata = {};
    $.extend(postdata, $scope.dataset, {'csrf_token': csrf_token});
    var dfd = $http.post('/api/3/datasets', postdata);
    dfd.then(function(res) {
      $location.path('/' + res.data.name + '/manage/meta');
    }, validation.handle(form));
  };

// can check this as we

}]);

var getDataTableOptions = function(resobj){

  var basekeys = _.keys(resobj[0]);
  var headers = [{data:"loaddata", title:"load link"}];
  _.each(basekeys, function(val, key){
    //backslash per https://datatables.net/reference/option/columns.render
	if(val!='description'&&val!='name'&&val!='source'){
		headers.push({data:val.replace('.', '\\.'), title:val.replace('.', '\\.')});
	}
  });

  _.each(resobj, function(val, key){
    val['loaddata'] = ' **Edit Data***';

	if(val['has_data']===true){
		val['has_data'] = ''+val['has_data']+'';
    }
  });

  return {data: resobj,
          columns: headers,
          destroy: true};
};

openspending.controller('datasetListCrl', ['$scope', '$http', 'OSAPIservice', '$location',
  function($scope, $http, OSAPIservice, $location) {

    $scope.table_loading= "Loading....";

    $scope.datasets = [];
    OSAPIservice.getDatasets({'fields':"name,label"})
    .success(function (response) {
      $scope.datasets = response;

      var dtops = getDataTableOptions(response);
      //$scope.table_obj = getTablefromDict(response.cells);

      if ($scope.table_obj){
        $scope.table_obj.destroy();
        $(".datatable-preview").empty();
      }
      $scope.table_obj = $(".datatable-preview").DataTable(dtops);
      $scope.table_loading = null;
    });

    $scope.deleteSource = function(datasetname, sourcename){
      //delete is a reserved word
      var req = {
       method: 'DELETE',
       url: '/api/3/datasets/' + datasetname + '/sources/' + sourcename
      };

      $http(req)
      .then(function(res){
        if (res.data){
          $scope.datasets = res.data;
        }
        //remove it from the set or rerun dataListCrl
      });

    };

    $scope.newDatasource = function(){
      $location.path("dataform");
    };

}]);

openspending.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) {
  $urlRouterProvider.otherwise( '/datasetlist' );
});

openspending.config(function OSStateProvider( $stateProvider ) {
  $stateProvider.state('datasetlist', {
    url: '/datasetlist',
    views: {
      "main": {
        controller: 'datasetListCrl',
        templateUrl: 'templates/dataset-list.tpl.html'
      }
    }
  })
  //create a new dataset
  .state('dataform', {
    url: '/dataform',
    views: {
      "main": {
        //controller: 'CubeOptionsCtrl',
        templateUrl: 'templates/data_form.tpl.html'
      }
    }
  })
  //manage an existing dataset
  .state('dataform_edit', {
    url: '/:datasetname/manage',
    views: {
      "main": {
        //controller: 'DatamanagerCrl',
        templateUrl: 'templates/data_form.tpl.html'
      }
    }
  });

});

<|endoftext|>


<commit_before>/**
 * feature detection about dom
 * module  dom/feature
 */

KM.DOM.feature = function(){

	function elementsByTagName(wrap, tagName){
		return wrap.getElementsByTagName(tagName);
	};

	var DOC = document,
		element_test = DOC.createElement('div'),
		a;

	element_test.innerHTML = ' <link/>

a<input type="checkbox"/>';

	a = elementsByTagName(element_test, 'a')[0];

	return {

		// in some old webkit(including chrome), a.style.opacity === '0,7', so use regexp instead
		// ref:
		opacity		: /^0.7$/.test(a.style.opacity),

		compactEl	: !DOC.compatMode || DOC.compatMode === 'CSS1Compat' ?
			  function(doc){ return doc.documentElement; }
			: function(doc){ return doc.body; }
	};

}();<commit_msg>dom/feature: add support to getComputedStyles, event handlers<commit_after>/**
 * feature detection about dom
 * module  dom/feature
 */

KM.DOM.feature = function(){

	function elementsByTagName(wrap, tagName){
		return wrap.getElementsByTagName(tagName);
	};

	var DOC = document,
		defaultView = DOC.defaultView,
		element_test = DOC.createElement('div'),
		ADD_EVENT_LISTENER = 'addEventListener',
		REMOVE_EVENT_LISTENER = 'removeEventListener',

		a;

	element_test.innerHTML = ' <link/>

a<input type="checkbox"/>';

	a = elementsByTagName(element_test, 'a')[0];

	return {

		computedStyle: !!(defaultView && defaultView.getComputedStyle),

		// in some old webkit(including chrome), a.style.opacity === '0,7', so use regexp instead
		// ref:
		opacity: /^0.7$/.test(a.style.opacity),

		compactEl: !DOC.compatMode || DOC.compatMode === 'CSS1Compat' ?
			  function(doc){ return doc.documentElement; }
			: function(doc){ return doc.body; },

		addEvent: element_test[ADD_EVENT_LISTENER] ?
			  function(el, type, fn){ el[ADD_EVENT_LISTENER](type, fn, false); }
			: function(el, type, fn){ el.attachEvent('on' + type, fn); },

		removeEvent: element_test[REMOVE_EVENT_LISTENER] ?
			  function(el, type, fn){ el[REMOVE_EVENT_LISTENER](type, fn, false); }
			: function(el, type, fn){ el.detachEvent('on' + type, fn); }

	};

}();

<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';

import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import DatePicker from 'material-ui/DatePicker';
import TextField from 'material-ui/TextField';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
import { green600, grey50 } from 'material-ui/styles/colors';
import defaultUtils from 'material-ui/DatePicker/dateUtils';
import persianUtils from 'material-ui-persian-date-picker-utils';

import './NewTaskDialog.css';

class NewTaskDialog extends PureComponent {
  constructor() {
    super();
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    this.state = {
      estimationValue: 1,
      repetitionValue: 1,
      task: '',
      start: Date.parse(todayStart),
      end: 0,
      estimation: '',
      repetition: '',
    };
  }
  buttonDisabled = () => !(
    this.state.task
    && this.state.end
    && this.state.estimation
    && /^[0-9]*$/.test(this.state.estimation)
    && /^[0-9]*$/.test(this.state.repetition)
  );
  handleEstimationMenuChange = (e, i, value) => {
    this.setState({
      estimationValue: value,
    });
  }
  handleRepetitionMenuChange = (e, i, value) => {
    this.setState({
      repetitionValue: value,
    });
  }
  handleTaskChange = (e) => {
    this.setState({
      task: e.target.value,
    });
  }
  handleStartChange = (e, start) => {
    this.setState({
      start: Date.parse(start),
    });
  }
  handleEndChange = (e, end) => {
    this.setState({
      end: Date.parse(end),
    });
  }
  handleEstimationChange = (e) => {
    this.setState({
      estimation: e.target.value,
    });
  }
  handleRepetitionChange = (e) => {
    this.setState({
      repetition: e.target.value,
    });
  }
  handleRequestClose = () => {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    this.setState({
      estimationValue: 1,
      repetitionValue: 1,
      task: '',
      start: Date.parse(todayStart),
      end: 0,
      estimation: '',
      repetition: '',
    });
    this.props.onRequestClose();
  }
  handleRequestAdd = () => {
    this.props.onRequestAdd(this.state);
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    this.setState({
      estimationValue: 1,
      repetitionValue: 1,
      task: '',
      start: Date.parse(todayStart),
      end: 0,
      estimation: '',
      repetition: '',
    });
  }
  handleRequestFinish = () => {
    this.handleRequestAdd();
    this.handleRequestClose();
  }
  disablePassed = date => Date.parse(date) < Date.now() - 86400000;
  disableEndBeforeStart = date => Date.parse(date) < this.state.start ||
                                  Date.parse(date) < Date.now() - 86400000;
  render() {
    const actions = [
      <FlatButton
        label="Add and finish"
        primary
        disabled={this.buttonDisabled()}
        onTouchTap={this.handleRequestFinish}
      />,
      <FlatButton
        label="Add and continue"
        primary
        disabled={this.buttonDisabled()}
        onTouchTap={this.handleRequestAdd}
      />,
      <FlatButton
        label="Cancel"
        primary
        onTouchTap={this.handleRequestClose}
      />,
    ];
    const dialogTitleStyle = {
      backgroundColor: green600,
      color: grey50,
    };
    const textFieldStyles = {
      underlineFocusStyle: {
        borderColor: green600,
      },
      floatingLabelFocusStyle: {
        color: green600,
      },
    };
    const datePickerStyles = {
      textFieldStyle: {
        flex: 1,
      },
    };
    const DateTimeFormat = global.Intl.DateTimeFormat;
    return (

        <Dialog
          title="Add new task"
          actions={actions}
          titleStyle={dialogTitleStyle}
          open={this.props.open}
          onRequestClose={this.props.onRequestClose}
        >

          What do you wanna do?

            <TextField
              floatingLabelText="Task title"
              fullWidth
              underlineFocusStyle={textFieldStyles.underlineFocusStyle}
              floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
              value={this.state.task}
              onChange={this.handleTaskChange}
              autoFocus
            />

              <DatePicker
                hintText="Start"
                defaultDate={new Date()}
                autoOk
                DateTimeFormat={DateTimeFormat}
                locale={this.props.calendarSystem}
                utils={
                  this.props.calendarSystem === 'fa-IR' ?
                  persianUtils :
                  defaultUtils
                }
                firstDayOfWeek={this.props.firstDayOfWeek}
                textFieldStyle={datePickerStyles.textFieldStyle}
                shouldDisableDate={this.disablePassed}
                value={new Date(this.state.start)}
                onChange={this.handleStartChange}
              />

              <DatePicker
                hintText="End"
                autoOk
                DateTimeFormat={DateTimeFormat}
                locale={this.props.calendarSystem}
                utils={
                  this.props.calendarSystem === 'fa-IR' ?
                  persianUtils :
                  defaultUtils
                }
                firstDayOfWeek={this.props.firstDayOfWeek}
                textFieldStyle={datePickerStyles.textFieldStyle}
                shouldDisableDate={this.disableEndBeforeStart}
                value={
                  this.state.end ?
                  new Date(this.state.end) :
                  ''
                }
                onChange={this.handleEndChange}
              />

              <TextField
                floatingLabelText="Estimated time"
                underlineFocusStyle={textFieldStyles.underlineFocusStyle}
                floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
                value={this.state.estimation}
                onChange={this.handleEstimationChange}
                errorText={
                  /^[0-9]*$/.test(this.state.estimation) ?
                  '' :
                  'Estimated time should be a number'
                }
              />
              <DropDownMenu
                value={this.state.estimationValue}
                onChange={this.handleEstimationMenuChange}
              >
                <MenuItem value={1} primaryText="Minutes" />
                <MenuItem value={60} primaryText="Hours" />
              </DropDownMenu>

              <TextField
                floatingLabelText="Repetition period"
                underlineFocusStyle={textFieldStyles.underlineFocusStyle}
                floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
                value={this.state.repetition}
                onChange={this.handleRepetitionChange}
                errorText={
                  /^[0-9]*$/.test(this.state.repetition) ?
                  '' :
                  'Repetition period should be a number'
                }
              />
              <DropDownMenu
                value={this.state.repetitionValue}
                onChange={this.handleRepetitionMenuChange}
              >
                <MenuItem value={1} primaryText="Days" />
                <MenuItem value={7} primaryText="Weeks" />
              </DropDownMenu>

        </Dialog>

    );
  }
}

export default NewTaskDialog;
<commit_msg>Fix minor bug in NewTaskDialog<commit_after>import React, { PureComponent } from 'react';

import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import DatePicker from 'material-ui/DatePicker';
import TextField from 'material-ui/TextField';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
import { green600, grey50 } from 'material-ui/styles/colors';
import defaultUtils from 'material-ui/DatePicker/dateUtils';
import persianUtils from 'material-ui-persian-date-picker-utils';

import './NewTaskDialog.css';

class NewTaskDialog extends PureComponent {
  constructor() {
    super();
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    this.state = {
      estimationValue: 1,
      repetitionValue: 1,
      task: '',
      start: Date.parse(todayStart),
      end: 0,
      estimation: '',
      repetition: '',
    };
  }
  buttonDisabled = () => !(
    this.state.task
    && this.state.end
    && this.state.estimation
    && /^[0-9]*$/.test(this.state.estimation)
    && /^[0-9]*$/.test(this.state.repetition)
  );
  handleEstimationMenuChange = (e, i, value) => {
    this.setState({
      estimationValue: value,
    });
  }
  handleRepetitionMenuChange = (e, i, value) => {
    this.setState({
      repetitionValue: value,
    });
  }
  handleTaskChange = (e) => {
    this.setState({
      task: e.target.value,
    });
  }
  handleStartChange = (e, start) => {
    this.setState({
      start: Date.parse(start),
    });
  }
  handleEndChange = (e, end) => {
    this.setState({
      end: Date.parse(end),
    });
  }
  handleEstimationChange = (e) => {
    this.setState({
      estimation: e.target.value,
    });
  }
  handleRepetitionChange = (e) => {
    this.setState({
      repetition: e.target.value,
    });
  }
  handleRequestClose = () => {
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    this.setState({
      estimationValue: 1,
      repetitionValue: 1,
      task: '',
      start: Date.parse(todayStart),
      end: 0,
      estimation: '',
      repetition: '',
    });
    this.props.onRequestClose();
  }
  handleRequestAdd = () => {
    this.props.onRequestAdd(this.state);
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    this.setState({
      estimationValue: 1,
      repetitionValue: 1,
      task: '',
      start: Date.parse(todayStart),
      end: 0,
      estimation: '',
      repetition: '',
    });
  }
  handleRequestFinish = () => {
    this.handleRequestAdd();
    this.handleRequestClose();
  }
  disablePassed = date => Date.parse(date) < Date.now() - 86400000;
  disableEndBeforeStart = date => Date.parse(date) < this.state.start ||
                                  Date.parse(date) < Date.now() - 86400000;
  render() {
    const actions = [
      <FlatButton
        label="Add and finish"
        primary
        disabled={this.buttonDisabled()}
        onTouchTap={this.handleRequestFinish}
      />,
      <FlatButton
        label="Add and continue"
        primary
        disabled={this.buttonDisabled()}
        onTouchTap={this.handleRequestAdd}
      />,
      <FlatButton
        label="Cancel"
        primary
        onTouchTap={this.handleRequestClose}
      />,
    ];
    const dialogTitleStyle = {
      backgroundColor: green600,
      color: grey50,
    };
    const textFieldStyles = {
      underlineFocusStyle: {
        borderColor: green600,
      },
      floatingLabelFocusStyle: {
        color: green600,
      },
    };
    const datePickerStyles = {
      textFieldStyle: {
        flex: 1,
      },
    };
    const DateTimeFormat = global.Intl.DateTimeFormat;
    return (

        <Dialog
          title="Add new task"
          actions={actions}
          titleStyle={dialogTitleStyle}
          open={this.props.open}
          onRequestClose={this.props.onRequestClose}
        >

          What do you wanna do?

            <TextField
              floatingLabelText="Task title"
              fullWidth
              underlineFocusStyle={textFieldStyles.underlineFocusStyle}
              floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
              value={this.state.task}
              onChange={this.handleTaskChange}
              autoFocus
            />

              <DatePicker
                hintText="Start"
                defaultDate={new Date()}
                autoOk
                DateTimeFormat={DateTimeFormat}
                locale={this.props.calendarSystem}
                utils={
                  this.props.calendarSystem === 'fa-IR' ?
                  persianUtils :
                  defaultUtils
                }
                firstDayOfWeek={this.props.firstDayOfWeek}
                textFieldStyle={datePickerStyles.textFieldStyle}
                shouldDisableDate={this.disablePassed}
                value={new Date(this.state.start)}
                onChange={this.handleStartChange}
              />

              <DatePicker
                hintText="End"
                autoOk
                DateTimeFormat={DateTimeFormat}
                locale={this.props.calendarSystem}
                utils={
                  this.props.calendarSystem === 'fa-IR' ?
                  persianUtils :
                  defaultUtils
                }
                firstDayOfWeek={this.props.firstDayOfWeek}
                textFieldStyle={datePickerStyles.textFieldStyle}
                shouldDisableDate={this.disableEndBeforeStart}
                value={
                  this.state.end ?
                  new Date(this.state.end) :
                  null
                }
                onChange={this.handleEndChange}
              />

              <TextField
                floatingLabelText="Estimated time"
                underlineFocusStyle={textFieldStyles.underlineFocusStyle}
                floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
                value={this.state.estimation}
                onChange={this.handleEstimationChange}
                errorText={
                  /^[0-9]*$/.test(this.state.estimation) ?
                  '' :
                  'Estimated time should be a number'
                }
              />
              <DropDownMenu
                value={this.state.estimationValue}
                onChange={this.handleEstimationMenuChange}
              >
                <MenuItem value={1} primaryText="Minutes" />
                <MenuItem value={60} primaryText="Hours" />
              </DropDownMenu>

              <TextField
                floatingLabelText="Repetition period"
                underlineFocusStyle={textFieldStyles.underlineFocusStyle}
                floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle}
                value={this.state.repetition}
                onChange={this.handleRepetitionChange}
                errorText={
                  /^[0-9]*$/.test(this.state.repetition) ?
                  '' :
                  'Repetition period should be a number'
                }
              />
              <DropDownMenu
                value={this.state.repetitionValue}
                onChange={this.handleRepetitionMenuChange}
              >
                <MenuItem value={1} primaryText="Days" />
                <MenuItem value={7} primaryText="Weeks" />
              </DropDownMenu>

        </Dialog>

    );
  }
}

export default NewTaskDialog;
<|endoftext|>


<commit_before>var dbName = 'sag-js-tests';

var isArray = Array.isArray || function(arg) {
  return Object.prototype.toString.call(arg) == '[object Array]';
};

function makeCouch(setDB) {
  var couch = sag.server('localhost', '80');

  couch.setPathPrefix('/db');

  if(setDB) {
    couch.setDatabase(dbName);
  }

  return couch;
}

module('Core');

test('Init', function() {
  var couch;
  expect(1);

  couch = makeCouch(false);

  equal(typeof couch, 'object', 'server() should return an object');
});

test('setDatabase() and currentDatabase()', function() {
  var couch;
  expect(3);

  couch = makeCouch(false);

  equal(couch.currentDatabase(), undefined, 'no db yet');

  equal(couch.setDatabase(dbName), couch, 'returns sag object');
  equal(couch.currentDatabase(), dbName, 'did it get set?');
});

asyncTest('createDatabase()', function() {
  var couch;
  expect(3);

  couch = makeCouch(false);

  equal(
    couch.createDatabase(dbName, function(resp) {
      equal(resp.body.ok, true, 'JSON body/parsing check');
      equal(resp._HTTP.status, '201', 'Proper HTTP code');

      couch.deleteDatabase(dbName, function(r) {
        start();
      });
    }),
    couch,
    'returns sag object'
  );
});

asyncTest('setDatabase() and create if does not exist', function() {
  var couch;
  expect(2);

  couch = makeCouch(false);

  couch.setDatabase(dbName);

  couch.get({
    url: '/',
    callback: function(resp) {
      equal(resp._HTTP.status, 404, 'expect it to not be there');

      couch.setDatabase(dbName, true, function(exists) {
        ok(exists, 'db should exist now');

        start();
      });
    }
  });
});

asyncTest('decode()', function() {
  var couch;
  expect(5);

  couch = makeCouch(true);

  equal(couch.decode(false), couch, 'returns the sag obj');

  couch.get({
    url: '/',
    callback: function(resp) {
      equal(resp._HTTP.status, 200, 'got a response');
      equal(typeof resp.body, 'string', 'no decode');

      couch.decode(true);

      couch.get({
        url: '/',
        callback: function(resp) {
          equal(resp._HTTP.status, 200, 'got a response');
          equal(typeof resp.body, 'object', 'no decode');

          start();
        }
      });
    }
  });
});

asyncTest('get()', function() {
  var couch;
  expect(2);

  couch = makeCouch(true);

  couch.get({
    url: '',
    callback: function(resp) {
      equal(resp._HTTP.status, 200, 'got a 200');
      equal(typeof resp.body, 'object', 'body is decoded');

      start();
    }
  });
});

asyncTest('put()', function() {
  var couch;
  var docID = 'wellhellothere';
  var docData = {
    _id: docID,
    how: 'you doin',
    worked: true
  };

  expect(4);

  couch = makeCouch(true);

  couch.put({
    id: docID,
    data: docData,
    callback: function(resp) {
      equal(resp._HTTP.status, 201, 'got a 201');
      equal(resp.body.id, docID, 'got the id');

      docData._rev = resp.body.rev;

      couch.put({
        id: docID,
        data: docData,
        callback: function(resp) {
          equal(resp._HTTP.status, 201, 'got a 201');

          //for the next call and its deepEqual()
          docData._rev = resp.body.rev;

          couch.get({
            url: docID,
            callback: function(resp) {
              deepEqual(resp.body, docData, 'got the body');

              start();
            }
          });
        }
      });
    }
  });
});

asyncTest('post()', function() {
  var couch;
  var docData = {
    foo: 'bar'
  }

  expect(2);

  couch = makeCouch(true);

  couch.post({
    data: docData,
    callback: function(resp) {
      equal(resp._HTTP.status, 201, 'got a 201');

      //for the next call and deepEqual
      docData._id = resp.body.id;
      docData._rev = resp.body.rev;

      couch.get({
        url: resp.body.id,
        callback: function(resp) {
          deepEqual(resp.body, docData, 'data got saved');

          start();
        }
      });
    }
  });
});

asyncTest('getAllDatabases()', function() {
  var couch;
  expect(3);

  couch = makeCouch(true);

  couch.getAllDatabases(function(resp) {
    var hasOurDb = false;

    equal(resp._HTTP.status, 200, 'got a 200');
    ok(isArray(resp.body));

    for(var i in resp.body) {
      if(resp.body[i] === dbName) {
        hasOurDb = true;
        break;
      }
    }

    ok(hasOurDb, 'Our DB should be in the list.');

    start();
  });
});

asyncTest('head()', function() {
  var couch = makeCouch(true);

  expect(3);

  equal(
    couch.head({
      url: '/',
      callback: function(resp) {
        equal(resp._HTTP.status, 200, 'got a 200');
        strictEqual(resp.body, undefined, 'no body in resp object');

        start();
      }
    }),
    couch,
    'Got the couch object back.'
  );
});

asyncTest('post(), delete(), then head()', function() {
  var couch = makeCouch(true);

  expect(3);

  couch.post({
    data: {},
    callback: function(resp) {
      var id = resp.body.id;
      var rev = resp.body.rev;

      equal(
        couch.delete(id, rev, function(resp) {
          equal(resp._HTTP.status, 200, 'got a 200');

          couch.head({
            url: id,
            callback: function(resp) {
              equal(resp._HTTP.status, 404, 'got a 404 after delete()');

              start();
            }
          });
        }),
        couch,
        'Got the couch object back'
      );
    }
  });
});

asyncTest('bulk()', function() {
  var docs = [
    {
      foo: 'bar',
      _id: 'one'
    },
    {
      hi: 'there',
      _id: 'two'
    }
  ];

  var couch = makeCouch(true);

  expect(2 + docs.length);

  couch.bulk({
    docs: docs,
    callback: function(resp) {
      equal(resp._HTTP.status, 201, 'got a 201 back');
      equal(resp.body.length, docs.length, 'proper array size');

      for(var i in resp.body) {
        equal(resp.body[i].id, docs[i]._id, 'matching _id');
      }

      start();
    }
  });
});

asyncTest('deleteDatabase()', function() {
  var couch;
  expect(3);

  couch = makeCouch(false);

  equal(
    couch.deleteDatabase(dbName, function(resp) {
      equal(resp.body.ok, true, 'JSON body/parsing check');
      equal(resp._HTTP.status, '200', 'Proper HTTP code');

      start();
    }),
    couch,
    'returns sag object'
  );
});
<commit_msg>copy() tests to create a new doc and overwrite an existing doc<commit_after>var dbName = 'sag-js-tests';

var isArray = Array.isArray || function(arg) {
  return Object.prototype.toString.call(arg) == '[object Array]';
};

function makeCouch(setDB) {
  var couch = sag.server('localhost', '80');

  couch.setPathPrefix('/db');

  if(setDB) {
    couch.setDatabase(dbName);
  }

  return couch;
}

module('Core');

test('Init', function() {
  var couch;
  expect(1);

  couch = makeCouch(false);

  equal(typeof couch, 'object', 'server() should return an object');
});

test('setDatabase() and currentDatabase()', function() {
  var couch;
  expect(3);

  couch = makeCouch(false);

  equal(couch.currentDatabase(), undefined, 'no db yet');

  equal(couch.setDatabase(dbName), couch, 'returns sag object');
  equal(couch.currentDatabase(), dbName, 'did it get set?');
});

asyncTest('createDatabase()', function() {
  var couch;
  expect(3);

  couch = makeCouch(false);

  equal(
    couch.createDatabase(dbName, function(resp) {
      equal(resp.body.ok, true, 'JSON body/parsing check');
      equal(resp._HTTP.status, '201', 'Proper HTTP code');

      couch.deleteDatabase(dbName, function(r) {
        start();
      });
    }),
    couch,
    'returns sag object'
  );
});

asyncTest('setDatabase() and create if does not exist', function() {
  var couch;
  expect(2);

  couch = makeCouch(false);

  couch.setDatabase(dbName);

  couch.get({
    url: '/',
    callback: function(resp) {
      equal(resp._HTTP.status, 404, 'expect it to not be there');

      couch.setDatabase(dbName, true, function(exists) {
        ok(exists, 'db should exist now');

        start();
      });
    }
  });
});

asyncTest('decode()', function() {
  var couch;
  expect(5);

  couch = makeCouch(true);

  equal(couch.decode(false), couch, 'returns the sag obj');

  couch.get({
    url: '/',
    callback: function(resp) {
      equal(resp._HTTP.status, 200, 'got a response');
      equal(typeof resp.body, 'string', 'no decode');

      couch.decode(true);

      couch.get({
        url: '/',
        callback: function(resp) {
          equal(resp._HTTP.status, 200, 'got a response');
          equal(typeof resp.body, 'object', 'no decode');

          start();
        }
      });
    }
  });
});

asyncTest('get()', function() {
  var couch;
  expect(2);

  couch = makeCouch(true);

  couch.get({
    url: '',
    callback: function(resp) {
      equal(resp._HTTP.status, 200, 'got a 200');
      equal(typeof resp.body, 'object', 'body is decoded');

      start();
    }
  });
});

asyncTest('put()', function() {
  var couch;
  var docID = 'wellhellothere';
  var docData = {
    _id: docID,
    how: 'you doin',
    worked: true
  };

  expect(4);

  couch = makeCouch(true);

  couch.put({
    id: docID,
    data: docData,
    callback: function(resp) {
      equal(resp._HTTP.status, 201, 'got a 201');
      equal(resp.body.id, docID, 'got the id');

      docData._rev = resp.body.rev;

      couch.put({
        id: docID,
        data: docData,
        callback: function(resp) {
          equal(resp._HTTP.status, 201, 'got a 201');

          //for the next call and its deepEqual()
          docData._rev = resp.body.rev;

          couch.get({
            url: docID,
            callback: function(resp) {
              deepEqual(resp.body, docData, 'got the body');

              start();
            }
          });
        }
      });
    }
  });
});

asyncTest('post()', function() {
  var couch;
  var docData = {
    foo: 'bar'
  }

  expect(2);

  couch = makeCouch(true);

  couch.post({
    data: docData,
    callback: function(resp) {
      equal(resp._HTTP.status, 201, 'got a 201');

      //for the next call and deepEqual
      docData._id = resp.body.id;
      docData._rev = resp.body.rev;

      couch.get({
        url: resp.body.id,
        callback: function(resp) {
          deepEqual(resp.body, docData, 'data got saved');

          start();
        }
      });
    }
  });
});

asyncTest('getAllDatabases()', function() {
  var couch;
  expect(3);

  couch = makeCouch(true);

  couch.getAllDatabases(function(resp) {
    var hasOurDb = false;

    equal(resp._HTTP.status, 200, 'got a 200');
    ok(isArray(resp.body));

    for(var i in resp.body) {
      if(resp.body[i] === dbName) {
        hasOurDb = true;
        break;
      }
    }

    ok(hasOurDb, 'Our DB should be in the list.');

    start();
  });
});

asyncTest('head()', function() {
  var couch = makeCouch(true);

  expect(3);

  equal(
    couch.head({
      url: '/',
      callback: function(resp) {
        equal(resp._HTTP.status, 200, 'got a 200');
        strictEqual(resp.body, undefined, 'no body in resp object');

        start();
      }
    }),
    couch,
    'Got the couch object back.'
  );
});

asyncTest('post(), delete(), then head()', function() {
  var couch = makeCouch(true);

  expect(3);

  couch.post({
    data: {},
    callback: function(resp) {
      var id = resp.body.id;
      var rev = resp.body.rev;

      equal(
        couch.delete(id, rev, function(resp) {
          equal(resp._HTTP.status, 200, 'got a 200');

          couch.head({
            url: id,
            callback: function(resp) {
              equal(resp._HTTP.status, 404, 'got a 404 after delete()');

              start();
            }
          });
        }),
        couch,
        'Got the couch object back'
      );
    }
  });
});

asyncTest('bulk()', function() {
  var docs = [
    {
      foo: 'bar',
      _id: 'one'
    },
    {
      hi: 'there',
      _id: 'two'
    }
  ];

  var couch = makeCouch(true);

  expect(2 + docs.length);

  couch.bulk({
    docs: docs,
    callback: function(resp) {
      equal(resp._HTTP.status, 201, 'got a 201 back');
      equal(resp.body.length, docs.length, 'proper array size');

      for(var i in resp.body) {
        equal(resp.body[i].id, docs[i]._id, 'matching _id');
      }

      start();
    }
  });
});

asyncTest('copy() to new doc', function() {
  var couch = makeCouch(true);

  expect(2);

  couch.copy({
    srcID: 'one',
    dstID: 'oneCopy',
    callback: function(resp) {
      equal(resp._HTTP.status, 201, 'got a 201 back');
      equal(resp.body.id, 'oneCopy', 'got the id back');

      start();
    }
  });
});

asyncTest('copy() to overwrite', function() {
  var couch = makeCouch(true);

  expect(4);

  //overwrite 'two' with 'one'
  couch.get({
    url: 'two',
    callback: function(resp) {
      equal(resp._HTTP.status, 200, 'got a 200 back');
      ok(resp.body._id, 'has an _id');
      ok(resp.body._rev, 'has a _rev');

      couch.copy({
        srcID: 'one',
        dstID: resp.body._id,
        dstRev: resp.body._rev,
        callback: function(resp) {
          equal(resp._HTTP.status, 201, 'got a 201 back');

          start();
        }
      });
    }
  });
});

asyncTest('deleteDatabase()', function() {
  var couch;
  expect(3);

  couch = makeCouch(false);

  equal(
    couch.deleteDatabase(dbName, function(resp) {
      equal(resp.body.ok, true, 'JSON body/parsing check');
      equal(resp._HTTP.status, '200', 'Proper HTTP code');

      start();
    }),
    couch,
    'returns sag object'
  );
});
<|endoftext|>


<commit_before>var SDK = require('wunderlist')
var dirty = require('dirty')
var db = dirty(__dirname + '/../cache.db')

var conf = {}
require('rc')('wunderlist-cli', conf)

var api = new SDK({
  'accessToken': conf.access_token,
  'clientID': conf.client_id
})

function addTask (task, cb) {
  var req = api.http.tasks.create(task)
  req.then(function (res) {
    cb(res)
  })
}

module.exports = function (task) {
  db.on('load', function () {
    task.list_id = db.get('inbox_id')
    if (task.list_id) {
      addTask(task, function (res) {
        console.log('Created task ' + res.id)
        process.exit()
      })
    } else {
      var req = api.http.lists.all()
      req.then(function (res) {
        task.list_id = res[0].id
        db.set('inbox_id', task.list_id)
        addTask(task, function (task) {
          console.log('Created task ' + task.id)
          process.exit()
        })
      })
    }
  })
}
<commit_msg>exit if title is empty<commit_after>var SDK = require('wunderlist')
var dirty = require('dirty')
var db = dirty(__dirname + '/../cache.db')

var conf = {}
require('rc')('wunderlist-cli', conf)

var api = new SDK({
  'accessToken': conf.access_token,
  'clientID': conf.client_id
})

function addTask (task, cb) {
  var req = api.http.tasks.create(task)
  req.then(function (res) {
    cb(res)
  })
}

module.exports = function (task) {
  if (task.title.trim().length < 1) {
    process.exit();
  }
  db.on('load', function () {
    task.list_id = db.get('inbox_id')
    if (task.list_id) {
      addTask(task, function (res) {
        console.log('Created task ' + res.id)
        process.exit()
      })
    } else {
      var req = api.http.lists.all()
      req.then(function (res) {
        task.list_id = res[0].id
        db.set('inbox_id', task.list_id)
        addTask(task, function (task) {
          console.log('Created task ' + task.id)
          process.exit()
        })
      })
    }
  })
}
<|endoftext|>


<commit_before>import { GraphQLEnumType } from 'graphql';

export default {
  type: new GraphQLEnumType({
    name: 'FairSorts',
    values: {
      created_at_asc: {
        value: 'created_at',
      },
      created_at_desc: {
        value: '-created_at',
      },
      start_at_asc: {
        value: 'start_at',
      },
      start_at_desc: {
        value: '-start_at',
      },
      name_asc: {
        value: 'name',
      },
      name_desc: {
        value: '-name',
      },
    },
  }),
};
<commit_msg>Use uppercase for fair sort enum<commit_after>import { GraphQLEnumType } from 'graphql';

export default {
  type: new GraphQLEnumType({
    name: 'FairSorts',
    values: {
      CREATED_AT_ASC: {
        value: 'created_at',
      },
      CREATED_AT_DESC: {
        value: '-created_at',
      },
      START_AT_ASC: {
        value: 'start_at',
      },
      START_AT_DESC: {
        value: '-start_at',
      },
      NAME_ASC: {
        value: 'name',
      },
      NAME_DESC: {
        value: '-name',
      },
    },
  }),
};
<|endoftext|>


<commit_before>import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import Components from './../../components';

const styles = StyleSheet.create({
  base: {
    padding: 24
  },
  name: {
    fontSize: 24
  },
  header: {
    flexWrap: 'wrap',
    flexDirection: 'row'
  },
});

class ClazzScreen extends Components.PyxisComponent {
  static navigationOptions = {
    title: 'Turma'
  };

  get graduationClass() {
    return this.props.navigation.state.params.graduationClass;
  }

  constructor(props) {
    super(props);

    const { state } = this.props.navigation;

    this.state = {
      name: state.params ? state.params.name : '',
      graduationSemesters: []
    };
  }

  async componentDidMount() {
    const graduationSemesters = await this.services.graduationSemestersRepository.all({
      graduation_class_id: this.graduationClass.id
    });

    this.setState({ graduationSemesters });
  }

  navigateToSemester(graduationSemester) {
    this.navigate('Semester', { graduationSemester });
  }

  async remove() {
    try {
      const institute = await this.services.graduationClassesRepository.destroy(this.graduationClass);

      Alert.alert('Turma removida com sucesso!');
      this.goBack();
    } catch (err) {
      Alert.alert('Ops..', err.message);
    }
  }

  render() {
    return (
      <View style={styles.base}>
        <View>
          <Text style={styles.name}>{this.state.name}</Text>
          <View style={styles.header}>
            <Components.PButton title="Excluir" onPress={() => this.remove()}></Components.PButton>
          </View>
        </View>
        <View>
          {
            this.state.graduationSemesters.map(graduationSemester => {
              return (
                <Components.PButton
                  key={graduationSemester.id}
                  title={`Semestre ${graduationSemester.number}`}
                  onPress={() => this.navigateToSemester(graduationSemester)}>
                </Components.PButton>
              )
            })
          }
        </View>
        <Components.PButton title="Voltar" onPress={() => this.goBack()}></Components.PButton>
      </View>
    );
  }
}

export default ClazzScreen;<commit_msg>clazz title<commit_after>import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import Components from './../../components';

const styles = StyleSheet.create({
  base: {
    padding: 24
  },
  name: {
    fontSize: 24
  },
  header: {
    flexWrap: 'wrap',
    flexDirection: 'row'
  },
});

class ClazzScreen extends Components.PyxisComponent {
  static navigationOptions = {
    title: 'Turma'
  };

  get graduationClass() {
    return this.props.navigation.state.params.graduationClass;
  }

  constructor(props) {
    super(props);

    const { state } = this.props.navigation;

    this.state = {
      name: `Turma ${this.graduationClass.year}`,
      graduationSemesters: []
    };
  }

  async componentDidMount() {
    const graduationSemesters = await this.services.graduationSemestersRepository.all({
      graduation_class_id: this.graduationClass.id
    });

    this.setState({ graduationSemesters });
  }

  navigateToSemester(graduationSemester) {
    this.navigate('Semester', { graduationSemester });
  }

  async remove() {
    try {
      const institute = await this.services.graduationClassesRepository.destroy(this.graduationClass);

      Alert.alert('Turma removida com sucesso!');
      this.goBack();
    } catch (err) {
      Alert.alert('Ops..', err.message);
    }
  }

  render() {
    return (
      <View style={styles.base}>
        <View>
          <Text style={styles.name}>{this.state.name}</Text>
          <View style={styles.header}>
            <Components.PButton title="Excluir" onPress={() => this.remove()}></Components.PButton>
          </View>
        </View>
        <View>
          {
            this.state.graduationSemesters.map(graduationSemester => {
              return (
                <Components.PButton
                  key={graduationSemester.id}
                  title={`Semestre ${graduationSemester.number}`}
                  onPress={() => this.navigateToSemester(graduationSemester)}>
                </Components.PButton>
              )
            })
          }
        </View>
        <Components.PButton title="Voltar" onPress={() => this.goBack()}></Components.PButton>
      </View>
    );
  }
}

export default ClazzScreen;<|endoftext|>