-
Notifications
You must be signed in to change notification settings - Fork 0
/
CRM.R
483 lines (358 loc) · 19.4 KB
/
CRM.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
########################################################################################
#Now perform CRM analysis
########################################################################################
getwd()
setwd("/home/bi_user/Automation/Reports/CRM")
rm(list = ls(all=TRUE))
#Provide new paths to libraries
.libPaths("/home/bi_user/R/x86_64-pc-linux-gnu-library/3.3/")
library(lubridate)
library(zoo)
library(dplyr)
library(mongolite)
library(jsonlite)
library(data.table)
library(reshape2)
library(tidyr)
library(stringr)
library(stringi)
#Load data
load("DataToCRM.dat")
collections <- c("intwash_notifications","ratings")
notifications_connection <- mongo(collection = collections[1], db = "uk_live",
url = "mongodb://172.31.51.215:27017",verbose = TRUE)
ratings_connection <- mongo(collection = collections[2], db = "uk_live",
url = "mongodb://172.31.51.215:27017",verbose = TRUE)
notifications <- notifications_connection$find(fields = '{"_id":1,"email":1,"publicReference":1,"newsletterSubscribed":1,"reference":1}')
ratings <- ratings_connection$find(fields = '{"_id":1,"appVersion":1,"orderReference":1,
"customerReference":1,"rating":1,"skipped":1,"topics":1}')
#####################################################
#Work with phones
#####################################################
#Check list inside the dataframe
#phones <- customers_table[,c(1,2)]
#colnames(phones) <- c("id","ph")
#phones <- data.table(phones)
#Expands the data frame
#phones_temp1 <- as.data.table(phones)[,unlist(ph),by=id] #expands without types, aka names
#phones_temp <- phones[, .(phnames = names(unlist(ph)), phvalues = unlist(ph)), by = id] #expands with names
#Aggregate by values, transform from long to wide format
#phones_temp <- dcast(phones_temp,id~phnames, value.var = 'phvalues')
#Replace with 2 number if applicable
#phones_temp$number <- ifelse(is.na(phones_temp$number),phones_temp$number1,phones_temp$number)
#Check whether vector has NAs
#sum(is.na(phones_temp$number)) > 0
#Left join
#phones <- merge(x = phones[,1,with=F],y = phones_temp, by="id", all.x = T )
#Subset phones
#phones <- phones[,.(id,number,type)]
#####################################################
#Work with addresses
#####################################################
#Check another list inside the dataframe
addresses <- customers_table[,c(1,4)]
colnames(addresses) <- c("id","adr")
addresses <- data.table(addresses)
#Here I removed all empty rows
#addresses <- addresses[first_non_null_index,]
first_non_null_index <- which(!unlist(lapply(addresses$adr,is.null)))[1]
first_null_index <- which(unlist(lapply(addresses$adr,is.null)))[1]
intermediate <- addresses[first_null_index,]
addresses[first_null_index,] <- addresses[first_non_null_index,]
addresses[first_non_null_index,] <- intermediate
#Expands the data frame
adr_temp <- addresses[, .(adrnames = names(unlist(adr)), adrvalues = unlist(adr)), by = id]
#Aggregate by values, transform from long to wide format
adr_temp <- dcast(adr_temp,id~adrnames, value.var = "adrvalues",
fun.aggregate = function(x) paste(x, collapse=""))
#Replace empty strings with data from another col
adr_temp$addressLine <- ifelse(str_length(adr_temp$addressLine)==0,adr_temp$addressLine1,adr_temp$addressLine)
adr_temp$addressLine2 <- ifelse(str_length(adr_temp$addressLine2)==0,adr_temp$addressLine21,adr_temp$addressLine2)
adr_temp$zip <- ifelse(str_length(adr_temp$zip)==0,adr_temp$zip1,adr_temp$zip)
adr_temp <- data.table(adr_temp)
#Subset the address lines and zip
adr_temp <- adr_temp[,.(id,addressLine,addressLine2,zip)]
#Merge
addresses <- merge(x = addresses[,1,with=F],y = adr_temp, by="id", all.x = T )
#####################################################
#Work with tags
#####################################################
names(customers_table)
#tags <- customers_table[,c("_id","meta.tags")]
#tags <- data.table(tags)
#Rename columns in a list
#colnames(tags) <- c("id","tags")
#first_non_null_index_t <- which(!unlist(lapply(tags$tags,is.null)))
#first_non_empty_list_t <- first_non_null_index_t[which(tags[first_non_null_index_t,lapply(tags,length)] != 0)[1]]
#first_null_index_t <- which(unlist(lapply(tags$tags,is.null)))[1]
#intermediate_tags <- tags[first_non_empty_list_t,]
#tags[first_null_index_t,] <- tags[first_non_empty_list_t,]
#tags[first_non_empty_list_t,] <- intermediate_tags
#tags <- tags[, .(tagnames = names(unlist(tags)), tagvalues = unlist(tags)), by = id]
#tags <- tags[,lapply(tags, unlist),by=id]
#tags <- flatten(tags)
#tags$tags <- unlist(tags$tags)
#####################################################
#Move to main body
#####################################################
crm <- customers_table[,c(1,3,5:10)] #Here the person name is appended
crm <- flatten(crm)
str(crm)
colnames(crm)[1] <- c("id")
#Convert person names to ACSII characters
crm$person.name <- stri_trans_general(crm$person.name,"latin-ascii")
#crm <- merge(x = crm, y = tags, by = "id", all.x = T)
#colnames(crm)[9] <- c("tags")
#####################################################
#Now work with orders
#####################################################
orders_table <- flatten(orders_table)
str(orders_table)
#####################################################
#Try to split the user Agent
#####################################################
#Try to split the userByAgent
#str_split_fixed(orders_table$createdBy.userAgent,"()",4)
#out <- strsplit(as.character(orders_table$createdBy.userAgent),";")
#data.frame(orders_table$new,do.call(rbind,out))
#list <- strsplit(orders_table$createdBy.userAgent,";")
#orders_table$device_temp <- NULL
#orders_table$device_temp <- gsub("[\\(\\)]","", orders_table$createdBy.userAgent) #remove everything before semicolon
#orders_table$device_temp <- gsub(";.*$","", orders_table$device_temp) #remove parenthesis
#orders_table$device_temp <- sub(".+? ", "", orders_table$device_temp) #remove string before first whitespace
orders_table$device <- NULL
orders_table$device[(grepl("iPhone",orders_table$createdBy.userAgent)==T)] = "iOS app"
orders_table$device[(grepl("Android",orders_table$createdBy.userAgent)==T)] = "android app"
orders_table$device[(!is.na(orders_table$createdBy.userAgent)
& !grepl("^(iOS)",orders_table$device)
& !grepl("^(android)",orders_table$device))] = "web app"
#Check tha table
table(orders_table$device)
sum(!is.na(orders_table$device))
#create device by customer
orders_table <- data.table(orders_table)
#Add isvalid column (first, initialize default value, then, adjust by particular state)
orders_table$isvalid = 1 #initialize isvalid
orders_table$isvalid[which(orders_table$state %in% c("new","payment_authorisation_error",
"canceled","reserved"))] = 0
#Extract Service Class from the string
orders_table$serviceClass <- sapply(as.character(orders_table$chosenServiceClass.reference),
function(x) {
unlist(strsplit(x,'-',fixed = T))[2]})
#Create a dataframe with total orders
totalOrders <- orders_table[,.(sum(length(unique(reference)))),by=.(customer)]
colnames(totalOrders) <- c("customer","totalOrders")
#Check total orders
sum(totalOrders$totalOrders)
length(unique(orders_table$reference))
#Make order summary, providing firstOrderDate, lastOrderDate,sumOfValidOrders,#of VouchersUsed
orders_summary <- orders_table[isvalid==1,.(min(createdAt),max(createdAt),sum(isvalid),sum(!is.na(voucherCode))),by=.(customer)]
colnames(orders_summary) <- c("customer","firstOrder","lastOrder","validOrders","VouchersUsed")
#Create a dataframe for ServiceClasses
long <- orders_table[,.(reference,serviceClass)]
wide <- dcast(long,reference~serviceClass,value.var = "serviceClass") #order(left side) ~ to serviceClass(right side), by serviceClass
names(wide)
#Reformat into numbers
wide$ClassicN <- ifelse(is.na(wide$CLASSIC),0,1)
wide$ExpressN <- ifelse(is.na(wide$EXPRESS),0,1)
wide$LiteN <- ifelse(is.na(wide$LITE),0,1)
wide$PersilN <- ifelse(is.na(wide$PERSIL),0,1)
wide$PlusN <- ifelse(is.na(wide$PLUS),0,1)
#Check the number of reformatted classes
sum(wide$ClassicN)+sum(wide$ExpressN)+sum(wide$LiteN)+sum(wide$PersilN)+sum(wide$PlusN)
sum(!is.na(orders_table$serviceClass))
#Now merge the wide stuff back into orders subset
orders_table <- merge(x = orders_table, y = wide[,c("reference","ClassicN","ExpressN","LiteN","PersilN","PlusN")], by='reference', all.x = T)
#Calculate orders by class
classes <- orders_table[isvalid==1,.(sum(ClassicN),sum(ExpressN),sum(LiteN),sum(PersilN),sum(PlusN)),by=.(customer)]
colnames(classes) <- c("customer","Classic","Express","Lite","Persil","Plus")
#Merge back to orders summary
orders_summary <- merge(x = orders_summary, y = classes, by = 'customer', all.x = T)
orders_summary$NoClass <- orders_summary$validOrders-orders_summary$Classic-orders_summary$Express-orders_summary$Lite-orders_summary$Persil-orders_summary$Plus
#Merge to crm
colnames(crm)[1] <- c("customer") #remember that customer from crm is id in the final table
#Count Open order
orders_table$openOrder = 1 #initialize isvalid
orders_table$openOrder[which(orders_table$state %in% c("canceled","completed"))] = 0
orders_table$canceledOrder = 0 #initialize isvalid
orders_table$canceledOrder[which(orders_table$state %in% c("canceled"))] = 1
customer_stat <- orders_table[,.(min(locationIdentifier),min(device),sum(openOrder),sum(canceledOrder)),by=.(customer)]
colnames(customer_stat) <- c("customer","City","Device","OpenOrders","CanceledOrders")
colnames(addresses)[1] <- c("customer")
#####################################################
#MERGE STEP BY STEP TO CRM
#####################################################
#Merge customer_stat with crm, left join
crm <- merge(x = crm, y = customer_stat, by = "customer",all.x = T)
#Left join orders_summary
crm <- merge(x = crm, y = orders_summary, by = "customer", all.x = T )
#Left join total orders
crm <- merge(x = crm, y = totalOrders, by = "customer", all.x = T)
#Left join addresses
crm <- merge(x = crm, y = addresses, by = "customer", all.x = T)
crm$CustomerStatus = "NA"
crm$CustomerStatus[which(crm$validOrders==1)] <- "New"
crm$CustomerStatus[which(crm$validOrders>1)] <- "Returning"
#####################################################
#Deal with ratings
#####################################################
#Unlist the column
colnames(ratings)[3] <- c("reference")
#Remove duplicates
ratings <- ratings[!duplicated(ratings$reference),]
#Make a subset
ratings_subset <- ratings[,c("reference","topics")]
ratings_subset <- data.table(ratings_subset)
#Unlist
rating_temp <- ratings_subset[, .(ratnames = names(unlist(topics)), ratvalues = unlist(topics)), by = reference]
rating_temp <- dcast(rating_temp,reference ~ ratnames, value.var = "ratvalues",
fun.aggregate = function(x) paste(x, collapse=""))
crm$CustomerStatus[which(crm$validOrders==1)] <- "New"
crm$CustomerStatus[which(crm$validOrders>1)] <- "Returning"
#####################################################
#Deal with ratings
#####################################################
#Unlist the column
colnames(ratings)[3] <- c("reference")
#Remove duplicates
ratings <- ratings[!duplicated(ratings$reference),]
#Make a subset
ratings_subset <- ratings[,c("reference","topics")]
ratings_subset <- data.table(ratings_subset)
#####################################################
#Deal with ratings
#####################################################
#Unlist the column
colnames(ratings)[3] <- c("reference")
#Remove duplicates
ratings <- ratings[!duplicated(ratings$reference),]
#Make a subset
ratings_subset <- ratings[,c("reference","topics")]
ratings_subset <- data.table(ratings_subset)
#Unlist
rating_temp <- ratings_subset[, .(ratnames = names(unlist(topics)), ratvalues = unlist(topics)), by = reference]
rating_temp <- dcast(rating_temp,reference ~ ratnames, value.var = "ratvalues",
fun.aggregate = function(x) paste(x, collapse=""))
#Right join rating to rating_temp
rating_temp <- merge(x = rating_temp, y = ratings[,c("reference","rating")], by = "reference", all.y = T)
orders_table <- merge(x = orders_table, y = rating_temp, by = "reference", all.x = T)
#Create last rating for every customer
names(orders_table)
colnames(orders_table)[22:27] <- c("Punctuality","CleaningQ","DamagedI","DriverB","IroningQ","MissingI")
last_rating <- orders_table[,.(max(rating),max(Punctuality),max(CleaningQ),max(IroningQ)), by = .(customer)]
colnames(last_rating) <- c("customer","rating","Punctuality","CleaningQ","IroningQ")
#Merge ratings to crm
crm <- merge(x = crm , y = last_rating, by = "customer", all.x = T)
#####################################################
#Deal with notifications
#####################################################
notifications <- data.table(notifications)
names(notifications)
#notifications_lastValue <- notifications[,list(c(lastpublicRef = publicReference[.N],lastSubscribed=newsletterSubscribed)),email]
notifications_lastpublicRef <- notifications[,list(lastpublicRef = publicReference[.N]),email]
notifications_lastnewsSubs <- notifications[,list(lastnewsSubs = newsletterSubscribed[.N]),email]
notifications_last <- cbind(x = notifications_lastpublicRef, y = notifications_lastnewsSubs)
notifications_last <- notifications_last[,.(x.email,x.lastpublicRef,y.lastnewsSubs)]
colnames(notifications_last) <- c("email","publicReference","newsletterSubscribed")
colnames(crm)[3] <- c("email")
crm <- merge(x = crm, y = notifications_last, by = "email", all.x = T)
#####################################################
#Deal with credits
#####################################################
#Set the folders
from_folder <- "/home/bi_user/sisense_share"
to_folder <- "/home/bi_user/Automation/Reports/CRM/"
#Identify files
list_files <- list.files(from_folder,"branch_credits.csv",full.names = T)
#Copy the files
file.copy(list_files,to=to_folder,overwrite = T)
credits <- read.csv("branch_credits.csv",header = T,sep = ";")
colnames(credits)[1] <- c("reference")
#Merge credits with crm, left join
crm <- merge(x = crm , y = credits, by = "reference", all.x = T)
crm$last_updated <- NULL #Drop the last column
#####################################################
#Deal with RFM
#####################################################
colnames(new_data)[1] <- "reference"
crm <- merge( x = crm, y = new_data, by = "reference", all.x = T)
#Check unique values
length(unique(crm$customer))
length(unique(crm$reference))
#####################################################
#Beautify
#####################################################
#Paste
crm$SubscriberKey <- paste("ZJ",crm$customer,sep = '_')
#Reformat dates
crm$firstOrder <- as.Date(crm$firstOrder,"%Y-%m-%d")
crm$lastOrder <- as.Date(crm$lastOrder,"%Y-%m-%d")
crm$DiffFirstOrderDate <- difftime(time1 = Sys.Date(),
time2 = crm$firstOrder,
units = 'days')
crm$IndividualFreq <- difftime(time1 = crm$lastOrder,
time2 = crm$firstOrder,
units = "days") / (crm$validOrders-1)
crm$FirstName <- gsub(" .*$","",crm$person.name)
#Subset columns
#crm <- crm[,c(1:24,27:52)]
crm$amount <- round(crm$amount,0)
crm$IndividualFreq <- round(crm$IndividualFreq,0)
crm$overtime <- round((difftime(time1 = Sys.Date(),
time2 = crm$lastOrder,
units = 'days') - crm$IndividualFreq),0)
crm$addressLine <- NULL
crm$addressLine2 <- NULL
#Convert to numeric
crm[,c("DiffFirstOrderDate","IndividualFreq","overtime",
"OpenOrders","CanceledOrders","validOrders","VouchersUsed",
"Classic","Express","Lite","Persil","Plus","NoClass",
"totalOrders","rating","Punctuality","IroningQ","CleaningQ",
"newsletterSubscribed","branch_credits","recency","frequency","amount",
"rankR","rankRecencyPoints","rankF","rankFrequencyPoints","rankM",
"rankMonetaryPoints","sum","class","classfactor")] <- sapply(crm[,c("DiffFirstOrderDate","IndividualFreq","overtime",
"OpenOrders","CanceledOrders","validOrders","VouchersUsed",
"Classic","Express","Lite","Persil","Plus","NoClass",
"totalOrders","rating","Punctuality","IroningQ","CleaningQ",
"newsletterSubscribed","branch_credits","recency","frequency","amount",
"rankR","rankRecencyPoints","rankF","rankFrequencyPoints","rankM",
"rankMonetaryPoints","sum","class","classfactor")],as.numeric)
#Replace specific columns of NA with 0
crm[c("DiffFirstOrderDate","IndividualFreq","overtime",
"OpenOrders","CanceledOrders","validOrders","VouchersUsed",
"Classic","Express","Lite","Persil","Plus","NoClass",
"totalOrders","rating","Punctuality","IroningQ","CleaningQ",
"newsletterSubscribed","branch_credits","recency","frequency","amount",
"rankR","rankRecencyPoints","rankF","rankFrequencyPoints","rankM",
"rankMonetaryPoints","sum","class","classfactor")][is.na(crm[c("DiffFirstOrderDate","IndividualFreq","overtime",
"OpenOrders","CanceledOrders","validOrders","VouchersUsed",
"Classic","Express","Lite","Persil","Plus","NoClass",
"totalOrders","rating","Punctuality","IroningQ","CleaningQ",
"newsletterSubscribed","branch_credits","recency","frequency","amount",
"rankR","rankRecencyPoints","rankF","rankFrequencyPoints","rankM",
"rankMonetaryPoints","sum","class","classfactor")])] <- 0
crm[,c("firstOrder","lastOrder")] <- sapply(crm[, c("firstOrder","lastOrder")], function(x){format(x,format = "%Y-%m-%d")})
crm[,c("firstOrder","lastOrder")][is.na(crm[, c("firstOrder","lastOrder")])] <- ""
#Check types of variables in the dataframe
str(crm)
names(crm)
colnames(crm)[8] <- c("LanguageCode")
#####################################################
#Get the provider Data
#####################################################
orders_collection <- c("intwash_orders")
provider <- mongo(collection = orders_collection, db = "uk_live",
url = "mongodb://172.31.51.215:27017",verbose = TRUE)
provider_data <- provider$find(fields = '{"paymentData.provider":1,"customer":1}')
#Flatten the data frame
provider_data <- flatten(provider_data)
length(unique(provider_data$customer))
#Create a df with first value by customer
provider_data <- data.table(provider_data)
providerByCustomer <- provider_data[, paymentData.provider[1],by=customer]
colnames(providerByCustomer) <- c("customer","provider")
#Merge to crm
crm <- merge(x = crm , y = providerByCustomer, by = "customer", all.x = TRUE)
#Write to a specific folder that is shared with another machine/server
#write.csv(crm, file="/home/dima/sisense_share/crm_full_list.csv",row.names = FALSE)
write.csv(crm, file="/home/bi_user/powerbi-share/R_outputs/crm_full_list.csv",row.names = FALSE)