I need to show the date field of a merge in the invoice model, specifically in the date_invoice field of the invoice model - python-3.x

I have this module in which I have created the date field, this date field I want that when I finish compiling the invoices it is added as the date of the invoice. In the invoice model, date_invoice field
for rec in (active_records - rec_to_exclude):
for line in rec.invoice_line_ids:
same_line = InvLine.search([
('invoice_id', '=', new_rec_id.id),
('product_id','=',line.product_id.id),
('price_unit','=',line.price_unit),
('discount','=',line.discount),
#('invoice_line_tax_ids','in',line.invoice_line_tax_ids.ids),
], limit=1)
if same_line:
same_line.quantity += line.quantity
else:
InvLine.create({
'product_id': line.product_id and line.product_id.id or False,
'quantity' : line.quantity,
'uom_id' : line.uom_id.id,
'price_unit' : line.price_unit,
'invoice_id': new_rec_id.id,
'name': line.name,
'discount': line.discount,
'account_id': line.account_id.id,
'invoice_date_invoice': self.date_invoicea,
'invoice_line_tax_ids': [(6,0, line.invoice_line_tax_ids.ids)]
})
for record in self:
record[(date_invoice)] = record(date_invoicea)
I have tried several functions, but it has not worked.

Related

Modify csv with groovy

Newbie need help with Groovy. I want to modify the next .csv:
Agency Name:IKEA,,,,,,,,,,,,,,
Advertiser Name: Ingka,,,,,,,,,,,,,,
Campaign Name:All,,,,,,,,,,,,,,
Date Resolution:Days,,,,,,,,,,,,,,
Campaign Dates:N/A,,,,,,,,,,,,,,
Report Date Range:Last X Days (25.06.2020 - 01.07.2020),,,,,,,,,,,,,,
Report Creation Date: 02.07.2020 5:26:18 (GMT -5 Eastern Standard Time),,,,,,,,,,,,,,
You must save the report locally to create a pivot table based on the report data.,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,
Advertiser Name,Advertiser ID,Campaign Name,Campaign ID,Date,Site Name,Site ID,Device Type,Placement Name,Placement ID,Clickthrough URL,* Clicks,* Served Impressions,* Total Recordable Impressions (IAB),* Total Viewable Impressions (IAB)
Ingka,190530,1_flight_0119,947535,25.06.2020,Auditorius SE,101304,Smart Phone,Flight_EK_Auditorius_Video_mobile,27353235,https://www.ikea.com/promo/wifi?utm_source=Auditorius&utm_medium=Video_mobile,0,0,0,0
Ingka,190530,1_flight_0119,947535,28.06.2020,Between Exchange SE,124598,PC,Flight_IQP_Between_Exchange_Banner_728x90_DCO,27359134,,0,0,0,0
Data was updated last on 7/2/2020 12:00:00 AM (GMT -5 Eastern Standard Time),,,,,,,,,,,,,,
Viewability mode is set per individual campaign,,,,,,,,,,,,,,
What I want:
Remove these lines:
Agency Name:IKEA,,,,,,,,,,,,,,
Advertiser Name: Ingka,,,,,,,,,,,,,,
Campaign Name:All,,,,,,,,,,,,,,
Date Resolution:Days,,,,,,,,,,,,,,
Campaign Dates:N/A,,,,,,,,,,,,,,
Report Date Range:Last X Days (25.06.2020 - 01.07.2020),,,,,,,,,,,,,,
Report Creation Date: 02.07.2020 5:26:18 (GMT -5 Eastern Standard Time),,,,,,,,,,,,,,
You must save the report locally to create a pivot table based on the report data.,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,
Remove these lines:
Data was updated last on 7/2/2020 12:00:00 AM (GMT -5 Eastern Standard Time),,,,,,,,,,,,,,
Viewability mode is set per individual campaign,,,,,,,,,,,,,,
Change headers names.
To: AdvertiserName,AdvertiserID,CampaignName,CampaignID,ReportDate,Site,SiteID,Device,PlacementName,PlacementID,URL,Clicks,Impressions,TotalRecordableImpressions,TotalViewableImpressions
After reading some topics about parsing CSV in groovy I tried with:
def reader = new StringReader('''...''') //or FileReader/InputStream/whatever
def mapList = []
reader.splitEachLine(','){ parts ->
mapList << [
AdvertiserName:parts[0],
AdvertiserID:parts[1],
CampaignName:parts[2],
CampaignID:parts[3],
ReportDate:parts[4],
Site:parts[5],
SiteID:parts[6],
Device:parts[7],
PlacementName:parts[8],
PlacementID:parts[9],
URL:parts[10],
Clicks:parts[11],
Impressions:parts[12],
TotalRecordableImpressions:parts[13],
TotalViewableImpressions:parts[14]
]
}
def result = mapList.findAll{ it.value!=null }
But it returns empty map, when mapList contains records with non null values:
[AdvertiserName:Ingka, AdvertiserID:190530, CampaignName:1_flight_0119, CampaignID:947535, ReportDate:25.06.2020, Site:Auditorius SE, SiteID:101304, Device:Smart Phone, PlacementName:Flight_EK_Auditorius_Video_mobile, PlacementID:27353235, URL:https://www.ikea.com/promo/wifi?utm_source=Auditorius&utm_medium=Video_mobile, Clicks:0, Impressions:0, TotalRecordableImpressions:0, TotalViewableImpressions:0]
Because it's a list with maps. I tried to fix it with:
mapList.collectEntries() {
[it.AdvertiserName, it.AdvertiserID, ...]
}
But it also returns smth weird.
something straight-forward:
def str ='''\
Agency Name:IKEA,,,,,,,,,,,,,,
Advertiser Name: Ingka,,,,,,,,,,,,,,
Campaign Name:All,,,,,,,,,,,,,,
Date Resolution:Days,,,,,,,,,,,,,,
Campaign Dates:N/A,,,,,,,,,,,,,,
Report Date Range:Last X Days (25.06.2020 - 01.07.2020),,,,,,,,,,,,,,
Report Creation Date: 02.07.2020 5:26:18 (GMT -5 Eastern Standard Time),,,,,,,,,,,,,,
You must save the report locally to create a pivot table based on the report data.,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,
Advertiser Name,Advertiser ID,Campaign Name,Campaign ID,Date,Site Name,Site ID,Device Type,Placement Name,Placement ID,Clickthrough URL,* Clicks,* Served Impressions,* Total Recordable Impressions (IAB),* Total Viewable Impressions (IAB)
Ingka,190530,1_flight_0119,947535,25.06.2020,Auditorius SE,101304,Smart Phone,Flight_EK_Auditorius_Video_mobile,27353235,https://www.ikea.com/promo/wifi?utm_source=Auditorius&utm_medium=Video_mobile,0,0,0,0
Ingka,190530,1_flight_0119,947535,28.06.2020,Between Exchange SE,124598,PC,Flight_IQP_Between_Exchange_Banner_728x90_DCO,27359134,,0,0,0,0
Data was updated last on 7/2/2020 12:00:00 AM (GMT -5 Eastern Standard Time),,,,,,,,,,,,,,
Viewability mode is set per individual campaign,,,,,,,,,,,,,,
'''
def headers = [ 'AdvertiserName', 'AdvertiserID', 'CampaignName', 'CampaignID', 'ReportDate', 'Site',
'SiteID', 'Device', 'PlacementName', 'PlacementID', 'URL', 'Clicks', 'Impressions',
'TotalRecordableImpressions', 'TotalViewableImpressions' ].withIndex()
def list = []
boolean start
str.splitEachLine(','){ parts ->
if( 'Advertiser Name' == parts[ 0 ] ){
start = true
return
}else if( !start || 15 != parts.size() ) return
list << headers.collectEntries{ [ it[ 0 ], parts[ it[ 1 ] ] ] }
}
println list.join( '\n' )
prints:
[AdvertiserName:Ingka, AdvertiserID:190530, CampaignName:1_flight_0119, CampaignID:947535, ReportDate:25.06.2020, Site:Auditorius SE, SiteID:101304, Device:Smart Phone, PlacementName:Flight_EK_Auditorius_Video_mobile, PlacementID:27353235, URL:https://www.ikea.com/promo/wifi?utm_source=Auditorius&utm_medium=Video_mobile, Clicks:0, Impressions:0, TotalRecordableImpressions:0, TotalViewableImpressions:0]
[AdvertiserName:Ingka, AdvertiserID:190530, CampaignName:1_flight_0119, CampaignID:947535, ReportDate:28.06.2020, Site:Between Exchange SE, SiteID:124598, Device:PC, PlacementName:Flight_IQP_Between_Exchange_Banner_728x90_DCO, PlacementID:27359134, URL:, Clicks:0, Impressions:0, TotalRecordableImpressions:0, TotalViewableImpressions:0]
To put the data back into a file you would need smth like:
def file = new StringWriter() // replace with new File( '../output.csv' )
file.withWriter{ out ->
out << headers*.first().join( ',' )
list.each{
out << '\n' << it.values().join( ',' )
}
}
file
prints:
AdvertiserName,AdvertiserID,CampaignName,CampaignID,ReportDate,Site,SiteID,Device,PlacementName,PlacementID,URL,Clicks,Impressions,TotalRecordableImpressions,TotalViewableImpressions
Ingka,190530,1_flight_0119,947535,25.06.2020,Auditorius SE,101304,Smart Phone,Flight_EK_Auditorius_Video_mobile,27353235,https://www.ikea.com/promo/wifi?utm_source=Auditorius&utm_medium=Video_mobile,0,0,0,0
Ingka,190530,1_flight_0119,947535,28.06.2020,Between Exchange SE,124598,PC,Flight_IQP_Between_Exchange_Banner_728x90_DCO,27359134,,0,0,0,0

Error creating invoice from custom module (Odoo 13)

I am trying to create an invoice from a custom object but I am getting errors from on validation .When I post, i get the following error: "
ValueError: Wrong value for account.move.line_ids: {'display_type': 'line_section', 'name': 'Phone Bill', 'product_id': 11783, 'product_uom_id': 19, 'current_reading': 66.0, 'current_date': datetime.date(2020, 11, 3), 'quantity': 17.0, 'price_unit': 565.0, 'account_id': 19, 'debit': 9605.0, 'credit': 0.0}
current_date and current_reading are custom fields i created. I am aware that Odoo automatically creates values for line_ids from invoice_line_ids if line_ids is not provided, so I am really stuck about this error.
Here's my code for creating the invoice:
class ReadingCorrection(models.TransientModel):
_name = 'reading.upload.wizard'
_description = 'Validate reading uploads'
def validate_entry(self):
active_ids = self._context.get('active_ids', []) or []
company = self.env.user.company_id
journal = self.env['account.move'].with_context(force_company=company.id, type='out_invoice')._get_default_journal()
for reads in self.env['reading.upload'].browse(active_ids):
if reads.reading >= reads.previous_reading: # and reads.state == 'draft':
account = reads.product_id.product_tmpl_id._get_product_accounts()['income']
if not account:
raise UserError(_('No account defined for product "%s".') % reads.product_id.name)
invoice = {
'type': 'out_invoice',
'invoice_date':reads.read_date,
'narration': reads.remark,
'invoice_user_id': reads.current_user.id,
'partner_id': reads.meter_id.customer_id.id,
'journal_id': 1,#journal.id,
'currency_id': reads.meter_id.customer_id.currency_id.id,
'doc_type': 'bill',
'invoice_line_ids':[(0,0, {
'name': reads.product_id.name,
'product_id': reads.product_id.id,
'product_uom_id': reads.product_id.uom_id.id,
'current_reading': reads.reading,
'previous_reading': reads.previous_reading,
'current_date': reads.read_date,
'quantity': reads.reading - reads.previous_reading,
'price_unit': reads.product_id.product_tmpl_id.lst_price,
'account_id': account.id,
})]
}
moves = self.env['account.move'].with_context(default_type='out_invoice').create(invoice)
#invoice = self.env['account.move'].sudo().create(invoice)
reads.write({'state':'uploaded'})
Any help given will be appreciated. Thanks
If you want to create invoices, in the lines you should not use the debit and credit fields since these are calculated, as it is a product line, you should not use display_type, since the line_section type is treated as an annotation and not as a price calculation line.
In the invoice data, when linking the lines 'invoice_line_ids': inv_line_ids an instruction must be specified to process the lines in your case it would be as follows 'invoice_line_ids': (0, 0, inv_line_ids) for greater information visit this page.

creating Price object in stripe payment with customized interval

I can create price in stripe using, for month and year:
price1 = stripe.Price.create(
product=product.stripe_id,
unit_amount=1000,
currency='usd',
recurring={
'interval': 'month',
},
)
price4 = stripe.Price.create(
product=product.stripe_id,
unit_amount=12000,
currency='usd',
recurring={
'interval': 'year',
},
)
I was wondering how can I create for 3 month and 6 month. they are obviously available, for creating from interface:
however if I use "6month" or "6-month" or ...
it gives the following error:
Invalid recurring[interval]: must be one of month, year, week, or day
any ide how i can achieve this?
You can specify recurring.interval_count with recurring.interval to specify the number of intervals between subscription billings. For example, you could set interval=month and interval_count=6 to get a price that bills every 6 months. In your code, that would look like this:
price1 = stripe.Price.create(
product=product.stripe_id,
unit_amount=1000,
currency='usd',
recurring={
'interval': 'month',
'interval_count': 6
},
)
Here's the documentation for recurring.interval_count: https://stripe.com/docs/api/prices/create?lang=cli#create_price-recurring-interval_count

TypeError: Object of type 'Location' is not JSON serializable

i am using geopy library for my Flask web app. i want to save user location which i am getting from my modal(html form) in my database(i am using mongodb), but every single time i am getting this error:
TypeError: Object of type 'Location' is not JSON serializable
Here's the code:
#app.route('/register', methods=['GET', 'POST'])
def register_user():
if request.method == 'POST':
login_user = mongo.db.mylogin
existing_user = login_user.find_one({'email': request.form['email']})
# final_location = geolocator.geocode(session['address'].encode('utf-8'))
if existing_user is None:
hashpass = bcrypt.hashpw(
request.form['pass'].encode('utf-8'), bcrypt.gensalt())
login_user.insert({'name': request.form['username'], 'email': request.form['email'], 'password': hashpass, 'address': request.form['add'], 'location' : session['location'] })
session['password'] = request.form['pass']
session['username'] = request.form['username']
session['address'] = request.form['add']
session['location'] = geolocator.geocode(session['address'])
flash(f"You are Registerd as {session['username']}")
return redirect(url_for('home'))
flash('Username is taken !')
return redirect(url_for('home'))
return render_template('index.html')
Please Help, let me know if you want more info..
According to the geolocator documentation the geocode function "Return a location point by address" geopy.location.Location objcet.
Json serialize support by default the following types:
Python | JSON
dict | object
list, tuple | array
str, unicode | string
int, long, float | number
True | true
False | false
None | null
All the other objects/types are not json serialized by default and there for you need to defined it.
geopy.location.Location.raw
Location’s raw, unparsed geocoder response. For details on this,
consult the service’s documentation.
Return type: dict or None
You might be able to call the raw function of the Location (the geolocator.geocode return value) and this value will be json serializable.
Location is indeed not json serializable: there are many properties in this object and there is no single way to represent a location, so you'd have to choose one by yourself.
What type of value do you expect to see in the location key of the response?
Here are some examples:
Textual address
In [9]: json.dumps({'location': geolocator.geocode("175 5th Avenue NYC").address})
Out[9]: '{"location": "Flatiron Building, 175, 5th Avenue, Flatiron District, Manhattan Community Board 5, Manhattan, New York County, New York, 10010, United States of America"}'
Point coordinates
In [10]: json.dumps({'location': list(geolocator.geocode("175 5th Avenue NYC").point)})
Out[10]: '{"location": [40.7410861, -73.9896298241625, 0.0]}'
Raw Nominatim response
(That's probably not what you want to expose in your API, assuming you want to preserve an ability to change geocoding service to another one in future, which might have a different raw response schema).
In [11]: json.dumps({'location': geolocator.geocode("175 5th Avenue NYC").raw})
Out[11]: '{"location": {"place_id": 138642704, "licence": "Data \\u00a9 OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright", "osm_type": "way", "osm_id": 264768896, "boundingbox": ["40.7407597", "40.7413004", "-73.9898715", "-73.9895014"], "lat": "40.7410861", "lon": "-73.9896298241625", "display_name": "Flatiron Building, 175, 5th Avenue, Flatiron District, Manhattan Community Board 5, Manhattan, New York County, New York, 10010, United States of America", "class": "tourism", "type": "attraction", "importance": 0.74059885426854, "icon": "https://nominatim.openstreetmap.org/images/mapicons/poi_point_of_interest.p.20.png"}}'
Textual address + point coordinates
In [12]: location = geolocator.geocode("175 5th Avenue NYC")
...: json.dumps({'location': {
...: 'address': location.address,
...: 'point': list(location.point),
...: }})
Out[12]: '{"location": {"address": "Flatiron Building, 175, 5th Avenue, Flatiron District, Manhattan Community Board 5, Manhattan, New York County, New York, 10010, United States of America", "point": [40.7410861, -73.9896298241625, 0.0]}}'

Reformat csv file using python?

I have this csv file with only two entries. Here it is:
Meat One,['Abattoirs', 'Exporters', 'Food Delivery', 'Butchers Retail', 'Meat Dealers-Retail', 'Meat Freezer', 'Meat Packers']
First one is title and second is a business headings.
Problem lies with entry two.
Here is my code:
import csv
with open('phonebookCOMPK-Directory.csv', "rt") as textfile:
reader = csv.reader(textfile)
for row in reader:
row5 = row[5].replace("[", "").replace("]", "")
listt = [(''.join(row5))]
print (listt[0])
it prints:
'Abattoirs', 'Exporters', 'Food Delivery', 'Butchers Retail', 'Meat Dealers-Retail', 'Meat Freezer', 'Meat Packers'
What i need to do is that i want to create a list containing these words and then print them like this using for loop to print every item separately:
Abattoirs
Exporters
Food Delivery
Butchers Retail
Meat Dealers-Retail
Meat Freezer
Meat Packers
Actually I am trying to reformat my current csv file and clean it so it can be more precise and understandable.
Complete 1st line of csv is this:
Meat One,+92-21-111163281,Al Shaheer Corporation,Retailers,2008,"['Abattoirs', 'Exporters', 'Food Delivery', 'Butchers Retail', 'Meat Dealers-Retail', 'Meat Freezer', 'Meat Packers']","[[' Outlets Address : Shop No. Z-10, Station Shopping Complex, MES Market, Malir-Cantt, Karachi. Landmarks : MES Market, Station Shopping Complex City : Karachi UAN : +92-21-111163281 '], [' Outlets Address : Shop 13, Ground Floor, Plot 14-D, Sky Garden, Main Tipu Sultan Road, KDA Scheme No.1, Karachi. Landmarks : Nadra Chowrangi, Sky Garden, Tipu Sultan Road City : Karachi UAN : +92-21-111163281 '], ["" Outlets Address : Near Jan's Broast, Boat Basin, Khayaban-e-Roomi, Block 5, Clifton, Karachi. Landmarks : Boat Basin, Jans Broast, Khayaban-e-Roomi City : Karachi UAN : +92-21-111163281 View Map ""], [' Outlets Address : Gulistan-e-Johar, Karachi. Landmarks : Perfume Chowk City : Karachi UAN : +92-21-111163281 '], [' Outlets Address : Tee Emm Mart, Creek Vista Appartments, Khayaban-e-Shaheen, Phase VIII, DHA, Karachi. Landmarks : Creek Vista Appartments, Nueplex Cinema, Tee Emm Mart, The Place City : Karachi Mobile : 0302-8333666 '], [' Outlets Address : Y-Block, DHA, Lahore. Landmarks : Y-Block City : Lahore UAN : +92-42-111163281 '], [' Outlets Address : Adj. PSO, Main Bhittai Road, Jinnah Supermarket, F-7 Markaz, Islamabad. Landmarks : Bhittai Road, Jinnah Super Market, PSO Petrol Pump City : Islamabad UAN : +92-51-111163281 ']]","Agriculture, fishing & Forestry > Farming equipment & services > Abattoirs in Pakistan"
First column is Name
Second column is Number
Third column is Owner
Forth column is Business type
Fifth column is Y.O.E
Sixth column is Business Headings
Seventh column is Outlets (List of lists containing every branch address)
Eighth column is classification
There is no restriction of using csv.reader, I am open to any technique available to clean my file.
Think of it in terms of two separate tasks:
Collect some data items from a ‘dirty’ source (this CSV file)
Store that data somewhere so that it’s easy to access and manipulate programmatically (according to what you want to do with it)
Processing dirty CSV
One way to do this is to have a function deserialize_business() to distill structured business information from each incoming line in your CSV. This function can be complex because that’s the nature of the task, but still it’s advisable to split it into self-containing smaller functions (such as get_outlets(), get_headings(), and so on). This function can return a dictionary but depending on what you want it can be a [named] tuple, a custom object, etc.
This function would be an ‘adapter’ for this particular CSV data source.
Example of deserialization function:
def deserialize_business(csv_line):
"""
Distills structured business information from given raw CSV line.
Returns a dictionary like {name, phone, owner,
btype, yoe, headings[], outlets[], category}.
"""
pieces = [piece.strip("[[\"\']] ") for piece in line.strip().split(',')]
name = pieces[0]
phone = pieces[1]
owner = pieces[2]
btype = pieces[3]
yoe = pieces[4]
# after yoe headings begin, until substring Outlets Address
headings = pieces[4:pieces.index("Outlets Address")]
# outlets go from substring Outlets Address until category
outlet_pieces = pieces[pieces.index("Outlets Address"):-1]
# combine each individual outlet information into a string
# and let ``deserialize_outlet()`` deal with that
raw_outlets = ', '.join(outlet_pieces).split("Outlets Address")
outlets = [deserialize_outlet(outlet) for outlet in raw_outlets]
# category is the last piece
category = pieces[-1]
return {
'name': name,
'phone': phone,
'owner': owner,
'btype': btype,
'yoe': yoe,
'headings': headings,
'outlets': outlets,
'category': category,
}
Example of calling it:
with open("phonebookCOMPK-Directory.csv") as f:
lineno = 0
for line in f:
lineno += 1
try:
business = deserialize_business(line)
except:
# Bad line formatting?
log.exception(u"Failed to deserialize line #%s!", lineno)
else:
# All is well
store_business(business)
Storing the data
You’ll have the store_business() function take your data structure and write it somewhere. Maybe it’ll be another CSV that’s better structured, maybe multiple CSVs, a JSON file, or you can make use of SQLite relational database facilities since Python has it built-in.
It all depends on what you want to do later.
Relational example
In this case your data would be split across multiple tables. (I’m using the word “table” but it can be a CSV file, although you can as well make use of an SQLite DB since Python has that built-in.)
Table identifying all possible business headings:
business heading ID, name
1, Abattoirs
2, Exporters
3, Food Delivery
4, Butchers Retail
5, Meat Dealers-Retail
6, Meat Freezer
7, Meat Packers
Table identifying all possible categories:
category ID, parent category, name
1, NULL, "Agriculture, fishing & Forestry"
2, 1, "Farming equipment & services"
3, 2, "Abattoirs in Pakistan"
Table identifying businesses:
business ID, name, phone, owner, type, yoe, category
1, Meat One, +92-21-111163281, Al Shaheer Corporation, Retailers, 2008, 3
Table describing their outlets:
business ID, city, address, landmarks, phone
1, Karachi UAN, "Shop 13, Ground Floor, Plot 14-D, Sky Garden, Main Tipu Sultan Road, KDA Scheme No.1, Karachi", "Nadra Chowrangi, Sky Garden, Tipu Sultan Road", +92-21-111163281
1, Karachi UAN, "Near Jan's Broast, Boat Basin, Khayaban-e-Roomi, Block 5, Clifton, Karachi", "Boat Basin, Jans Broast, Khayaban-e-Roomi", +92-21-111163281
Table describing their headings:
business ID, business heading ID
1, 1
1, 2
1, 3
…
Handling all this would require a complex store_business() function. It may be worth looking into SQLite and some ORM framework, if going with relational way of keeping the data.
You can just replace the line :
print(listt[0])
with :
print(*listt[0], sep='\n')

Resources