Problem adding datefield to invoice odoo12 - invoice

The following Python script does not create a date field:
from datetime import datetime
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
class DealInvoice(models.Model):
_inherit = 'account.invoice'
x_date_deal = fields.Date(string='Date Deal',
required=True,
readonly=True,
default=(date.today()),
index=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
help='Item date deal.')
#api.constrains('x_date_deal')
def _x_date_deal_check(self):
for record in self:
if record.x_date_deal and record.x_date_deal [0] <= str(date.today()):
raise ValidationError(_("Date deal must be before current date."))

The code hereunder gives the error 'date not defined'. In the end i just want avalidation that a date is today or not more than 5 days in the past. Thanks for your help.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from datetime import date
today = date.today
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
_name = 'account.invoice'
x_date_deal = fields.Date(string='Date of Deal', required=True, readonly=False, index=True,
states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
help='Date of Deal')
#api.constrains('x_date_deal')
def _delivery_date_check(self):
for record in self:
if record.x_date_deal and record.x_date_deal > today:
raise ValidationError(_("Deal Date must be ...."))

Related

Google Ads Script (AWQL) get custom date range for reporting

I need to pull a google ads report that will get data from a fixed date (28th May) until today and push the data to a spreadsheet. I can't figure out how to define the date range for this query
I've tried googling and reading the google documentation but I can't figure it out
function main() {
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/XXX');
var sheet = spreadsheet.getSheetByName('Data')
var report = AdsApp.report(
'SELECT Date, CampaignName, AverageFrequency, Impressions, ImpressionReach ' +
'FROM CAMPAIGN_PERFORMANCE_REPORT ' +
'WHERE Impressions > 0 ' +
'DURING 20190528,TODAY');
sheet.clearContents();
report.exportToSheet(sheet);
}
I need to use today as the end date instead of the campaign end date as the end date for this query as I'm trying to pull frequency as a metric and it will just show blank values if the end date is in the future.
Please let me know if there is a way to make the query work. Thanks!
The TODAY keyword acts as the "full range" of the DURING property and cannot be used as the end part (as far as I know). The following should work.
function main() {
var endDate = new Date();
var endRange = Utilities.formatDate(endDate, 'America/Chicago', 'YYYYMMdd');
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/XXX');
var sheet = spreadsheet.getSheetByName('Data')
var report = AdsApp.report(
'SELECT Date, CampaignName, AverageFrequency, Impressions, ImpressionReach ' +
'FROM CAMPAIGN_PERFORMANCE_REPORT ' +
'WHERE Impressions > 0 ' +
'DURING 20190528,' + endRange);
sheet.clearContents();
report.exportToSheet(sheet);
}
Date ranges for the report are defined in the DURING clause of the query. Date ranges can be specified in two different ways:
A custom date range using regular AWQL syntax, for example:
SELECT Id, Criteria, AdGroupName
FROM KEYWORDS_PERFORMANCE_REPORT
DURING 20190101,20190325
A date range type, for example:
SELECT Id, Criteria, AdGroupName
FROM KEYWORDS_PERFORMANCE_REPORT
DURING LAST_7_DAYS
In your case you should use:
DURING 20190528, 20190723
There is no other option for you to do that.

Grails - dynamic finders derived date query GORM

I have the following domain class
class Book {
String title
Date releaseDate
Integer daysOnShelf
Author author
}
How can I list all books where current date is greater than the releaseDate + daysOnShelf? For instance, don't list if 2015-02-10 + 5 (releaseDate + daysOnShelf) since date is less than now.
Can this be done using GORM dynamic finders or Criteria Builder ? e.g.,
def index(Integer max) {
def books = Book.findAll {
releaseDate.plus(daysOnShelf) < new Date()
}
respond books
}
This should acchieve what you want:
Date dateMinusDaysOnShelf = new Date() - daysOnShelf
Book.findAllByReleaseDateLessThan(dateMinusDaysOnShelf)

Create an autoincrement (non id) field in Grails & Oracle

I have to keep track of sequential submissions per fiscal year. Given the fiscal year '2015' then the numbering should be '2015001, 2015002, 2015003, etc'.
I have defined a domain class to keep track of these settings:
class MYAPPConfig {
String fiscalYear
Integer requestCount
static constraints = {
fiscalYear (size: 4..4, nullable: false)
requestCount(max: 999, nullable: false)
}
}
The idea is that for a new fiscal year I will add a new record and the 'requestCount' will be reset to 0 (or 1 depending on how Grails wants to manage it).
Ideally this field should be mapped to an Oracle sequence field. If that's not possible then should I manage the increment logic in a service method?
My Grails version is 2.4.2
Thanks.
I figured it out.
I took a different route (after more googling). I added dateCreated to my model which is managed by Grails so its updated automatically. So all I needed to do is get the record with the latest date (every year we will add a new record for the coming fiscal year). Take note of the [0] at the end of the call, that flattens the array of arrays returned and allows me to deal with a single object.
My model now looks like this ( MYAPPConfig.groovy ) :
class MYAPPConfig {
String fiscalYear
Integer requestCount
Date dateCreated
static constraints = {
fiscalYear (size: 4..4, nullable: false)
requestCount(max: 999, nullable: false)
}
}
I created the following service ( ManageRequestsService.groovy )
import grails.transaction.Transactional
#Transactional
class ManageRequestService {
def getNextTrackingId() {
def latestConfig = MYAPPConfig.listOrderByDateCreated(max:1, order: "desc")[0]
def latestFiscal = latestConfig.fiscalYear
Integer sequence = latestConfig.requestCount
sequence++
latestConfig.requestCount = sequence
latestConfig.save(flush:true)
return latestFiscal + sprintf('%03d', sequence)
}
}
And in my controller ( MyTestController.groovy ) I have:
class MyTestController {
def manageRequestsService
def test() {
def trackingId = manageRequestsService.getNextTrackingId()
render "Next id is: ${trackingId}"
}
}
Giving the following output ( http://localhost:8080/MYAPP/myTest/test ):
Next id is: 2015001
Refresh page!
Next id is: 2015002
Refresh again!
Next id is: 2015003

Grails - Can't add child record to parent

Trying to follow the example shown here I am trying to create a record which links to a parent record.
In my case I have two classes: Sensor, and Readings. I can create Sensors without any issues, but no matter how I try to create readings I seem to fail :(
I've been spinning my wheels for long enough, I'm throwing in the towel and hoping someone can spot my silly mistake(s).
One more thing - I want to post the data using JSON. But through the debugging process I'm not even looking at the JSON values, I've hard coded them and it still doesn't work.
ReadingsController.groovy
package grailshelloworld
import grails.converters.JSON
import groovy.json.JsonSlurper
class ReadingsController {
def scaffold=Readings
def save = {
def slurper = new JsonSlurper()
def result = slurper.parseText(request.reader.text)
def s = new Sensor (sensorid: "SID", sensorname: "name", sensordescription: "description")
.addToReadings(reading: "blah")
.save()
render ([ok: false] as JSON)
}
}
sensor.groovy
package grailshelloworld
class Sensor {
String sensorid
String sensorname
String sensordescription
static hasMany = [readings: Readings]
static constraints = {
sensorid blank:false, nullable: false
sensorname blank:false, nullable: false
}
}
Readings.grooovy
package grailshelloworld
import java.util.Formatter.DateTime;
class Readings {
String reading
static belongsTo = [sensor: Sensor]
}
Current error: argument type mismatch...
<dt>Class</dt><dd>java.lang.IllegalArgumentException</dd><dt>Message</dt><dd>argument type mismatch</dd></dl><h2>Around line 15 of <span class="filename">grails-app/controllers/grailshelloworld/ReadingsController.groovy</span></h2>
<pre class="snippet"><code class="line"><span class="lineNumber">12:</span> def slurper = new JsonSlurper()</code><code class="line"><span class="lineNumber">13:</span> def result = slurper.parseText(request.reader.text)</code><code class="line"><span class="lineNumber">14:</span></code><code class="line error"><span class="lineNumber">15:</span> def s = new Sensor (sensorid: "SID", sensorname: "name", sensordescription: "description")</code><code class="line"><span class="lineNumber">16:</span> .addToReadings(reading: "blah")</code><code class="line"><span class="lineNumber">17:</span> .save()</code><code class="line"><span class="lineNumber">18:</span></code></pre><h2>Around line 195 of <span class="filename">PageFragmentCachingFilter.java</span></h2>
Have you tried it by explicitly creating a new Readings?
def s = new Sensor (sensorid: "SID", sensorname: "name", sensordescription: "description")
.addToReadings(new Readings(reading: 'blah'))
.save()
The error is saying "around line 15" which is the start to the def s = ... statement.
I know the docs say it can be done the way you are attempting - but it's worth a try.

How Do I Combine Two Query Results In To A Map, In Grails?

I'm new to Grails development.
I have a domain class like this :
class DaySchedule {
Date Todaysdate
String startTime;
String endTime;
String task
int priority
boolean completed
static belongsTo = [ schedule : Schedule ]
}
I have bootstrapped with some test data's. Now I want to do a query, with following condition :
I need to pick each task (which are stored in bootstrap.groovy) which are belongs to a particularTodaysdate.
For example if I have these statements in my BootStrap.groovy :
//other codes
def daySchedule3 = new DaySchedule(Todaysdate:new Date(),
startTime:"6pm",endTime:"10pm",
task:"ReaD git...",completed:false)
def daySchedule4 = new DaySchedule(Todaysdate:new Date()+1,
startTime:"10am",endTime:"12pm",
task:"Read MySQL....",completed:false)
Now clearly the task, ReaD git... belongs to a day (which is today as I have passed new Date() into it).
To find these I came up with a partial solution like this:
def allTasks = DaySchedule.findAllByTaskIsNotNull()
def dates = allTasks.collect { it.Todaysdate }
def tasks = dates.collect {
def queryParameter = new DaySchedule(Todaysdate:it)
def todaysWork = DaySchedule.findAll(queryParameter)
todaysWork.task
}
I have a problem with this code. I couldn't use collectEntries method on the dates and tasks so that I convert it into map of a particular date(i.e dates) with values as tasks. (which is what I tried for!)
Now I'm left lone. I couldn't not able to find a way to guess for which dates the tasks belongs to.
Any other solutions for it?
Thanks in advance.
It sounds like you're trying to get a map with a key of the date, and a value of the task name, for all of the domain objects DaySchedule. You may want to try Collection.groupBy. For example:
def allTasks = DaySchedule.findAllByTaskIsNotNull()
def tasksByDate = [:] // start with empty map
tasksByDate.putAll(
allTasks.groupBy { task ->
// group by just the date portion, ignoring time
// clone since clearTime modifies original
task.todaysDate.clone().clearTime()
}.collect { date, daySchedule ->
// change from map of date -> daySchedule to map of date -> task
[date, daySchedule.task] as MapEntry
}
)
I think you have a design problem somewhere... it would be easier to have something like :
class Task {
Date startTime;
Date endTime;
String description
int priority
boolean completed
static belongsTo = [ schedule : Schedule ]
String toString() {
return "${description} : from ${startTime} to ${endTime}"
}
}
Then, you can list all the dates for which you have tasks in them like this :
java.text.DateFormat df = java.text.DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
def days = Task.list().collect {
df.format(it.startTime);
}.unique()
So now the "days" variable contains an array of strings of unique days present in your database with tasks associated.
If you want to list the tasks by day, you can then do :
days.each { dayString ->
def date = df.parse(dayString)
def dayTasks = Task.findAllByStartTimeBetween(date, date+1)
println "Tasks for ${dayString}"
dayTasks.each {
println " - ${it}"
}
}

Resources