Navigation Menu change from Quotation to Sales Order in odoo10 - action

I want to change status of Navigation menu from quotation to sale order when sales confirm. For this i tried to call sale order menu action into action_confirm. but didn't get up-to result.
also image attached below:
My action_confirm method code is here:
#api.multi
def action_confirm(self):
if self.partner_id.pet_names:
for record in self.partner_id.pet_names:
if record == self.pet_names_info:
if self.order_line:
for s in self.order_line:
if s.product_id:
if self.ser1 or self.ind_ser1:
self.confirm_rental_service() # Rental service
self.confirm_rental_service_history() # Rental history maintain
break
res = super(sale_order_pet, self).action_confirm()
if res:
self.confirm_email_template()
action = self.env.ref('sale.action_orders').read()[0]
action['res_id'] = self.ids[0]
action['name'] = 'Sales Order'
return action
else:
raise ValidationError("Please Add Products in Order Lines")

Related

Django Not Creating Model Objects After Retrieving Data From External Payment API

I created an app for table ordering (basically like an ecommerce website) that has 3 models:
class Dish(model.Models):
some other fields()
class Cart(model.Models):
customer = models.ForeignKey(User)
session_key = models.CharField(max_length=40)
dish = models.ForeignKey(Dish)
order = models.ForeignKey(Order)
paid = models.CharField(max_length = 3, default = "No")
some other fields()
class Order(model.Models):
customer = models.ForeignKey(User)
session_key = models.CharField(max_length=40)
some other fields()
All the items that are added to the cart have a default field of "No", that turn to "Yes" once the payment has been done. If the user is authenticated, it populates the customer field for the cart item, otherwise it creates a session key with the following function:
def create_session(request):
session = request.session
if not session.session_key:
session.create()
return session
To process the payment, the application uses Square (similar to stripe). The following view takes care of it:
from square.client import Client
def square_payment(request):
# this view receives the necessary data such as order total and token via a POST request.
# I have omitted these details for the simplicity of the example
if request.method == "POST":
#create a client object to handle payment through Square
client = Client(access_token= "some access token",environment= "production")
body = {}
body['amount_money']['amount'] = "some amount"
# execute payment with the amount specified in body
result = client.payments.create_payment(body = body)
if result.is_success():
if request.user.is_authenticated:
order_object = Order.objects.create(customer = request.user)
Cart.objects.filter(customer = request.user, paid = "No").update(paid = "Yes")
else:
session = create_session(request)
order_object = Order.objects.create(session_key = session.session_key)
Cart.objects.filter(session_key = session.session_key, paid = "No").update(paid = "Yes")
elif result.is_error():
return JsonResponse({"Message":"Error"})
I tested everything many times and seemed to work fine until I tested it at a restaurant and the results that I got were quite mixed. The results were as follow:
#1) Everything worked as expected, the payment got through, the Order object was created and all cart items associated to that order were updated to paid = "Yes".
#2) The payment got through, the order object was created but the cart items were not updated to paid "Yes".
#3) The payment got through, but neither the Order object was created nor the cart items updated to paid = "Yes".
Not entirely sure what the issue is, but I would really appreciate it if someone could point me in the right direction.

In django i want to change the date from views

I want to update the date from the backend views in django how can i did that here are my views where i want to do this
explaining what i exactly want to achive i am building a crm where clients suppose to pay monthly or quaterly depends on their plan i have given a button at dashbord which triggers this function and redirect to homepage in this function if the user date month came then this function is suppose to generate the bills which is fetching in the homepage and show outstanding amount what wrong happen with this idea everytime pressing the button it will genertate duplicate bills adding in revenue to stops this i add a variable is eligible which i thought the user will change it manually but then i feel it is more good to update the date
def refresh_dashboard(request):
date = datetime.datetime.now().strftime ("%Y%m%d")
m = datetime.date.today()
print(f"the date is {m}")
customer = Customer.objects.all()
for i in customer:
# print(i.eligible)
period = i.next_payment.strftime("%Y%m%d")
if period <= date and i.eligible == True:
x = Bill.objects.create(name = i.name,status ="unpaid",price = i.recuring_amount,generate_date = date)
x.save()
obj = i
# obj.next_payment.strftime("%Y%(m+1)%d")
obj.eligible = False
obj.save()
# print(f"the date is {date} and the obtain from the customer is {period}")
# print(f"this customer {i.name} bill need to be generated")
# print(f"the date is {datetime.datetime.now()}")
return redirect('/')
You can increment datetime on the basis of given days using timedelta
from datetime import datetime
from datetime import timedelta #new
today = datetime.now()
print(f"Today's the date & Time is {today}")
month_later = today+ timedelta(days=MONTHLY_CYCLE)
three_months_later = today+ timedelta(days=QUA_CYCLE)
six_months_later = today+ timedelta(days=SIX_MONTH_CYCLE)
print(f"three_months_later's the date & Time is {month_later}")
print(f"three_months_later's the date & Time is {three_months_later}")
print(f"six_months_later's the date & Time is {six_months_later}")
customer = Customer.objects.get(pk=id) # Targeted Customer
selected_cycle = int(customer.billing_cycle) #return the value of billing_cycle selected from Customer
tentative_date = today+ timedelta(days=selected_cycle)
print(f"tentative_date Billing date & Time is {month_later}") # Required DAte.
This is how you can update the datetime. rest you can implement as required.

Django admin: How to show calculated value from entered values dynamically in Django admin form page?

I have a form which is having a 'price', 'tax' and 'discount' fields (IntegerFields).
And then one more read-only field will be there called 'total_price'.
while we enter the 'price', 'discount' and 'tax', automatically 'total_price' value should display. If we change the 'discount' or 'price' then 'total_price' also change immediately.
After seeing the final price, we can click the 'Save' button.
How to attain this in Django admin?
To do this, you will have to add custom Javascript code to your admin page.
Here's what you can do:
Add read-only field to admin - it will display "total_price"
Add custom script to admin page.
Write JS script - this script will do "live update" of total price
Your admin may look like this:
#admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
# some code here...
readonly_fields = ('total_price', )
def total_price(self, obj):
# return whatever initial value you want
return obj.price - obj.price*obj.discount
# This is important - adding custom script to admin page
#property
def media(self):
media = super().media
media._js.append('js/your-custom-script.js')
return media
Remember that js/your-custom-script.js must be in your static files folder.
UPDATE:
Instead of overwriting media property, you can include your JS using Meta nested class:
class YourModelAdmin(admin.ModelAdmin):
...
class Media:
js = (
'path-to-your-static-script-file.js',
)
The last step is to write a script to update value of total_price field whenever some other field is changed.
Example: if you want to change total_price whenever price is changed, your script can look like this:
if (!$) {
$ = django.jQuery;
}
$(document).ready(function(){
// Add event listener to "price" input
$("#id_price").change(function(e){
// Get entered value
let price = parseFloat($(this).val());
// Get discount value from another field
let discount = parseFloat($("#id_discount").val())
// Compute total price in whatever way you want
let total_price = price - price*discount;
// Set value in read-only "total_price" field.
$("div.field-total_price").find("div.readonly").text(total_price);
});
})
If you want to update total_price when discount or tax fields are changed, simply add event listeners to them.

How to prohibit printing invoice when the client address field is empty

I'm using odoo and i want to prohibit printing invoices when client adresse is empty any idea for help please ? How can'i verify if this field or any other field is empty or not
this the function of printing i tried this code but nothing is happend
def invoice_print(self,cr,uid,values):
""" Print the invoice and mark it as sent, so that we can see more
easily the next step of the workflow
"""
res_partner = self.pool.get('res.partner')
adresse_partner = res_partner.browse(cr, uid, values.get('partner_id')).street
code_tva_partner = res_partner.browse(cr, uid, values.get('partner_id')).CodeTVA
if (code_tva_partner==False)or (adresse_partner==False) :
raise UserError(_(
"you cannot print invoice unless you enter partner adress and code TVA "))
elif (code_tva_partner==True) and (adresse_partner==True):
self.ensure_one()
self.sent = True
return self.env['report'].get_action(self, 'account.report_invoice')
In this function self is the record of invoice model that you are trying partner_id which is the client record for this invoice. All you have to do is add a if condition on self.partner_id.street and if that field is False which means not set, return a kind of warning. Which will prevent invoice from printing if the client has no address associated.

Odoo how update a field in inline edit mode upon selecting a product

helo,
I need to update a field (e.g description ) in order line (e.g purchase.order.line tree view) once I select a product in inline edit mode, how can I fetch the selected product in the backend and then update the desired field in the front end?
Model purchase.order.line:
description
product_id
thank you,
overriding the onchange_product_id() will solve my problem, and I'm able to handle the new selected product and update another field in tree view:
class purchase_ordr_line(models.Model):
_inherit = "purchase.order.line"
#api.multi
def onchange_product_id(self, pricelist_id, product_id, qty, uom_id,
partner_id, date_order=False, fiscal_position_id=False, date_planned=False,
name=False, price_unit=False, state='draft'):
dic_res = super(purchase_ordr_line, self).onchange_product_id(pricelist_id, product_id, qty, uom_id,partner_id, date_order=False, fiscal_position_id=False, date_planned=False,
name=False, price_unit=False, state='draft')
#Following the custom code:
dic_value = dic_res['value']
dic_value['new_field_to_update'] = new_value
return dic_res