Google Contacts v3 API + How to add a contact to a group? - google-contacts-api

I can do a CRUD with a contact or a group, but I can't figure out how to add a contact to a specific group.
Someone can help me?

def get_group_id(label_name):
feed = gd_client.GetGroups()
for entry in feed.entry:
if entry.title.text.lower() == label_name:
return entry.id.text
contact_entry = gdata.contacts.data.ContactEntry() #contact_entry
group = get_group_id(label_name) #group id
membership = gdata.contacts.data.GroupMembershipInfo(href=group) #group membership
contact_entry.group_membership_info.append(membership) # adding group membership to contact_entry

Related

Capturing Campaign through Ampscript in email giving duplicate records

Our requirement is to capture campaign information during send time through Ampscript. ask is to capture data extension name, jobid and publication list for every campaign(unique DE-Jobid pair). I am able to populate DE with details, however we see duplicate records with same DE-Jobid pair. find the snippet below
SET #Job_Id = jobid
SET #DE = _DataSourceName
SET #Publication_List = AttributeValue("_listname")
SET #Campaign_Name = emailName_
set #date = NOW()
set #campaign_found = LookupRows("Campaign_Details_CDT","Job_ID", #Job_Id,"Segment_Name", #DE)
set #rowcount = rowcount(#campaign_found)
IF(#rowcount == 0) THEN
InsertDE("Campaign_Details_CDT", "Job_ID", #Job_Id, "Campaign_Name", #Campaign_Name, "Segment_Name", #DE, "Sent_Date", #date, "Publication_List", #Publication_List)
ENDIF
]%%````
I will appreciate your help to find reason for this.

MySQL sql ignoring WHERE condition

I have the following problem - I am coding an e-commerce website, that has promotions for a certain period of time. When time elapses promotion changes its corresponding database active value to 0. When I check for promotions the first condition is that active=1, but at some cases MySQL is ignoring it.
Here is an example of my most recent problem:
$productPromotion = $db->getResults('*', TABLE_PROMO, "active = '1'
AND (discount_subject = 'all_orders'
OR discount_subject_product = ".$values['product']['id'].")
OR (discount_subject = 'category'
AND discount_subject_category = ".$categoryId[0] . ") ORDER BY id ASC");
$db->getResult is a custom function that takes 3 parameters - What, Table and Where.
The problem is that it is returning promotions that are already expired and have active=0. Where is the problem with my sql?
You have to add brackets arround or
$productPromotion = $db->getResults('*', TABLE_PROMO, "active = '1'
AND
((discount_subject = 'all_orders' OR discount_subject_product = ".$values['product']['id'].")
OR (discount_subject = 'category' AND discount_subject_category = ".$categoryId[0] . ")) ORDER BY id ASC");
Also learn about prepared Statements to prevent SQL-injection

Subquerying in Django

I have a Django 1.9 project implementing small chat app. All messages from a certain recipient are grouped into dialogs, so the models are defined as follows:
class Dialog(models.Model):
# Some fields
class Message(models.Model):
dialog = models.ForeignKey(Dialog, ...)
text = models.TextField()
is_read = models.BooleanField(default = False)
My goal is to render a template with a table that renders dialogs. And for each dialog in the table, I need to see
the number of unread messages and
the text of the last message.
To illustrate, consider mock-data below:
Input:
id dialog_id message is_read
1 1 Hello, sir false
2 1 My name is true
3 1 Jack true
4 2 This site false
5 2 is perfect false
6 2 Cheers false
Desired output:
dialog_id last_message_in_dialog unread_messages_count
1 Jack 1
2 Cheers 3
In pure mysql, I would write a query like this:
select
a.dialog_id,
text as last_message_in_dialog,
(select count(*) from message
where dialog_id = a.dialog_id and is_read = false) as unread_messages_count
from message a
where id in (select max(id) from message group by dialog_id)
In Django terms, I have the code below:
max_id_qs = Message.objects.\
values('dialog__id').\
annotate(max_id = Max('id'),).values('max_id')
qs = Message.objects.filter(id__in = max_id_qs).\
values('dialog__id', 'text')
This code serves well to fetch the last message in each dialog. However, the problem is that I can't figure out how to implement the subquery (select count(*) from message where dialog_id = a.dialog_id and is_read = false) in Django. Maybe my total approach with max_id_qsis wrong, and there's more elegant and clear way to implement the query in Django ORM?
I've spent an entire day trying to solve this issue. help me please !
This will work :-
allDistinctIdWithNotReadMsg =
Message.objects.filter(is_read=False).values('id').annotate(the_count=Count('is_read',distinct('id')))
for ids in allDistinctIdWithNotReadMsg:
lastMsg = Message.objects.filter(dialog_id=ids['id']).order_by("-id")[0]
for msg in lastMsg:
print ids['id'] ,msg.message,ids['the_count']

Difficult Rails ActiveModel Query

I am building a Rails app which has a User model, joined to a Interests model through a has_many :through relationship using a UserInterests join model.
Given a set of interests, what I want to do is find all users who have selected at least one interest in that set, OR who have not selected any interests at all. I am thinking of something a bit like this:
users = users.joins(:user_interests).where(["COUNT(user_interests) = 0 OR user_interests.interest_id IN ?", interest_ids])
This raises a Mysql syntax error. Any ideas how to achieve this?
Many thanks
try this one,
users = User.joins(:user_interests).where("COUNT(user_interests) = 0 OR interest_id IN (?)", interest_ids)
class User < ActiveRecord::Base
scope :with_interests, ->(*interests) {
joins(:user_interests).where(user_interests: {interest_id: interests.flatten.compact.uniq})
}
scope :no_interests, -> {
where("not exists (select * from user_interests ui2 where ui2.user_id = users.id)")
}
end
interest = Interest.first
User.with_interests(interest) + User.no_interests
This worked for me - although it is not 100% ideal.
Add a user_interests_count field to users with a counter_cache
Search using a LEFT JOIN query:
users = User.joins("LEFT JOIN user_interests ON user_interests.user_id = users.id").where("(users.user_interests_count = ?) OR user_interests.interest_id IN (?)", 0, interest_ids)

Generate a spending report from the following tables

My current project is to generate a spending report from the following tables. The complete report is to show a user's spending $ breakdown by Franchise's retail category, such as
User 1
retail_category 1: $20
retail_category 2: $30
retail_category 3: $35
User 2
retail_category 1: $10
retail_category 2: $15
retail_category 3: $5
Here are the tables:
class User(models.Model):
id_user = models.AutoField(primary_key = True)
class Franchises(models.Model):
id_franchise = models.AutoField(primary_key=True)
retail_category = models.IntegerField(default=99) # values are 1 to 13
class Stores(models.Model):
id_store = models.AutoField(primary_key=True)
franchise = models.ForeignKey(Franchises, db_column='id_franchise')
class Receipts(models.Model):
id_receipt = models.AutoField(primary_key=True)
store = models.ForeignKey(Stores, db_column='id_store')
user = models.ForeignKey(User, db_column='id_user')
grand_total = models.DecimalField(max_digits=19, decimal_places=4)
I'd appreciate any raw mysql or django model query. Thanks,
Hopefully I'm translating your django schema spec to raw mysql correctly:
SELECT user, retail_category, SUM(grand_total)
FROM Receipts
INNER JOIN Stores ON Receipts.store = Stores.id_store
INNER JOIN Franchises ON Stores.franchise = Franchises.id_franchise
GROUP BY user, retail_category;