Skip to content

Instantly share code, notes, and snippets.

@apalevich
Last active February 26, 2020 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apalevich/c16e622bf049961e3e4a011c18c21fa2 to your computer and use it in GitHub Desktop.
Save apalevich/c16e622bf049961e3e4a011c18c21fa2 to your computer and use it in GitHub Desktop.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using web.laredoute.su.Helpers;
namespace web.laredoute.su.Controllers
{
public class NPSController : Controller
{
static Dictionary<string, string> QuestionList = new Dictionary<string, string>()
{
{ "NPS", "NPS" },
{ "QUESTION2", "Что Вы посоветуете нам, чтобы мы могли предложить Вам лучший шопинг?" },
{ "QUESTION31", "Предлагаемый нами ассортимент" },
{ "QUESTION32", "Привлекательность товаров" },
{ "QUESTION33", "Соотношение цена/качество" },
{ "QUESTION4", "Расскажите нам больше об уровне удовлетворенности нашими товарами" },
{ "QUESTION51", "Сервис по возврату неподошедших вещей" },
{ "QUESTION52", "Способы оплаты, предлагаемые Ла Редут" },
{ "QUESTION53", "Способы доставки, предлагаемые Ла Редут" },
{ "QUESTION54", "Сроки доставки" },
{ "QUESTION55", "Информирование клиента на этапе между размещением заказа и его доставкой" },
{ "QUESTION56", "Расскажите нам больше о том, удовлетворены ли Вы нашим сервисом" },
{ "QUESTION6", "В какой степени Вы согласны со следующим утверждением: \"компания облегчила мне процесс совершения покупок\"?" },
{ "QUESTION7", "Что нам нужно улучшить, чтобы облегчить Вам шопинг у нас?" },
{ "QUESTION8", "Можете ли Вы выбрать из нижеприведенного списка до 3-х брендов, которые Вы приобретали?" },
{ "QUESTION91", "Asos рейтинг" },
{ "QUESTION101", "Asos комментарий" },
{ "QUESTION92", "Bonprix рейтинг" },
{ "QUESTION102", "Bonprix комментарий" },
{ "QUESTION93", "Lamoda рейтинг" },
{ "QUESTION103", "Lamoda комментарий" },
{ "QUESTION94", "Mango рейтинг" },
{ "QUESTION104", "Mango комментарий" },
{ "QUESTION95", "Zara рейтинг" },
{ "QUESTION105", "Zara комментарий" },
{ "QUESTION96", "Wildberries рейтинг" },
{ "QUESTION106", "Wildberries комментарий" },
{ "QUESTION97", "Amazon рейтинг" },
{ "QUESTION107", "Amazon комментарий" },
{ "QUESTION98", "Aliexpress рейтинг" },
{ "QUESTION108", "Aliexpress комментарий" },
{ "QUESTION99", "Kiabi рейтинг" },
{ "QUESTION109", "Kiabi комментарий" },
{ "QUESTION910", "H&M рейтинг" },
{ "QUESTION1010", "H&M комментарий" },
{ "QUESTION11", "Для завершения опроса, пожалуйста, расскажите в двух словах, за что Вы любите в Ла Редут?" },
{ "QUESTION12", "Можем ли мы позвонить Вам и задать несколько вопросов по оставленным ответам и комментариям?" },
{ "QUESTION13", "Укажите, пожалуйста, Ваш телефон и удобное время для связи" }
};
static Dictionary<string, string> StatsQuestionList = new Dictionary<string, string>()
{
{ "NPS", "NPS" },
{ "QUESTION31", "Предлагаемый нами ассортимент" },
{ "QUESTION32", "Привлекательность товаров" },
{ "QUESTION33", "Соотношение цена/качество" },
{ "QUESTION51", "Сервис по возврату неподошедших вещей" },
{ "QUESTION52", "Способы оплаты, предлагаемые Ла Редут" },
{ "QUESTION53", "Способы доставки, предлагаемые Ла Редут" },
{ "QUESTION54", "Сроки доставки" },
{ "QUESTION55", "Информирование клиента на этапе между размещением заказа и его доставкой" },
{ "QUESTION6", "В какой степени Вы согласны со следующим утверждением: \"компания облегчила мне процесс совершения покупок\"?" }
};
private struct Survey
{
public string iid;
public string cid;
public string oid;
public Dictionary<string, string> questions;
}
private class Stat
{
public int Amount;
public List<StatQuestion> Questions;
}
private class StatQuestion
{
public int Amount;
public string Key;
public string KeyTranslated;
public List<StatAnswer> Answers;
}
private class StatAnswer
{
public int Amount;
public string Value;
}
// GET: NPS
public ActionResult Index()
{
return View();
}
public async Task<string> Submit()
{
Response.ContentType = "application/json";
string json = new StreamReader(Request.InputStream).ReadToEnd();
if (string.IsNullOrEmpty(json))
{
return jsonResponse("No data", true);
}
var result = string.Empty;
var survey = JsonConvert.DeserializeObject<Survey>(json);
object objResult = null;
objResult = Helpers.DB.ExecuteScalar(@"BEGIN
DECLARE @i int = 5
IF (SELECT COUNT([InvoiceID]) FROM [NPS_Survey].[dbo].[NPS] WHERE [InvoiceID] = @InvoiceID) > 0
BEGIN
SET @i=1
END
ELSE
BEGIN
INSERT INTO [NPS_Survey].[dbo].[NPS] ([InvoiceID], [OrderID], [CustomerID], [DateEntry]) VALUES (@InvoiceID, @OrderID, @CustomerID, @DateEntry)
SET @i=2
END
SELECT @i
END",
new SqlParameter[] {
new SqlParameter("@InvoiceID", survey.iid),
new SqlParameter("@OrderID", survey.oid),
new SqlParameter("@CustomerID", survey.cid),
new SqlParameter("@DateEntry", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.FFF"))
}, "vc_fc");
if (objResult != null)
{
if (string.Equals(objResult.ToString(), "2"))
{
//пишем ответы
DataTable Questions = new DataTable();
DataColumn COLUMN = new DataColumn();
COLUMN.ColumnName = "InvoiceID";
COLUMN.DataType = typeof(string);
Questions.Columns.Add(COLUMN);
COLUMN = new DataColumn();
COLUMN.ColumnName = "Question";
COLUMN.DataType = typeof(string);
Questions.Columns.Add(COLUMN);
COLUMN = new DataColumn();
COLUMN.ColumnName = "Answer";
COLUMN.DataType = typeof(string);
Questions.Columns.Add(COLUMN);
foreach (var question in survey.questions)
{
DataRow DR = Questions.NewRow();
DR[0] = survey.iid;
DR[1] = question.Key;
DR[2] = question.Value.Replace("\n", " ");
//DR[2] = "\"" + question.Value.Replace("\"", "") + "\"";
Questions.Rows.Add(DR);
}
SqlParameter Parameter = new SqlParameter("@Questions", SqlDbType.Structured);
Parameter.Value = Questions;
Parameter.TypeName = "dbo.NPS_Answer_Type";
/*INSERT INTO[NPS_Survey].[dbo].[NPS_Answer] ([InvoiceID], [Question], [CustomerID], [Answer]) VALUES*/
Helpers.DB.ExecuteNonQuery(@"INSERT INTO [NPS_Survey].[dbo].[NPS_Answer] SELECT * FROM @Questions", new SqlParameter[] { Parameter }, "nps_fc");
}
else
{
//уже есть
return jsonResponse("Already sent", false);
}
}
else
{
//ошибка не удалось проверить
return jsonResponse("Unable to check", true);
}
return result;
}
[FilterIp]
public ActionResult Stats()
{
return View();
}
[FilterIp]
public async Task<string> StatsByDate()
{
var result = string.Empty;
if (!string.IsNullOrEmpty(Request.QueryString["datefrom"]) && !string.IsNullOrEmpty(Request.QueryString["dateto"]))
{
var DateFrom = DateTime.Parse(Request.QueryString["datefrom"]);
var DateTo = DateTime.Parse(Request.QueryString["dateto"]);
var stat = new Stat
{
Amount = 0,
Questions = new List<StatQuestion>()
{
new StatQuestion() { Amount = 0, Key = "NPS", KeyTranslated = "NPS", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "0"
},
new StatAnswer() {
Amount = 0,
Value = "1"
},
new StatAnswer() {
Amount = 0,
Value = "2"
},
new StatAnswer() {
Amount = 0,
Value = "3"
},
new StatAnswer() {
Amount = 0,
Value = "4"
},
new StatAnswer() {
Amount = 0,
Value = "5"
},
new StatAnswer() {
Amount = 0,
Value = "6"
},
new StatAnswer() {
Amount = 0,
Value = "7"
},
new StatAnswer() {
Amount = 0,
Value = "8"
},
new StatAnswer() {
Amount = 0,
Value = "9"
},
new StatAnswer() {
Amount = 0,
Value = "10"
},
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION31", KeyTranslated = "Предлагаемый нами ассортимент", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION32", KeyTranslated = "Привлекательность товаров", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION33", KeyTranslated = "Соотношение цена/качество", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION51", KeyTranslated = "Сервис по возврату неподошедших вещей", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Совсем не удовлетворительно"
},
new StatAnswer() {
Amount = 0,
Value = "Не очень удовлетворительно"
},
new StatAnswer() {
Amount = 0,
Value = "Довольно удовлетворительно"
},
new StatAnswer() {
Amount = 0,
Value = "Вполне удовлетворительно"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION52", KeyTranslated = "Способы оплаты, предлагаемые Ла Редут", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION53", KeyTranslated = "Способы доставки, предлагаемые Ла Редут", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION54", KeyTranslated = "Сроки доставки", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION55", KeyTranslated = "Информирование клиента на этапе между размещением заказа и его доставкой", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично не удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Частично удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью удовлетворен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Затрудняюсь ответить"
}
}
},
new StatQuestion() { Amount = 0, Key = "QUESTION6", KeyTranslated = "В какой степени Вы согласны со следующим утверждением: \"компания облегчила мне процесс совершения покупок\"?", Answers = new List<StatAnswer>()
{
new StatAnswer() {
Amount = 0,
Value = "Полностью не согласен(-на)"
},
new StatAnswer() {
Amount = 0,
Value = "Не согласен(-на)"
},
new StatAnswer() {
Amount = 0,
Value = "В чем-то не согласен(-а)"
},
new StatAnswer() {
Amount = 0,
Value = "Нейтрален(-ьна)"
},
new StatAnswer() {
Amount = 0,
Value = "В чем-то согласен(-на)"
},
new StatAnswer() {
Amount = 0,
Value = "Согласен(-на)"
},
new StatAnswer() {
Amount = 0,
Value = "Полностью согласен(-на)"
}
}
}
}
};
foreach (var survey in DB.SurveyByDate(DateFrom, DateTo))
{
stat.Amount++;
foreach (var question in survey.Questions)
{
if (StatsQuestionList.ContainsKey(question.Question))
{
var q = stat.Questions.Find(x => x.Key.Equals(question.Question));
if (q == null)
{
stat.Questions.Add(new StatQuestion() { Amount = 1, Answers = new List<StatAnswer>() { new StatAnswer() { Amount = 1, Value = question.Answer } }, Key = question.Question, KeyTranslated = QuestionList[question.Question] });
}
else
{
q.Amount++;
var a = q.Answers.Find(x => x.Value.Equals(question.Answer.Replace("Затрудняюсь ответить(-а)", "Затрудняюсь ответить")));
if (a == null)
{
q.Answers.Add(new StatAnswer() { Amount = 1, Value = question.Answer });
}
else
{
a.Amount++;
}
}
}
}
}
result = JsonConvert.SerializeObject(stat);
}
return result;
}
[FilterIp]
public FileContentResult SurveyByDate()
{
var result = string.Empty;
FileContentResult file = null;
try
{
result += "\"InvoiceID\";\"OrderID\";\"CustomerID\";\"DateEntry\";";
foreach (var item in QuestionList)
{
result += "\"" + item.Key + "\";";
}
result += Environment.NewLine;
result += "\"InvoiceID\";\"OrderID\";\"CustomerID\";\"DateEntry\";";
foreach (var item in QuestionList)
{
result += "\"" + item.Value + "\";";
}
result += Environment.NewLine;
if (!string.IsNullOrEmpty(Request.QueryString["datefrom"]) && !string.IsNullOrEmpty(Request.QueryString["dateto"]))
{
var DateFrom = DateTime.Parse(Request.QueryString["datefrom"]);
var DateTo = DateTime.Parse(Request.QueryString["dateto"]);
foreach (var survey in DB.SurveyByDate(DateFrom, DateTo))
{
result += "\"" + survey.InvoiceID + "\";";
result += "\"" + survey.OrderID + "\";";
result += "\"" + survey.CustomerID + "\";";
result += "\"" + survey.DateEntry + "\";";
foreach (var item in QuestionList)
{
var answer = string.Empty;
var question = survey.Questions.Find(x => x.Question.Equals(item.Key));
if (question != null)
{
answer = question.Answer;
}
result += "\"" + answer.Replace("\"", "'") + "\";";
}
result += Environment.NewLine;
}
}
file = File(System.Text.Encoding.GetEncoding(1251).GetBytes(result), "text/csv", "SurveyByDate.csv");
}
catch (Exception e)
{
int a = 1;
int b = 2;
int c = a + b;
}
return file;
}
private string jsonResponse(string text, bool error = false)
{
return JsonConvert.SerializeObject(
new
{
error = error == true ? "true" : "false",
data = text
}
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment