Modeling objects with no id in ember data - ember.js

I am building a dashboard application for an accounting department.
The user will select a month, and see all the companies that meet certain criteria in that month. The routes will be
/:month_id a summary page
/:month_id/companies more details about each company
/:month_id/companies/:company_id all details about a single company
Ideally I'd have a month model which hasMany company models. The only problem is, companies will show up in multiple months.
Correct me if I'm wrong, but doesn't this mean that if a company is already in the store, when a new month is requested, it will take that company's data from the store instead of from the server? The data will be different for each month, so this wouldn't work for me.
I suppose in this application each company's id is really their normal, integer id plus the selected month. So one way around this would be to give each company an id like '15-Mar-2013'.
Alternatively, I could just pass each month's companies data through raw and do transformations on the plain array. The problem with this, though, is that I'll have to calculate aggregates on companies (in addition to the entire month), and it would be very nice to keep those two things separate. If I had a completely separate Company model, I could just go to town within the model:
App.Company = DS.Model.extend({
month: DS.belongsTo('App.Month'),
name: DS.attr('string'),
contracts: DS.hasMany('App.Contract'),
totalRevenue: function() {
return this.get('contracts')
.filterProperty('type', 'newSetup')
.getEach('feeChange').reduce(function(accum, item) {
return accum + item;
}, 0);
}.property('contracts.#each.feeChange'),
...additional aggregation functions
});
What do you think?

It doesn't make any sense to me that months own companies, which is what your month[1]->[N]company relationship indicates.
What you want to say is that you're looking for all companies that have certain criteria that occur within a month. The month chosen is just part of the search criteria.

Related

I need help properly implementing a booking scheduler and availability in Django

This question has been asked many times before on StackOverflow and in the Django forums, but none of the answers I've found are appropriate or complete enough for my situation.
First, the brief:
I'm creating a web application for a car rental business. In addition to helping them organize and centralize their fleet, it will also help them collect orders directly from customers. As with most rentals, the logistics of it all can be somewhat confusing.
Someone may place an order for a car today (December 12th) but actually take the car over the Christmas to New Year's period.
A renter may borrow a car for just two days, and then extend the booking at the last minute. When this happens (often very frequently), the business usually has to scramble to find another one for a different customer who was scheduled to get that car the next day.
Adding to that, an individual car can only be rented to one client at a time, so it can't have multiple bookings for the same period.
Most answers advocate for a simple approach that looks like this:
models.py
class Booking(models.Model):
car = models.ForeignKey(Car, ...)
start_date = models.dateField(...)
end_date = models.dateField(...)
is_available = models.booleanField(default=True)
forms.py
import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from . import models
class PlaceOrderForm(forms.Form):
"""Initial order forms for customers."""
start_date = forms.DateField(help_text='When do you want the car?')
end_date = forms.DateField(help_text='When will you return the car?')
def clean_data(self, date):
data = self.cleaned_data(date)
# Check that start date is not in the past
if data < datetime.date.today():
raise ValidationError(_('Invalid date: Start in past.'))
# Ensure that start date is not today (to avoid last_minute bookings.)
if data == datetime.date.today():
raise ValidationError(_('Invalid date: Please reserve your car at least 24 hours in advance.'))
return data
cleaned_start_date = clean_data(start_date)
cleaned_end_date = clean_data(end_date)
('_' is for )
The booking has a start_date and an end_date. When a current date is within the start_date and end_date, the car is marked as unavailable. If the boolean field is_available (not represented in forms.py above) is set to "False", the car is unavailable completely.
Again, because of the unique nature of car rentals, this may be a problem. Some people book a car for six months, and others book it for two days. If someone wants a long-term rental but there's another short interlude during their expected duration, this validation would prevent them from placing the order completely!
But this is a problem: Going back to the rental model, someone may be booking a car in the future. A car that's unavailable now should still be able to be reserved for a future date.
Adding to that, an individual car can only be rented to one person at a time, so it can't have multiple bookings for the same period. Again, because of the unique nature of car rentals, this may be a problem. Some people book a car for six months, and others book it for two days. If someone wants a long-term rental but there's another short interlude during their expected duration, this validation would prevent them from placing the order completely!
So if a conflict arises, rather than blocking the booking entirely (which, again, would be a bad UX decision), it should notify the business so they can assign another car and plan ahead.
Other clients should not be able to book it for the time in which it is borrowed, but they should be able to book it for other times when it is free.
So if someone places an order now for, let's say the 24-31st of December. Those days should be blocked off. However, another person should be able to book it from today to the 23rd, and from the 31st onwards. And if the person renting it should extend, it should notify the rental business so they can assign another car to the user well in advance.
Possible idea to move forward
The core assumption in all those answers is that the booking unavailability has to be handled in Django itself, in the backend. However, I'm building this project with REST framework, and will use a Js based front-end (currently learning Javascript for this purpose).
I think that this would be better handled in a more holistic way with the in-built form validation and save functions.
The workflow would go something like this:
The User selects a car and selects the start and end dates from a drop-down calendar on the website.
The form will then check to see if the absolute basic checks (can't book a car in the past) are fine. If those work, then the order is placed and saved in the database.
If there's a scheduling conflict, the order is not blocked, but passed to the business that can assign them a different car for the period. (Generally, people don't care much for receiving particular cars--mostly the price, space and the fuel economy. Everything else is interchangeable.
Once that happens, the deposit can be collected, and the order can be set in the system.
Anyhow, that's my preliminary idea that would bring together the best of all worlds
and create a great experience for both the business and customer.
So my question is: How could this actually be set up? What would need to be on the front-end and what would go in the back-end? I'm learning programming as I go, so this may be simple, but I've been struggling with this for a week, I would appreciate any help on this!
Thanks!
Sounds like you have two processes - the customer order and the car assignment. You need to plan out your data structure and then your process flow. This will help you get things straight before you start.
Models
Using (Brackets) for foreign keys, Customer_order collects things like:
Customer(User)
desired_start_date
desired_end_date
car_type - this could be many fields
A car model
car_type
rental (many to many Rental with through table Rental)
A rental model
car (Car)
customer_order(Customer_order)
start_date
end_date
We have kept the rental model with its own start and end dates as the user may change their desired period but it shouldn't change the rental dates without checking if others exist in that time period for that car.
So the flow should go:
user passes js validation and form submitted to backend
backend checks for car availability based on type and dates
if available, creates rental
if not available, alert user and passes to staff
if a user changes a rental period (via an edit screen for existing customer_orders)
backend checks for same car availability based on existing rentals
if not available, alert user and pass to staff
You'd also create a staff only view, that lists customer_orders that can't be matched (without rental models) along with cars of the requested type that don't have rentals for that period.
Seeing as you have that view, it strikes me your backend process could use something similar to also look for and assign a different car of the same type automatically if you wanted to extend the availability check process, notifying staff it has occurred, while only referring back to staff if that type of car is unavailable.
Actually programming all this is left as an exercise for the reader.

Data modelling one to many relationship in DynamoDB

I am working in Dynamo DB for the first time . My assignment is Game Management System where it has 3 entities Game , Tournament and User. The relationship between each entity is.
1 Game has multiple users
1 User has multiple tournaments
1 Game has multiple tournaments
I have identified the following access patterns. User can login via gameId and userId . Be it anycase we should retrieve complete Game details hence the data in dynamoDb is stored as below.
Fetch GameDetails by GameId
Fetch GameDetails by userId
challenge here is we will have either GameId or UserId at a time. I should send back complete GameDetail object . GameDetail object should be maintained across the GameId . For example If user logs in using userId 101 and play a game "abc" then all the items with gameId should be updated .
Considering such scenario how to data model DynamoDb . I thought having gameId as partition key and userId as sort key and GSI with inverted index (userId as partitionkey and gameId as sortKey)
As I mentioned earlier the challenge is we will have either GameId or userId at a time in which case we cannot update without sort key . Experienced people please help .
There are three DynamoDB concepts that I think will help here.
The first relates to granularity of Items. In DynamoDB I like my individual Items to be fine-grained. Then if I need to assemble a more complex object, I can pull together a number of fine-grained Items. The advantage is that I can then pull properties of the fine-grained object out into attributes, and I can make Global Secondary Indexes to create different views of the object.
The second relates to immutability. In DynamoDB I like to use Items to represent true facts that have happened and will never change. Then if I need to determine the state of the system, I can pull together all of those immutable events, and perform computations on them. The advantage is that I don’t have to worry about conflicting updates to an Item or to worry about losing historical information.
The third relates to pulling complexity out of the database and into the application. In DynamoDB I like to move computations involving multiple Items out of the database, and perform them within my application. There is not much cost to doing so, since the amount of data for one domain object, like a game, an employee, or an order, is often manageable. The advantage is less complexity in the data model, and fewer opportunities for complicated operations performed within the database where they could affect its performance.
These relate to your system as follows.
For granularity, I would model the Score, not the Game. Assemble the state of the Game by pulling in all the Scores for all the Tournaments within the Game and doing computations on them.
For immutability, record a Score for a particular Tournament as an immutable event. Then you don’t have to worry about updating existing Items when a Score is determined for a Tournament. If the Score has to change, and you want to store the Score between changes, then record Points instead of Scores, and similar logic applies. Once a Point is scored, it forever has been scored and won’t change (but you can score negative Points), and you can determine the score for a Tournament by pulling together all the Point events.
For pulling out complexity, you will be performing things like determining the winner of a Game using computations in your application, either front-end or back-end, using a potentially large collection of Scores. This is generally fine, since compute resources and browsers can usually handle computations on data sets of the size that would be expected for a Game.
I have one note on terminology. In English usage in the United States, you would call a collection of games a tournament. It may be that in other parts of the world, or for particular sports I don't know about, a game is a collection of tournaments. Either way, we effectively have “Big Competitions” and “Little Competitions,” where a Big Competition is a collection of Little Competitions. In your post, you’re using Big Competition for Game, and Little Competition for Tournament. In my suggested table design below, I’m using generic terms BigComp to abbreviate “Big Competition” and LittleComp to abbreviate “Little Competition.” I’m calling this out, and using my generic terms, in case others are confused as I was by the notion of a game as a collection of tournaments.
I would model your system with the following Item types and Global Secondary Indexes.
Constructions like bigcomp#<BigComp Id> mean the literal string bigcomp# followed by a Game Id like 4839457. I do this so that I can use a PK for different types of Items without worrying about collisions in name.
Item type: Score
PK: bigcomp#<BigComp Id>
SK: littlecomp#<LittleComp Id>#userid#<User Id>#score
Attribute: ScoreUserId
Attribute: ScoreValue
**Note: User Id and ScoreUserId are repetitions of the same info, the User Id.**
Global Secondary Index UserScores
PK: ScoreUserId
Projections: All attributes
Item type: Login
PK: userid#<User Id>
SK: <sortable date and time string>
**Note: This allows you to show the last login time.**
Item type: BigComp Enrollment
PK: bigcomp#<BigComp Id>
SK: bigcompenrollment
Attribute: BigCompEnrolledUserId
**Note: The attribute is the User Id of the user who has joined this BigComp.**
GlobalSecondaryIndex BigCompEnrolledUserId-BigComp
PK: BigCompEnrolledUserId
Projections: All attributes
Item type: LittleComp Enrollment
PK: bigcomp#<BigComp Id>
SK: littlecompenrollment#littlecomp#<LittleComp Id>
Attribute: LittleCompEnrolledUserId
GlobalSecondaryIndex LittleCompEnrolledUserId-LittleComp
PK: LittleCompEnrolledUserId
Projections: All attributes
Here’s how some access patterns would work. I’ll use the convention of a Big Competition being a Game, and a Little Competition being a Tournament, since that’s how it is in the original post.
User joins a Game. Write Item of type BigComp Enrollment.
User joins a Tournament. Write Item of type LittleComp Enrollment.
Another User joins the Tournament. Write another Item of type LittleComp Enrollment.
The first User logs out, and then wants to re-join the Tournament based on the Game Id. Query PK: bigcomp#<BigComp Id>, SK: begins_with(littlecompenrollment#), with BigComp Id set to the known Game Id, and you’ll have a collection of all the Tournaments for this Game, and their Users. The application will have to handle authentication, to make sure the User is who they say they are.
Two Users compete in their Tournament, each getting a Score. Write two Items of type Score.
Who won a given Tournament? Query all the Score Items for the specific Game (BigComp) and Tournament (LittleComp).
Who won the Game? Get all the Scores for the specific Game (BigComp). Use logic in your application to figure out the winner.

How to add fields dynamically to a form? - Implementing a django app to track order status

After a basic introduction to Python thanks to an edX course and a chat with a friend who told me about Django, I thought I could implement a solution for my laboratory. My goal is to keep track of every reagent order made by everyone of us researchers to the suppliers.
After one month I have a pretty decent version of it which I'm very proud of (I also have to thank a lot of StackOverFlow questions that helped me). Nonetheless, there's one requirement of the ordering flow that I haven't been able to translate to the Django app. Let me explain:
Users have a form to anotate the reagent (one per form) they need, and then it is passed to the corresponding manufacturer for them to send us an invoice. It's convenient that each invoice has several products, but they all have to: a) be sold by the same manufacturer, b) be sent to the same location and c) be charged to the same bank account (it's actually more complicated, but this will suffice for the explanation).
According to that, administrators of the app could process different orders by different users and merge them together as long as they meet the three requirements.
How would you implement this into the app regarding tables and relationships?
What I have now is an Order Model and an Order Form which has different CharFields regarding information of the product (name, reference, etc.), and then the sending direction and the bank account (which are ForeingKeys).
When the administrators (administratives) process the orders, they asign several of them that meet the requirements to an invoice, and then the problem comes: all the data has to be filled repeatedly for each of the orders.
The inmediate solution for this would be to create a Products Model and then each Order instance could have various products as long as they meet the three requirements, but this presents two problems:
1) The products table is gonna be very difficult to populate properly. Users are not gonna be concise about references and important data.
2) We would still have different Orders that could be merged into the same invoice.
I thought maybe I could let the users add fields dynamically to the Order model (adding product 1, product 2, product 3). I read about formsets, but they repeat whole Forms as far as I understood, and I would just need to repeat fields. Anyway, that would solve the first point, but not the second.
Any suggestions?
Thanks, and sorry for the long block!

Backend data vs ember presentation models

The problem arises from the fact that I have some data in backend which when presented has to be formed in different way than how they are stored, or at least this is my conception after reading some guides and docs about emberjs so I want to know what would an ember profi do.
To be concrete, on the backend I have a data structure which presents days (with full date like 2014-07-16) and have a bunch of data attached to each day.
On the client however I need to present the data structured under years, weeks and then day.
So I setup some nested route like this:
WorkTime.Router.map(function() {
this.resource('year', {
path: '/:year'
},
function() {
this.resource('week', {
path: '/:week'
},
function() {
this.resource('day', {
path: '/:day'
},
function() {
});
});
});
});
This implies the right structure that I need for the sake of presentation. Now the question is how should I approach toward needed models?
One solution that I can think of is to define the models for year, week and day. The first two are not stored on server (as they are really presentation only) and day has some computed attributes (like year and weeknumber) which then gives the right binding to year and week models. This however means that each time application starts, has to receive the days' records, and generate local records for year and week.
Im not sure if this is even supported in ember.
Is this a proper approach? would an ember profi do it?
Just to note: I'm using ember 1.6.0 with ember data 1.0.0 beta 8.
I have a data structure which presents days (with full date like 2014-07-16) and have a bunch of data attached to each day
Let's say we are storing log entries. I would only have one log DS model, one server API /logs and one Ember Router & Controller. Server will return records for all dates in one large list (each day entry is a separate object).
Then you can narrow your search for specific period of time by adding some filter refinement on a controller, or, even better by using Query Params (please note that this is still beta).
After you have loaded correct entries you can display them, grouping by day. Have a look at this answer regarding grouping results: Ember.js Grouping Results
— From discussion on Ember Forum http://discuss.emberjs.com/t/help-me-to-get-the-right-mindset/5919

DB Structure for a shopping cart

I like to develop a shopping cart website with multiple products.
(ex.: mobile phone, furniture etc.,)
here mobile phone specification will cover
size of display
memory
operating system
camera etc.,
but for furniture - its specification is entirely different from above electronic product.
type of wood
color
weight
shape
glass or mat finish etc.,
My question is: how to handle a common database-table for product specification ?
each & every category of product & its spec will be differ - so how to have a common
table ProductSpecificationTable ?
I searched many site including google.. but cant able to get the perfect soultion.
Please help me to move to next step.
Ask yourself the question: How can I accomplish this kind of database? First of all you need products.. Every product has to be in some kind of category and every category has to have his own properties. So, you've to create a product table with unique id and every product needs a category id. At this moment it is time to link from your property table to your category table(by id) and to set the values you need a 'property_value' table.
**table:** **id**
product --> category id
property --> category_id
property_value --> property_id
I hope you will understand my explanation otherwise just ask :)
You can add 1 more table to accomplish that. Table that contains cat_id, product_id and the property. That is a many to many relationship. I believe this way you can accomplish thst.
You can achieve this with a single table within a database but that will complicate the CRUD operations over the table. So I will recommend you to create one database like ‘Inventory’ which can have multiple tables (one table for each of the Product Type).
First Table could be list of Product Types you have (mobile phones, accessories, furniture):
You can use this table to populate your list of items available. Here the column _table_name will contain the actual name of the Tables.
Then for each of the product you can have different tables with different number of columns:
Table for Product Type Mobile Phones:
Table for Product Type Furniture:
I hope this will help.