PageRenderTime 20ms CodeModel.GetById 1ms app.highlight 16ms RepoModel.GetById 1ms app.codeStats 0ms

/public/JS/admin.js

https://bitbucket.org/sampepose/stl-food-rescue
JavaScript | 294 lines | 279 code | 15 blank | 0 comment | 23 complexity | 2a73e68278314e35a02129ed461f03cb MD5 | raw file
  1var getFirstDayOfWeek = function (d) {
  2    d = new Date(d);
  3    var day = d.getDay(),
  4        diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday
  5    return new Date(d.setDate(diff));
  6};
  7
  8var validateEmail = function (x) {
  9    var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum|us)\b/;
 10    return re.test(x);
 11};
 12
 13var FoodRunModel = Backbone.Model.extend({
 14    initialize:function () {
 15        if (this.get("total_volunteer_amount") == null) {
 16            this.set("total_volunteer_amount", 0);
 17        }
 18        if (this.get("total_car_amount") == null) {
 19            this.set("total_car_amount", 0);
 20        }
 21    },
 22    defaults:{
 23        food_run_id:"",
 24        pick_up_location:"",
 25        drop_off_location:"",
 26        time:"",
 27        total_volunteer_amount:"",
 28        total_car_amount:""
 29    },
 30    idAttribute:"food_run_id",
 31    urlRoot:'/data/foodrun/'
 32});
 33
 34var FoodRunCollection = Backbone.Collection.extend({
 35    model:FoodRunModel,
 36    url:"/data/foodrun/"
 37});
 38
 39var VolunteerModel = Backbone.Model.extend({
 40    defaults:{
 41        volunteer_id:"",
 42        first_name:"",
 43        last_name:"",
 44        phone_number:"",
 45        email:"",
 46        success:"0",
 47        failure:"0",
 48        last_delivery_date:"",
 49        sent_first_survey:"0"
 50    },
 51    idAttribute:"volunteer_id",
 52    urlRoot:'/data/volunteer/'
 53});
 54
 55var VolunteerCollection = Backbone.Collection.extend({
 56    model:VolunteerModel,
 57    url:"/data/volunteer/"
 58});
 59
 60var FoodRunColl = new FoodRunCollection();
 61var VolunteerColl = new VolunteerCollection();
 62
 63var VolunteerView = Backbone.View.extend({
 64    template:_.template($("#volunteer").html()),
 65    addNewVolunteer:function () {
 66        var firstName = $("#firstName").val();
 67        var lastName = $("#lastName").val();
 68        var phone = $("#phoneNumber").val();
 69        var email = $("#email").val();
 70        if (validateEmail(email)) {
 71            var n = new VolunteerModel({first_name: firstName, last_name:lastName, phone_number:phone,email:email});
 72            delete n.id;
 73            delete n.attributes.volunteer_id;
 74            delete n.attributes.last_delivery_date;
 75            n.save({}, {async:false});
 76            VolunteerColl.fetch();
 77            alert("New volunteer added!");
 78            $("#newVolunteer").val('');
 79        } else {
 80            alert("Not a valid email.");
 81        }
 82    },
 83    initialize:function () {
 84        this.collection.bind("reset", this.render, this);
 85        this.collection.bind("add", this.render, this);
 86        this.collection.bind("remove", this.render, this);
 87    },
 88    render:function () {
 89        $('#inject').html(this.template());//this.model.toJSON()
 90        for (var i = 0; i < this.collection.length; i++) {
 91            new VolunteerRowView({model:this.collection.at(i)}).render();
 92        }
 93        $("#newSubmit").click(this.addNewVolunteer);
 94    }
 95});
 96
 97var VolunteerRowView = Backbone.View.extend({
 98    template:_.template($("#volunteer-row").html()),
 99    events:{
100        "click":"remove"
101    },
102    render:function () {
103        $('#volunteerList').append(this.template(this.model.toJSON()));
104        this.setElement($("#" + this.model.id));
105    },
106    remove:function () {
107        var answer = confirm("Delete " + this.model.get("email") + "?");
108        if (answer) {
109            var res = prompt("Confirmation: Type \"confirm\" to delete the volunteer.");
110            if (res === "confirm") {
111                this.model.destroy();
112                this.unbind("click");
113                this.$el.remove();
114                alert("Volunteer removed!");
115            } else {
116                alert("Volunteer removal aborted!");
117            }
118        }
119
120    }
121});
122
123var FoodRunView = Backbone.View.extend({
124    template:_.template($("#foodrun").html()),
125    addNewFoodRun:function () {
126        var time = new XDate($("#date").val() + " " + $("#time").val()).toString("yyyy-MM-dd'T'HH:mm:ss'.000Z'");
127        if (!$("#date").val()) {
128            alert("Select a date!");
129            return;
130        }
131        var dropoff = $("#drop-off").val();
132        var pickup = $("#pick-up").val();
133        var n = new FoodRunModel({time:time, pick_up_location:pickup, drop_off_location:dropoff});
134        delete n.id;
135        delete n.attributes.food_run_id;
136        delete n.attributes.total_car_amount;
137        delete n.attributes.total_volunteer_amount;
138        n.save({}, {async:false});
139        FoodRunColl.fetch();
140        alert("New delivery added!");
141    },
142    initialize:function () {
143        this.collection.bind("reset", this.render, this);
144        this.collection.bind("add", this.render, this);
145        this.collection.bind("remove", this.render, this);
146    },
147    render:function () {
148        $('#inject').html(this.template());//this.model.toJSON()
149        for (var i = 0; i < this.collection.length; i++) {
150            new FoodRunRowView({model:this.collection.at(i)}).render();
151        }
152        $("#date").datepicker({ minDate:0, showWeek:true, firstDay:1});
153        $("#newSubmit").click(this.addNewFoodRun);
154    }
155});
156
157var FoodRunRowView = Backbone.View.extend({
158    template:_.template($("#foodRun-row").html()),
159    events:{
160        "click":"remove"
161    },
162    render:function () {
163        $('#foodRunList').append(this.template(this.model.toJSON()));
164        this.setElement($("#" + this.model.id));
165    },
166    remove:function () {
167        var answer = confirm("Delete this delivery (highly unrecommended...)?");
168        if (answer) {
169            var res = prompt("Confirmation: Type \"confirm\" to delete the delivery.");
170            if (res === "confirm") {
171                this.model.destroy();
172                this.unbind("click");
173                this.$el.remove();
174                alert("Delivery removed!");
175            } else {
176                alert("Delivery removal aborted!");
177            }
178        }
179    }
180});
181
182var InvoiceView = Backbone.View.extend({
183    week1:[],
184    week2:[],
185    template:_.template($("#invoice").html()),
186    initialize:function () {
187        var self = this;
188        $.ajax({
189            type:'GET',
190            url:'/data/foodrun/filter/week1',
191            dataType:'json',
192            timeout:10000,
193            async:false,
194            success:function (data) {
195                self.week1 = data;
196            },
197            error:function (xhr, type) {
198                alert('Ajax error!');
199            }
200        });
201        $.ajax({
202            type:'GET',
203            url:'/data/foodrun/filter/week2',
204            dataType:'json',
205            timeout:10000,
206            async:false,
207            success:function (data) {
208                self.week2 = data;
209            },
210            error:function (xhr, type) {
211                alert('Ajax error!');
212            }
213        });
214    },
215    render:function () {
216        $('#inject').html(this.template());
217        var day1 = new XDate(getFirstDayOfWeek(new Date().setHours(0, 0, 0, 0)), true);
218        $("#week1Header").html(day1.toString("MMM. d") + "-" + day1.clone().addDays(6).toString("MMM. d"));
219        day1.addWeeks(1);
220        $("#week2Header").html(day1.toString("MMM. d") + "-" + day1.addDays(6).toString("MMM. d"));
221        if (this.week1)
222            for (var i = 0; i < this.week1.length; i++) {
223                this.addOne(i, this.week1, "week1");
224            }
225        if (this.week2)
226            for (var i = 0; i < this.week2.length; i++) {
227                this.addOne(i, this.week2, "week2");
228            }
229    },
230    addOne:function (i, arr, el) {
231        var id = arr[i]['food_run_id'];
232        var containerTemp = _.template($("#invoice-foodrun-container").html());
233        $("#" + el).append(containerTemp({time:arr[i]['time'], drop_off_location:arr[i]['drop_off_location']}));
234        $.ajax({
235            type:'GET',
236            url:'/data/foodrun/' + id + '/invoice',
237            dataType:'json',
238            timeout:10000,
239            async:false,
240            success:function (data) {
241                if (data.length >= 1)
242                    for (var j = 0; j < data.length; j++) {
243                        new InvoiceFoodRunView({el:el, food_run_id:id, first_name:data[j]['first_name'],last_name:data[j]['last_name'], car_amount:data[j]['car_amount'], volunteer_amount:data[j]['volunteer_amount']}).render();
244                    }
245                else
246                    $('#' + el).append("No volunteers signed up.");
247            },
248            error:function (xhr, type) {
249                alert('Ajax error!');
250            }
251        });
252    }
253});
254
255var InvoiceFoodRunView = Backbone.View.extend({
256    template:_.template($("#invoice-foodrun").html()),
257    render:function () {
258        $('#' + this.options.el).append(this.template(this.options));
259    }
260});
261
262var AppRouter = Backbone.Router.extend({
263    routes:{
264        "":"changeContent",
265        "volunteer":"volunteerPage",
266        "foodrun":"foodRunPage",
267        "invoice":"invoicePage",
268        "*path":"error"
269    },
270    changeContent:function () {
271        var id = "#" + (Backbone.history.fragment == "" ? "homepage" : Backbone.history.fragment);
272        $("#inject").html(_.template($(id).html()));
273    },
274    volunteerPage:function () {
275        VolunteerColl.fetch({async:false});
276        new VolunteerView({collection:VolunteerColl}).render();
277    },
278    foodRunPage:function () {
279        FoodRunColl.fetch({async:false});
280        new FoodRunView({collection:FoodRunColl}).render();
281    },
282    invoicePage:function () {
283        new InvoiceView().render();
284    },
285    error:function () {
286        this.navigate("#");
287        this.changeContent();
288    }
289});
290
291$(document).ready(function () {
292    new AppRouter;
293    Backbone.history.start();
294});