Print receipt in pos order odoo - odoo-13

I want to print receipt in pos order not only in pos session. Can I print receipt or report like pos session receipt.
Above image, I want to print receipt in pos order form that are the same format with pos receipt.

Related

Python Gmail API. Search for emails based on Labels and Ascending Time Order?

I am using the Gmail API with Python. I would like to search for email messages using a label, in time ascending order. I am able to search for emails using a label or list of labels with the following function:
def gmailAPIMessageLabelSearch(self, labelList, userID="me", allPages=False):
try:
self.GLogger.info("Attempting to search emails with labelList (" + str(labelList)+ ") and userID (" +str(userID)+ ")")
service = self.gmailAPIService
if service is None:
logging.error('Gmail Service not initialized')
return False
response = service.users().messages().list(userId=userID, labelIds=labelList).execute()
messages = []
if 'messages' in response:
messages.extend(response['messages'])
if allPages is True:
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = service.users().messages().list(userId=userID, labelIds=labelList, pageToken=page_token).execute()
if 'messages' in response:
messages.extend(response['messages'])
self.GLogger.info("Successfully searched emails with labelList (" + str(labelList)+ ") and userID (" +str(userID)+ "). Number of matching emails (" +str(len(messages))+ ")")
return messages
except:
self.GLogger.error("An error was encounrtered while searching for messages with google API and label list")
tb = traceback.format_exc()
self.GLogger.exception(tb)
return False
However, I would specifically like to ensure that I am receiving emails in Time Ascending Order. So the search should return with the oldest first and newest last.
Also, I am not able to simply download the emails and then sort. The emails are used in real time, so they cannot be stored and then sorted. I am aware it would be possible to simply download the emails and then extract their time and sort accordingly. However, this is not an option. I would need the results of the search to already provide this list in ascending time order.
Is there a way of doing this?
I tried searching and checking the Gmail API for the list() function but I don't see a way. I tried applying "Oldest" label, and didn't do anything.
The docs say the the q parameter supports the same query format as the Gmail search box.
See here for which terms it accepts: https://support.google.com/mail/answer/7190?hl=en
Some of those terms can be useful to filter messages.
As Google mail does not provide the ability to invert the sorting, the easiest way is to retrieve the first page using list, the response then includes an estimate for the total number of results resultSizeEstimate, based on this you can jump to the last page and then you only have to sort the emails from that page.

Python issues with specific outlook email

Can anyone give me advice for this issue? I am not getting any error messages and don't know where to start.
I made a program that checks emails in an Outlook inbox for pdf attachments from a list of senders, then saves the attachments to a folder. You put in a starting date and choose how many days you want to search through. There is a line in the code to show all emails being checked even if they aren't related to the sender/s for debugging. It has been working fine for months, until recently I got an email from ebay that contains an emote of a packed cardboard box in the subject line, and this specific email causes the program to misbehave.
Here's an example of the erroneous output - I've put in zero to search for 'any sender' from a list, and chosen a date range like always. The first Attribute Error is caused by an undeliverable message (which is not considered class 43 'mail' by outlook). You can see that the first normal mail item in the date range gets checked, with the subject line etc displayed, but then the next message is the ebay email, which is way outside the date range. The program skips over several days without checking any other emails in that range and ends the search. Same thing happens if I disable the display of every email in output (all emails still get read by the program, but there is a line to display only relevant ones).
There seems to be some issue with that specific email - Ebay is not one of the senders in the list the program checks for attachments, and even if I have a date range of zero days it will still show that email from a week ago as the last email checked. The only thing that seems unique about it is the cardboard box emote in the subject line, there is nothing else about it that stands out to me.
Here is the output:
Choose a sender (blank to exit): 0
Enter a starting search date in format dd-mm-yyyy (blank to exit): 05-05-2020
Enter how many days previous to search through: 3
Your search starts from 2020-05-05 00:00:00 and ends on 2020-05-02
Searching for any sender
Searching...
Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass REPORT.IPM.Note.NDR - Class 46
Looking at [...], WordPress has been updated on [...]. 2020-05-05
Looking at 📦 ORDER DELIVERED: 10x Capacitive Stylus Pen Tou… 2020-04-28
Reached end of date range: final message - 📦 ORDER DELIVERED: 10x Capacitive Stylus Pen Tou… 2020-04-28
If I move the problematic email to a different inbox then my program will correctly check emails across the whole date range I entered.
It gets weirder, because if put in a date range that would include that particular ebay email, then it DOES NOT appear in the output, while OTHER ebay emails which include emotes like a truck or a ticked box DO get checked by the program.
Looking at 🚚 ORDER UPDATE: 10x Capacitive Stylu... 2020-04-22
Looking at FAILED Schemus mail synchronization 2020-04-22
Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass REPORT.IPM.Note.NDR - Class 46
Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass REPORT.IPM.Note.NDR - Class 46
Looking at Active Directory Sync Failure 2020-04-21
Looking at ✅ ORDER CONFIRMED: 10x Capacitive Stylu... 2020-04-21
Below is the block of code for collecting attachments:
def mainChoice0(): #COLLECT ATTACHMENTS
#Choose sender from menu.
senderNum = input("Choose a sender (blank to exit): ")
if senderNum == "":
mainChoiceDisplay0 = False
topMenu() #Return to main menu
else:
senderNum = int(senderNum)
senderChoice = listSender[senderNum]
####Determine search range by date
startDate = input("Enter a starting search date in format dd-mm-yyyy (blank to exit): ")
if startDate == "":
mainChoiceDisplay0 = False
topMenu()
#strptime will convert startDate from a string to a usable date
startDate = datetime.datetime.strptime(startDate, "%d-%m-%Y")
searchRange = int(input("Enter how many days previous to search through: "))
searchDate = startDate.date() - datetime.timedelta(days = searchRange)
print("Your search starts from", startDate, "and ends on", searchDate, "\n")
#SEARCH ANY SENDERS
if senderNum == 0:
print("Searching for any sender")
print("Searching...")
#LOOK AT INBOX CONTENTS
for msg in reversed(itcontents): #reversed() looks at most recent received email first based on date
#while mainChoiceDisplay0 == True:
try:
###!!! uncomment this to see details about every email even if they aren't relevant to the search !!!####
print("Looking at", msg, msg.SentOn.date())
#msg.Sender is sender name, msg.SenderEmailAddress is the address.
if ( (str(msg.SenderEmailAddress) or str(msg.Subject) or str(msg.Sender) or str(msg.SentOnBehalfOfName)) in senderDict and (msg.SentOn.date() >= searchDate and msg.SentOn.date() <= startDate.date())):
check += 1
print(check, "messages from", msg.SenderEmailAddress, "on", msg.SentOn.date()) #show number of messages from relevant senders
for x in msg.Attachments:
if str(".pdf").casefold() in str(x): #casefold() checks upper or lower case combinations e.g PDF pdf Pdf
x.SaveAsFile("C:\\Users\\"+emailUser+"\\Desktop\\Invoices from Outlook\\" + str(msg.SentOn.date()) + str(msg.SenderEmailAddress) + x.FileName)
print("Saved attachment", x, "from", str(msg.Sender()), "on", str(msg.SentOn.date()))
#break
#Stop searching inbox earlier than searchDate
nextMail() #Look at the next most recent email, repeat until end of date range
#Final message to indicate end of search, with subject line and date of the final message.
if msg.SentOn.date() < searchDate:
print("Reached end of date range: final message -", msg, msg.SentOn.date(), "\n")
mainChoiceDisplay0 = False
topMenu()
except UnicodeEncodeError: #unsupported characters
print("Subject line could not be parsed", msg, msg.SentOn.date())
#continue
except OverflowError: #caused by invalid or very old date e.g 01-01-0000
print("Date calculation caused an overflow error, possibly because you entered a very old date e.g 01-01-0000 at mainChoice0()")
#break
except AttributeError: #The email was the wrong class for the attribute msg.Sender or you tried to use an attribute that doesn't work for that method
print("Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass", msg.MessageClass, '- Class', msg.Class)
pass
except ValueError:
print("Invalid input caused a value error in mainChoice0().")
Instead of iterating over all items and checking separate property every time you need to use the Find/FindNext or Restrict methods of the Items class. Read more about thses methods in the following articles:
How To: Retrieve Outlook calendar items using Find and FindNext methods
How To: Use Restrict method in Outlook to get calendar items

twilio sends 3 separate sms from dictionary and i need it to send once

twilioCli = Client(accountSID, authToken)
message = twilioCli.messages.create(body="Your Shopping List:", from_ =twilioNum, to=myNum)
for keys,values in item_dict.items():
if keys == "" or values =="":
pass
else:
msg=twilioCli.messages.create(body='\n' + str(keys)+' '+ str(values) + '\n', from_=twilioNum, to=myNum)
how can i send sms in one msg vs multiples?
This is a very straight forward thing and I am confused. Please explain to me why twilio sends separate sms messages vs one?
program is simple, I have a grocery list, in the form of a dictionary and user checks items and enters a quantity. it iterates thru dictionary and should send checked items in the body of sms. But in my case i see multiple items. Thank you in advance
Twilio developer evangelist here.
You have one message being sent in the second line that just contains the string "Your Shopping List:".
To send as one message, I'd modify how you iterate through the key, value pairs in your dictionary so you move the for loop to the end like this:
for keys,values in item_dict.items():
if keys == "" or values =="":
pass
msg2Send = "Your Shopping List: \n" + \
('\n'.join(f'{key}: {value}' for key, value in item_dict.items()))
msg = twilioCli.messages.create(
body=msg2Send, from_="twilioNum", to="myNum")
Let me know if this helps at all!

Use one inline query to lead into another inline query? Telegram Bot (Python)

My bot passes a simple string (query.query) through a function that returns a "big" dictionary with many subdictionaries (each representing "card" data) inside it. As it works right now, all keys and values for all returned subdictionaries get displayed in-line (until pagination limit). So for example, writing "blue" will return the key:value pairs for all subdictionaries whose card name == "blue".
I want the bot to first display inline results for card names and, after the user chooses a card, for the bot to display the rest of the card data, so the user can choose what part to send in chat. This would look like:
User queries the word "blue" and makes card titles for "blue blob", "blue drake", "blue beard" appear in-line
User select "blue beard" from that menu, making bot then display available data for "blue-beard" in-line (stats, attack, etc.)
Here's a snippet of said code. Check the # comment to see where I think it all breaks down
#bot.inline_handler(lambda query: len(query.query) > 3)
def query_card(inline_query):
temp_names_list = []
results_list = []
try:
sound_dict = scrape(inline_query.query)
for key, sub_dict in sound_dict.items():
temp_names_list.append(types.InlineQueryResultArticle(id=key, title=sub_dict['Name'], input_message_content=types.InputTextMessageContent(sub_dict['Name'])))
bot.answer_inline_query(inline_query.id, temp_names_list, cache_time=1)
#The code breaks down here since I haven't found a way of passing the result to ^ this answer_inline_query into the next part of the loop:
for key, sub_dict in sound_dict.items():
for k, v in sub_dict.items():
if k == ['message']['text']:
results_list.append(types.InlineQueryResultArticle(id=key+k, title=k, input_message_content=types.InputTextMessageContent(sub_dict['Name']+"\'s ["+k+"] bit:\n"+v)))
#results_list.append(types.InlineQueryResultVoice(id=k, voice_url=v, title="^ "+sound_dict['Name']+"\'s ["+k+"] bit:\n"+v, caption=sound_dict['Name']+"\'s ["+k+"] bit"))
bot.answer_inline_query(inline_query.id, results_list, cache_time=1)
except Exception as e:
print(e)

Search the nth number of string in side the another list in python

add name, where is a string denoting a contact name. This must store as a new contact in the application.
find partial, where is a string denoting a partial name to search the application for. It must count the number of contacts starting with and print the count on a new line.
Given sequential add and find operations, perform each operation in order.
Input:
4
add hack
add hackerrank
find hac
find hak
Sample Output
2
0
We perform the following sequence of operations:
1.Add a contact named hack.
2.Add a contact named hackerrank.
3.Find and print the number of contact names beginning with hac.
There are currently two contact names in the application
and both of them start with hac, so we print 2 on a new line.
4.Find and print the number of contact names beginning with hak.
There are currently two contact names in the application
but neither of them start with hak, so we print 0 on a new line.
i solved it but it is taking long time for large number of string. my code is
addlist =[]
findlist=[]
n = int(input().strip())
for a0 in range(n):
op, contact = input().strip().split(' ')
if(op=='add'):
addlist.append(contact)
else:
findlist.append(contact)
for item in findlist:
count=0
count=[count+1 for item2 in addlist if item in item2 if item==item2[0:len(item)]]
print(sum(count))
is there any other way to avoid the long time to computation.
As far as optimizing goes I broke your code apart a bit for readability and removed a redundant if statement. I'm not sure if its possible to optimize any further.
addlist =[]
findlist=[]
n = int(input().strip())
for a0 in range(n):
op, contact = input().strip().split(' ')
if(op=='add'):
addlist.append(contact)
else:
findlist.append(contact)
for item in findlist:
count = 0
for item2 in addlist:
if item == item2[0:len(item)]:
count += 1
print(count)
I tested 10562 entries at once and it processed instantly so if it lags for you it can be blamed on your processor

Resources