Generate random resource ID's with prefix? - ruby-on-rails-3

I have a simple Rails 3 invoicing application with the following models:
Brand
Client
Invoice
A brand has many invoices, clients have many invoices and invoices belong to clients and brands. Basically the brand is the company creating the invoice, client is the recipient of the invoice and the invoice the the actual invoice.
I am trying to work out the best way of having a simple random reference number for each invoice that's prefixed by something unique per brand.
I'm thinking of adding a invoice_prefix to the brand table. Then the brands would each have a three digit prefix, such as DAN-.
What would be the best way of adding the brands prefix followed by a 5 digit random number to a column in the invoice table?
I'm open to suggestions of better ways of doing this!
The end result I would like is for each invoice to have a unique reference similar to DAN-98372.
I think the best way would be to add the prefix column to the brand table and then create an before_create action for invoices that inserts a random number after the brand prefix. I'm just not sure on the best way to do this.
before_create :generate_reference
private
def generate_reference
self.invoice_number = self.brand.prefix
end
The above code correctly pulls in the brand prefix, but I'm unsure how to add a random 5 digit number afterwards.
I think something like <%= rand(1000..9999) %> would work, but I'm not sure how to add that to the brand prefix in the before_create.
I'm not very familiar with after_create methods so any advice would be appreciated!

you can use
https://github.com/patdeegan/integer-obfuscator
or https://github.com/namick/obfuscate_id
that way you can hide how many invoices you really have and it will be unique

From the provided info, its a case of polymorphic association. refer http://guides.rubyonrails.org/association_basics.html.
In the code provided, u should call 'generate_reference' 'before_create' rather than 'after_create' since u want the assigned values to be saved. specifying 'after_create' will go infinite loop.

Generate random data resources
https://github.com/wemersonblend/fakejs

Related

How to create a temp boolean field with Django orm

Image I have following models:
class Product(models.Model):
name = models.CharField(max_length=20)
class Receipt(models.Model):
product = models.ForeignKey(Product)
user = models.ForeignKey(User)
I have an input list of product ids and a user. I want to query for each product, whether it's been purchased by this user. Notice I need a queryset with all exist products based on given input because there are other fields I need for each product even not purchased by this user, so I cannot use Product.objects.filter(receipt__user=user).
So can I create a temp Boolean field to present this property in one single query? I am using Django 1.8 and postgresql 9.3
Update requirements:To separate products into two groups. One is bought by this specific user, the other one is not. I don't think any given filter can implement this. This should be implement by creating a new temp field either by annotate or F expression.
I think, you need .annotate() expression as
from django.db.models.expressions import Case, When, Value
product_queryset = Product.objects.annotate(
is_purchased=Case(
When(receipt__user=current_user, then=Value('True')),
default=Value('False')
))
How to access the annotated field?
product_queryset.first().is_purchased
Thx for #JPG's answer.
I just realize except conditional expressions, there's another easy way to do it.
Just using prefetch_related will implement everything in two queries. Although it's double than conditional expressions, but it's still a considerable time complexity solution.
products = Product.objects.filter(id__in=[1,2,3,4,5]).prefetch_related ('receipt_set').all()
Then we can detect user for this product in Python by
for p in products:
print user in [receipt.user_id for receipt in p.purchase_set.all()]

Odoo 10 - How to retrieve associated stock_picking name (if such stock_picking exists) from account_invoice_line

I would like to include information about the specific delivery slip in which an invoice line was delivered or is going to be delivered.
Is it possible to retrieve "name" field from the "stock.picking" associated to a given "account_invoice_line"?
Which would be the easiest way to achieve that?
This code provides a new field for sale_order_line_ids in account_invoice_line:
class AccountInvoiceLine(models.Model):
_inherit = 'account.invoice.line'
sale_order_line_ids = fields.Many2many('sale.order.line', 'sale_order_line_invoice_rel', 'invoice_line_id', 'order_line_id', string='Sale Order Lines', readonly=True);
I would like to be able to get the stock_picking name for that specific account_invoice_line:
I see the following fields in tables:
Table procurement_order
Field: sale_line_id
Field: purchase_line_id
Also:
Table stock_move
Field: picking_id
Field: procurement_id
Field: purchase_line_id
So I need to go backwards but it seems feasible and not complex to get the picking_id.
How could this field be implemented in account_invoice_line model?
It's a little bit of a stab in the dark, but you ought to be able to use this or something very similar:
# Assuming `invoice_line_id` is an individual `account.invoice.line` record
invoice_line_id.sale_order_line_ids.mapped('procurement_id').mapped('move_ids').mapped('picking_id')
You can see in the ORM Documentation that mapped is used to get data for a record or recordset. It's extremely useful when you might have many lines and you want to gather data for all of them.
In this case, the above line would return a browse recordset of all stock.picking records linked to any of the Sales Order Lines belonging to that Invoice Line.
Note: It's possible you may get more data than you want from this, so you'll have to do the testing on your own to confirm it's only returning what you expect.

Databases design and primary key composed

I have a table named minibar_bill and i use it for keeping evidence of client's expenditure. I'm trying to build a hotel/pension system management.
I thought that i could make a table
Minibar_bill with (id_bill, id_minibar_product, id_client)
And i would like to add those info on an invoice based on bill_id...
How should i do it ?
I mean i want to have something like that:
Id_bill(1)
id_minibar_product(1,2,3)
id_client(123)
So first 3 records will be :
1, 1, 123
1, 2, 123
1, 3, 123
And i want the id_bill to be on invoice ... maybe i could switch id_product with id_bill
Where id_bill(1) - would be the first bill record in database
id_minibar_product(1,2,3) - would be product 1,2,3 which has been consumed by client
id_client(123) - client id which we use on invoice to collect data from Client table in order to print them on invoice( i will use C# for UI ).
What I have tried:
I've tried to make a db with field id_bill and id_product but i think it's a wrong approach since i made them a composed primary key and i cannot add them to foreign key in Invoice table.
Here are some suggestions for your design:
It's a good idea to name things descriptively, but if you create a table called Minibar_bill, that's going to be inconsistent and short sighted if you want to start charging in-room movies and in-room dining, services etc. to the room. I suggest you call it something more generic - remove Minibar from all of your table names.
You must never put comma separated values into a single field.
There are a million sales data models online, including, as already suggested, templates in MS Access. There's no point reinventing the wheel
I suggest you have something like this
Client A list of clients
Products A list of products you can be billed for (not just minibar)
Bill A client has zero or more bills (usually one)
BillLine A bill has zero ore more lines. Each line represents
One product being charged for on a bll
So Bill is the header. It's up to you whether you add a column indicating when / if it is invoiced, paid etc., or whether you want to create a seperate invoicing module.
With regards to this comment:
What i wish for is to link Invoice to minibar_bill in order to have the status on a single Invoice of all products from minibar which have been bought by a customer.
If you have a seperate invoice table you can write the BillID to it to link it.
I'm not sure if you understand that all this info exists across different tables, and when, for example, you print an invoice, you go and collect all the info from across the tables at that time.

OpenERP customers separation

Please I would like to know ho to separate customers in category, since we have two type of customers, the first group should only appear in crm->customers only and vice versa to avoid having a huge list of customers when searching.
My first attempt is to add a tag to different customers to separate them, for example the crm customers have the tag name Mass mailing is it correct to achieve this with tags ?? and my second question how to set default search keyword for example if I click on sales -> customers how to set the default value of search box to for example crmOnly tag thanks.
you can use "domain" where ever you want to have a such a separation.

Rails Custom Model Functions

I'm in a databases course and the instructor wants us to develop an e-commerce app. She said we can use any framework we like, and now that we're halfway through the semester she decided that Rails does too much and wants me to explicitly write my SQL queries.
So, what I'd like to do is to write my own functions and add them to the models to essentially duplicate already existing functionality (but with SQL that I wrote myself).
So the questions then become:
How do I execute manually created queries inside the model?
How do I stuff the results into an empty object that I can then return and work with inside the view?
Also, I'm aware of what terrible practice this is, I just don't want to start all over in PHP at this point.
I think, you should know 2-3 really necessary methods, to use it.
(assume we have at least 2 models, Order and User(customer for order))
For example, just to run query on your database use this:
Order.connection.execute("DELETE FROM orders WHERE id = '2')
to get number of objects from your database, the best way is use method "count_by_sql", it's scalable. I'm using it in my projects, where table has over 500 thousands records. All work to count application gives to database, and it did it much more efficient than app.
Order.count_by_sql("SELECT COUNT(DISTINCT o.user_id) FROM orders o")
this query gets number of all uniq users who has an order. we can "JOIN ON" tables, order results using "ORDER BY" and group results.
and the most often use method: find_by_sql
Order.find_by_sql("SELECT * FROM orders")
it returns to you an array with ruby objects.
Lets say you have a purchase
class Purchase < ActiveRecord:Base
def Purchase.find(id)
Purchase.find_by_sql(["Select * from purchases where id=?", id])
end
end
Maybe you want the products for a particular purchase. You can manually define the purchased_items in your Purchase model.
class Purchase < ActiveRecord:Base
def purchased_items
PurchasedItem.find_by_sql(["Select * from purchased_items where purchase_id=?",self.id])
end
end
So for example, in your controller where you now want to get the purchased items for a particular purchase you can now do this
#purchase = Purchase.find(params[:id])
#purchased_items = #purchase.purchased_items
If you need a more raw connection to the database, you can look into ActiveRecord:Base.connection.execute(sql)