Data Model to represent Flat and Variable rate - sql

I am designing a database for an app to sell parking spot use. Customer can order n number of uses of parking spot uses or pay a flat rate and use it for monthly/weekly or yearly. They can do mix of those also. Like they can buy 9 parking spot uses and later decide they will pay for the whole month - in which case their charges are kind of pro-rated.
For this, I have a Customer table, an Order Table and then an order type table. However, I am having a slightly hard time with the order-type table.
Can some one please shed light on how to model the rate and get available spot-uses for a customer?

Related

How to make a SQL table of formulas?

I'm have a MS SQL database for storing raw data on utility usage (electric, water, and gas), which I have implemented to compile data from four disparate automated collection systems. The ultimate goal is to generate invoices from this data.
Different customers have one of a dozen different rate structures, which all may-or-may-not use a non-linear function to calculate cost per usage based on peak demand and total usage.
It is not unheard of for a particular customer to change from one rate structure to another, or for the rate calculation for a particular rate class to change from year to year, so I would like to put these formulas into new tables within my database where they can be easily referenced and modified.
Ideally, I would want to run one of these dynamic functions as part of a query without relying on the front-end having to do them, but I have no idea how that would work.
By request, an example formula of the type I am talking about:
All current customer with Electricity Rate Structure A pay $0.005/kW-hr for the first 2,000 kW-hr consumed, $0.004/kW-hr for 2,000-15,000 kW-hr, and $0.003/kW-hr for all consumption above 15,000kW-hr. Additionally, any customer who has higher than 50kW demand will be subject to a $0.002/kW-hr surcharge on all consumption. The values for these coefficients, thresholds, the number of thresholds, and whether or not the customer even gets charged for peak demand can and do change from year to year and from rate structure to rate structure.
The formula for this (if I was programming it) would be:
min(sum(usage),2000)*.005+min(min(sum(usage)-2000,0),15000)*.004 + min(sum(usage)-15000,0)*.002 + (max(usage)>50)*sum(usage)*.002

Payroll, OpenERP 7, U.S. payroll taxes

I have searched and searched but to no avail... has anybody created a payroll module for a U.S. based company? It seems that most of what I've seen is that companies are using payroll companies to process their payroll, but I haven't found anybody using OpenERP 7 for hourly employees with the U.S. tax system (it's not a flat tax rate).
It seems like what I may have to do, is create tax table in PostgresQL for federal, state, and local taxes, then reference those tables in the deduction calculation. I read one article on using the vendors/ or suppliers module and implementing a tax structure from that, but then again, those are still flat rates. I have to believe someone else has done this for the U.S. payroll system, and probably done it better than I could as I am fairly new to OpenERP.
I am in the process of doing something similar for LedgerSMB. The thing is that doing this on an open source model is extremely painful business-model-wise. I am working on solutions to that part but that's outside the scope of your question.
In general many US taxes are set up in marginal rates with certain minimums and maximums. For example income tax withholding is a set of marginal rates within tax brackets. Same with FICA and FUMA, but FICA taxes are capped at a certain level, so a simple tax table with rates, minimums, maximums, etc. and then a way of handling deductions to determine the correct line may be sufficient.
But users of most open source ERP's use third party services for payroll.
I have worked in an ERP. How we did is just calculate the FIT in yearly for all the employee and subtract the withholding amount with multiples.
FIT => Taxable Wages Yearly - (No.of withholding(Exemption))
Do the process as per the revision based on single or married only for annually. No need to update all the tables.
Then,
Divided it based on the frequency from the employee table information
EX:
for monthly : FIT/12
for daily : FIT/365
For SIT you have to use based on the document in the state usine case function.

Best way to structure table for commission reports

I want to have a table that will track all the commissions we are due from our wireless sales. Each plan pays a different Commission, not a problem. We do our reconciliation as sometimes the carriers don't pay (they may miss a line or 2).
The problem occurs when the carriers change how much they pay for the commissions. We want to be able to go back and see that there was 4 lines not paid for in January at commission rate x. but Feb the same types of plans were sold but their commission rates were x-10.
If I change the rate in the commission table for the plan, when i go back to pull the data from the January report I will get incorrect commission rates.
I have a table for sales set up with a date stamp so I was thinking i can cross reference that somehow.
Hope someone followed this.
I am looking for the best way to structure this.
You should "STAMP" the record with the commission rate. You could either stamp the actual rate into every record... or you could keep a commission ID and put that into each record.

Have 2 separate tables or an additional field in 1 table?

I am making a small personal application regarding my trade of shares of various companies.
The actions can be selling shares of a company or buying. Therefore, the details to be saved in both cases would be:
Number of Shares
Average Price
Would it be better to use separate tables for "buy" and "sell" or just use one table for "trade" and keep a field that demarcates "buy" from "sell"?
Definitely the latter case - one table, simple one field (boolean) defining whether it's selling or buying. You should define tables by entities, not by actions taken on them.
This is actually a tricky one. The table you're talking about is basically a trade table, detailing all your buys and sells.
In that sense, you would think it would make sense to have both buys and sells in a single table.
However, in many jurisdictions, there is extra information for a sell order. That piece of information is which buy order to offset it against (for capital gains or profit purposes). While this is not necessary in a strict first-bought, first-sold (FBFS) environment, that's by no means the only possibility.
For example, under Australian law, you can actually offset a sale against your most recent purchase, as long as you have the rationale written down in clear language before-hand. Even though my company follow FBFS, I am allowed to receive bonus issues or supplemental shares which I can then sell immediately. These are offset against the most recent shares bought, not ones I've held for X number of years (this is often handy to minimise taxes payable).
If you follow a strict FBFS, then you don't need that extra information and your trades are symmetrical. Even where they're not, I've implemented it in one table with the extra information, useless for buy orders of course. That seemed the easiest way to go.
You could do it as two asymmetrical tables but that makes queries a bit more problematic since you often need to pull data from both tables. My advice is to stick with a single table with the extra information if needed.
I would also never store the average price. I prefer the quantity, the price per share and the brokerage costs. Every other figure can be calculated from those three, for example:
AvgPrice = (Brokerage + SharePrice * ShareQuant) / ShareQuant
but it's sometimes impossible to work backwards from just the average price, since you don't know what the brokerage was.
And I wouldn't have a boolean for buy/sell, it's just as easy to use negative numbers for the sell orders and it makes balance-sheet-type calculations a lot easier since you just sum values irrespective of the order type instead of needing to negate some of them depending on that order type.
Update: If, as you seem to indicate, you're only going to store aggregate information for each company, I would go for the following:
Companies:
CompanyId primary key
CompanyCode indexed
CompanyName
CompanyBuyQuant
CompanyBuyAvgPrice
CompanySellQuant
CompanySellAvgPrice
then you update the individual columns depending on whether it's a buy or sell. You don't need a separate row for the buy/sell stuff. When the company is first added, both quantities and prices are set to 0.
Your entity is now the company so this makes more sense. One thing you may want to consider is to store the aggregate values of shares bought and sold rather than the average buy and sell prices. That will simplify your update calculations and you can still easily get the averages by dividing the aggregate by the quantity.
So, the following table:
Companies:
CompanyId primary key
CompanyCode indexed
CompanyName
CompanyBuyQuant
CompanyBuyValue
CompanySellQuant
CompanySellValue
When adding a company, set all quanities and values to 0,
When buying M shares at N dollars each, add M to CompanyBuyQuant and N * M to CompanyBuyValue.
When selling M shares at N dollars each, add M to CompanySellQuant and N * M to CompanySellValue.
Get average buy price as CompanyBuyValue / CompanyBuyQuant.
Get average sell price as CompanySellValue / CompanySellQuant.
I'd go with a single table.
You can use negative quantities to indicate a sell. This is a fairly standard sort of indication. Subtraction is the same as adding a negative number!
One table. Each row/item is a trade, whether it's buy or sell.
Also, the aggregate of the quantity column will give you your current position. And cash too (-1 x quantity x price**) aggregated.
Buy or sell if inferred by the sign of the quantity: no need for separate column, unless you want to make a computed column derived from quantity.
**cash: When you sell (negative quantity) you get cash back (positive cash), hence -1 multiplier in case anyone wonders.
"Trade" can be ambiguous and it's not entirely clear to me what you want to do here. Are you interested in storing only your current position in each share or also the history of transactions that show how the position developed?
If you just want to record your holding ("position" might be a better word if you can be short) then I'd simply record for each share the number held. You mention average price, but I'd be cautious about that if you expect at any time to be able to sell part of a holding. What's the average price if you buy 100 at 50, 100 at 60 and sell 50 at 70?
Unless you expect your buy and sell transactions to number in the millions, I'd be more inclined to record each individual purchase or sale as a separate row in a single table and show the totals on demand as the derived results of a simple query.

track sales for week/month and find the best sellers

Lets say I have a website that sells widgets. I would like to do something similar to a tag cloud tracking best sellers. However, due to constantly aquiring and selling new widgets, I would like the sales to decay on a weekly time scale.
I'm having problems puzzling out how store and manipulate this data and have it decay properly over time so that something that was an ultra hot item 2 months ago but has since tapered off doesn't show on top of the list over the current best sellers. What would be the logic and database design for this?
Part 1: You have to have tables storing the data that you want to report on. Date/time sold is obviously key. If you need to work in decay factors, that raises the question: for how long is the data good and/or relevant? At what point in time as the "value" of the data decayed so much that you no longer care about it? When this point is reached for any given entry in the database, what do you do--keep it there but ensure it gets factored out of all subsequent computations? Or do you archive it--copy it to a "history" table and delete it from your main "sales" table? This is relevant, as it has to be factored into your decay formula (as well as your capacity planning, annual reporting requirements, and who knows what all else.)
Part 2: How much thought has been given to the decay formula that you want to use? There's no end of detail you can work into this. Options and factors to wade through include but are not limited to:
Simple age-based. Everything before the cutoff date counts as 1; everything after counts as 0. Sum and you're done.
What's the cutoff date? Precisly 14 days ago, to the minute? Midnight as of two Saturdays ago from (now)?
Does the cutoff date depend on the item that was sold? If some items are hot but some are not, does that affect things? What if you want to emphasize some things (the expensive/hard to sell ones) over others (the fluff you'd sell anyway)?
Simple age-based decays are trivial, but can be insufficient. Time to go nuclear.
Perhaps you want some kind of half-life, Dr. Freeman?
Everything sold is "worth" X, where the value of X is either always the same or varies on the item sold. And the value of X can decay over time.
Perhaps the value of X decreased by one-half every week. Or ever day. Or every month. Or (again) it may vary depending on the item.
If you do half-lifes, the value of X may never reach zero, and you're stuck tracking it forever (which is why I wrote "part 1" first). At some point, you probably need some kind of cut-off, some point after which you just don't care. X has decreased to one-tenth the intial value? Three months have passed? Either/or but the "range" depends on the inherent valud of the item?
My real point here is that how you calculate your decay rate is far more important than how you store it in the database. So long as the data's there that the formalu needs to do it's calculations, you should be good. And if you only need the last month's data to do this, you should perhaps move everything older to some kind of archive table.
you could just count the sales for the last month/week/whatever, and sort your items according to that.
if you want you can always add the total amonut of sold items into your formula.
You might have a table which contains the definitions of the pointing criterion (most sales, most this, most that, etc.), then for a given period, store in another table the attribution of points for each of the criterion defined in the criterion table. Obviously, a historical table will be used to store the score for each sellers for a given period or promotion, call it whatever you want.
Does it help a little?