├── assets
├── logo.png
├── star.png
└── logo-small.png
├── templates
├── layout.hdbs
└── form.hdbs
├── manifest.json
├── translations
├── zh.json
├── ko.json
├── ja.json
├── ru.json
├── da.json
├── pt.json
├── fr.json
├── nl.json
├── de.json
├── it.json
├── es.json
└── en.json
├── app.css
├── README.md
├── LICENSE
└── app.js
/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zendesk/back_at_ya/master/assets/logo.png
--------------------------------------------------------------------------------
/assets/star.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zendesk/back_at_ya/master/assets/star.png
--------------------------------------------------------------------------------
/assets/logo-small.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zendesk/back_at_ya/master/assets/logo-small.png
--------------------------------------------------------------------------------
/templates/layout.hdbs:
--------------------------------------------------------------------------------
1 |
6 |
7 |
--------------------------------------------------------------------------------
/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Back@Ya",
3 | "author": {
4 | "name": "Zendesk Labs",
5 | "email": "zendesklabs@zendesk.com"
6 | },
7 | "defaultLocale": "en",
8 | "private": false,
9 | "location": "ticket_sidebar",
10 | "version": "1.0",
11 | "frameworkVersion": "1.0"
12 | }
13 |
--------------------------------------------------------------------------------
/translations/zh.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"代理能率用户","name":"代理满意度应用"},"help":"您如何评 价与该客户的体验?
点击一个明星来选择你的评价:
5 =非常满意
1 =非常不满意
黄星代表平均等级老乡代理商。绿色星星代表什么你曾经对此顾客这张票。
评级被存储在用户现场agent_satisfaction和评级平均存储在agent_satisfaction_average(对于视图,触发器,报告)。","field_error":"
错误
您必须添加文本agent_satisfaction和小数agent_satisfaction_average用户字段。","give_it_stars":"给它","average":"平均","ratings":"评级","rate_requester":"速度:","be_the_first_to_rate":"成为第一位评论!","rate_success":"评价保存","rate_error_request":"保存时出错评级","heading_ticket":"票","heading_agent":"代理人","heading_rating":"等级"}
--------------------------------------------------------------------------------
/templates/form.hdbs:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 | {{{t "help"}}}
15 |
16 |
17 | {{{t "field_error"}}}
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/translations/ko.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"에이전트는 사용자를 평가할 수 있습니다","name":"에이전트 만족도 앱"},"help":"당신은 어떻게이 고객과의 경험을 평가한다면?
귀하의 평가를 선택하는 스타를 클릭
5 = 매우 만족
1 = 매우 불만족
노란색 별이 동료 에이전트가 평균 점수를 나타냅니다. 녹색 성이 티켓에이 고객이 평가 한 것을 나타냅니다.
평가는 사용자 필드 agent_satisfaction 및 평가의 평균이 (뷰, 트리거,보고) agent_satisfaction_average에 저장됩니다에 저장됩니다.","field_error":" 오류
당신은 텍스트 agent_satisfaction 진수 agent_satisfaction_average 사용자 필드를 추가해야합니다.","give_it_stars":"그것을 제공","average":"평균","ratings":"평가","rate_requester":"평가 :","be_the_first_to_rate":"평가하려면 첫번째로 올려주세요!","rate_success":"평가 저장","rate_error_request":"오류 절약 평가","heading_ticket":"표","heading_agent":"대리인","heading_rating":"평가"}
--------------------------------------------------------------------------------
/translations/ja.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"エージェントは、ユーザーが評価することができます","name":"エージェントの満足度のApp"},"help":"どのようにこの顧客とのあなたの経験を評価するだろうか?
あなたの評価を選択して星をクリックしてください。
5 =非常に満足
1 =非常に不満
黄色の星は、仲間のエージェントごとの平均評価を表している。緑の星は、このチケットにこの顧客を評価したものを表しています。
格付けは、ユーザフィールドagent_satisfactionと評価の平均に保存されている(ビュー、トリガ、レポート作成のために)agent_satisfaction_averageに格納されている。","field_error":"エラー
あなたは、テキストagent_satisfactionと小数agent_satisfaction_averageユーザーフィールドを追加する必要があります。","give_it_stars":"それを与える","average":"平均","ratings":"評価","rate_requester":"レート:","be_the_first_to_rate":"評価しよう!","rate_success":"評価保存","rate_error_request":"エラー省評価","heading_ticket":"チケット","heading_agent":"エージェント","heading_rating":"評価"}
--------------------------------------------------------------------------------
/translations/ru.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Агенты могут оценить пользователи","name":"Агент Удовлетворение App"},"help":"Как бы вы оценили ваш опыт работы с этим клиентом?
Нажмите звезду выбрать Оценить:
5 = Очень доволен
1 = Очень недоволен
Желтые звезды представляют Средний рейтинг по коллег агентов. Зеленые звезды представляют то, что вы дали оценку этим клиентом на этом билете.
Оценки хранятся в пользовательском поле agent_satisfaction и рейтинг среднем хранится в agent_satisfaction_average (для представлений, триггеров, отчетность).","field_error":" Ошибка
Вы должны добавить текст agent_satisfaction и десятичные пользовательские поля agent_satisfaction_average.","give_it_stars":"Дайте ему","average":"Средний","ratings":"Оценки","rate_requester":"Цена:","be_the_first_to_rate":"Будьте первым, чтобы оценить!","rate_success":"Рейтинг сохранен","rate_error_request":"Ошибка рейтинг экономия","heading_ticket":"Билет","heading_agent":"Агент","heading_rating":"Рейтинг"}
--------------------------------------------------------------------------------
/translations/da.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Agenter kan bedømme brugere","name":"Agent Tilfredshed App"},"help":"Hvordan vil du vurdere din oplevelse med denne kunde?
Klik på en stjerne for at vælge din bedømmelse:
5 = meget tilfreds
1 = meget utilfreds
Gule stjerner repræsenterer den gennemsnitlige bedømmelse af kollega agenter. Grønne stjerner repræsenterer, hvad du har bedømt denne kunde på denne billet.
Ratings er gemt i brugerens område agent_satisfaction og rating gennemsnit er gemt i agent_satisfaction_average (for visninger, udløser, rapportering).","field_error":" Fejl
Du skal tilføje tekst agent_satisfaction og decimaler agent_satisfaction_average brugernes felter.","give_it_stars":"Giv det","average":"Gennemsnitlig","ratings":"Ratings","rate_requester":"Rate:","be_the_first_to_rate":"Vær den første til at stemme!","rate_success":"Rating gemt","rate_error_request":"Fejl besparelse bedømmelse","heading_ticket":"Billet","heading_agent":"Agent","heading_rating":"Rating"}
--------------------------------------------------------------------------------
/translations/pt.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Os agentes podem avaliar usuários","name":"Agente Satisfação App"},"help":"Como você classificaria a sua experiência com este cliente?
Clique uma estrela para escolher a sua classificação:
5 = muito satisfeito
1 = Muito insatisfeito
Estrelas amarelas representam a classificação média por outros agentes. Estrelas verdes representam o que você classificou este cliente com este bilhete.
As avaliações são armazenadas no campo agent_satisfaction usuário e avaliação média é armazenado em agent_satisfaction_average (para vistas, triggers, relatórios).","field_error":" Erro
Você deve adicionar agent_satisfaction texto e campos de usuário decimais agent_satisfaction_average.","give_it_stars":"Dê-lhe","average":"Média","ratings":"Pontuações","rate_requester":"Taxa:","be_the_first_to_rate":"Seja o primeiro a avaliar!","rate_success":"Classificação salvo","rate_error_request":"Erro classificação poupança","heading_ticket":"Bilhete","heading_agent":"Agente","heading_rating":"Classificação"}
--------------------------------------------------------------------------------
/translations/fr.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Les agents peuvent évaluer utilisateurs","name":"Agent de satisfaction App"},"help":"Comment évaluez-vous votre expérience avec ce client?
Cliquez sur une étoile de choisir votre note:
5 = très satisfait
1 = Très insatisfait
Étoiles jaunes représentent la note moyenne attribuée par d'autres agents. Étoiles vertes représentent ce que vous avez noté ce client sur ce billet.
Les notes sont stockées dans le champ agent_satisfaction d'utilisateur et moyenne de notation est stocké dans agent_satisfaction_average (pour les vues, les triggers, rapports).","field_error":" Erreur
Vous devez ajouter au texte agent_satisfaction et les champs d'utilisateur agent_satisfaction_average décimales.","give_it_stars":"Donnez-lui","average":"Moyenne","ratings":"Évaluations","rate_requester":"Taux:","be_the_first_to_rate":"Soyez le premier à évaluer!","rate_success":"Note sauvé","rate_error_request":"Erreur note d'économie","heading_ticket":"Billet","heading_agent":"Agent","heading_rating":"Évaluation"}
--------------------------------------------------------------------------------
/translations/nl.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Agenten kunnen gebruikers waarderen","name":"Agent Tevredenheid App"},"help":"Hoe zou u uw ervaring met deze klant waardeert?
Klik op een ster om te kiezen voor je beoordeling:
5 = Zeer tevreden
1 = Zeer ontevreden
Gele sterren vertegenwoordigen de gemiddelde classificatie door collega-agenten. Groene sterren vertegenwoordigen wat u deze klant hebben beoordeeld op dit ticket.
Ratings worden opgeslagen in de gebruiker veld agent_satisfaction en classificatie gemiddelde wordt opgeslagen in agent_satisfaction_average (voor views, triggers, rapportage).","field_error":" Fout
U moet tekst agent_satisfaction en decimale agent_satisfaction_average gebruiker velden toevoegen.","give_it_stars":"Geef het","average":"Gemiddelde","ratings":"Ratings","rate_requester":"Tarief:","be_the_first_to_rate":"Wees de eerste om te beoordelen!","rate_success":"Rating opgeslagen","rate_error_request":"Fout bij het opslaan cijfer","heading_ticket":"Ticket","heading_agent":"Agent","heading_rating":"Rating"}
--------------------------------------------------------------------------------
/translations/de.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Agenten können Benutzer bewerten","name":"Agent-Satisfaction-App"},"help":"Wie würden Sie Ihre Erfahrungen mit diesem Kunden bewerten?
Klicken Sie auf einen Stern, um Ihre Bewertung zu wählen:
5 = Sehr zufrieden
1 = sehr unzufrieden
Gelbe Sterne repräsentieren die durchschnittliche Bewertung von Kolleginnen Mittel. Grüne Sterne darzustellen, was Sie der Kunde auf diesem Ticket bewertet haben.
Ratings werden im Benutzerfeld agent_satisfaction und Rating Durchschnitt wird in agent_satisfaction_average gespeichert ist (Views, Trigger, Reporting) gespeichert.","field_error":" Fehler
Sie müssen Text und agent_satisfaction dezimal agent_satisfaction_average Benutzerfelder hinzufügen.","give_it_stars":"Geben Sie es","average":"Durchschnitt","ratings":"Bewertungen","rate_requester":"Rate:","be_the_first_to_rate":"Die Erster bewerten!","rate_success":"Bewertung gespeichert","rate_error_request":"Fehler beim Speichern Bewertung","heading_ticket":"Ticket","heading_agent":"Agent","heading_rating":"Wertung"}
--------------------------------------------------------------------------------
/translations/it.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Gli agenti possono votare gli utenti","name":"Agente Soddisfazione App"},"help":"Come giudichi la tua esperienza con questo cliente?
Fare clic su una stella per scegliere il tuo voto:
5 = Molto soddisfatto
1 = Molto insoddisfatto
Stelle gialle rappresentano la valutazione media da altri agenti. Stelle verdi rappresentano quello che hai valutato questo cliente su questo biglietto.
Le valutazioni vengono memorizzati nel utente agent_satisfaction campo e punteggio medio è memorizzato in agent_satisfaction_average (per le viste, trigger, segnalazione).","field_error":" Errore
È necessario aggiungere agent_satisfaction testo e campi utente agent_satisfaction_average decimali.","give_it_stars":"Dategli","average":"Media","ratings":"Valutazioni","rate_requester":"Valuta:","be_the_first_to_rate":"Sarai il primo a votare!","rate_success":"Valutazione salvato","rate_error_request":"Valutazione Errore durante il salvataggio","heading_ticket":"Biglietto","heading_agent":"Agente","heading_rating":"Valutazione"}
--------------------------------------------------------------------------------
/translations/es.json:
--------------------------------------------------------------------------------
1 | {"app":{"description":"Los agentes pueden votar usuarios","name":"Satisfacción Agente App"},"help":"¿Cómo calificaría su experiencia con este cliente?
Haga clic en una estrella para elige una puntuación:
5 = Muy Satisfecho
1 = Muy insatisfecho
Estrellas amarillas representan la media de puntuación por parte de otros agentes. Estrellas verdes representan lo que usted ha calificado este cliente en este billete.
Las puntuaciones se almacenan en la agent_satisfaction campo de usuario y nota media se almacena en agent_satisfaction_average (para las vistas, disparadores, la presentación de informes).","field_error":" Error
Debe añadir agent_satisfaction texto y campos de usuario agent_satisfaction_average decimales.","give_it_stars":"Déle","average":"Promedio","ratings":"Valoraciones","rate_requester":"Cambio:","be_the_first_to_rate":"Sea el primero en evaluar!","rate_success":"Clasificación ahorrado","rate_error_request":"Error calificación ahorro","heading_ticket":"Billete","heading_agent":"Agente","heading_rating":"Clasificación"}
--------------------------------------------------------------------------------
/translations/en.json:
--------------------------------------------------------------------------------
1 | {
2 | "app": {
3 | "description": "Agents can rate users",
4 | "name": "Agent Satisfaction App"
5 | },
6 | "help": "How would you rate your experience with this customer?
Click a star to choose your rating:
5 = Very Satisfied
1 = Very Dissatisfied
Yellow stars represent the average rating by fellow agents. Green stars represent what you have rated this customer on this ticket.
Ratings are stored in the user field agent_satisfaction and rating average is stored in agent_satisfaction_average (for views, triggers, reporting).",
7 | "field_error": "Error
You must add text agent_satisfaction and decimal agent_satisfaction_average user fields.",
8 | "give_it_stars": "Give it",
9 | "average": "Average",
10 | "ratings": "Ratings",
11 | "rate_requester": "Rate: ",
12 | "be_the_first_to_rate": "Be the first to rate!",
13 | "rate_success": "Rating saved",
14 | "rate_error_request": "Error saving rating",
15 | "heading_ticket": "Ticket",
16 | "heading_agent": "Agent",
17 | "heading_rating": "Rating"
18 | }
19 |
--------------------------------------------------------------------------------
/app.css:
--------------------------------------------------------------------------------
1 | .rating_list{
2 | padding-top: 10px;
3 | }
4 |
5 | table th{
6 | text-align: left;
7 | }
8 |
9 | table td, table th{
10 | padding-right: 10px;
11 | }
12 |
13 | .faq{
14 | float: right;
15 | width: 15px;
16 | line-height: 26px;
17 | font-weight: bold;
18 | cursor: pointer;
19 | }
20 |
21 | .play {
22 | float: right;
23 | height: 25px;
24 | margin-right: 8px;
25 | }
26 |
27 | .faq_content, .rating_list, .field_error {
28 | display: none;
29 | }
30 |
31 | .rating {
32 | cursor: pointer;
33 | margin: 2em 0;
34 | clear: both;
35 | display: block;
36 | }
37 | .rating:after {
38 | content: '.';
39 | display: block;
40 | height: 0;
41 | width: 0;
42 | clear: both;
43 | visibility: hidden;
44 | }
45 | .cancel, .star {
46 | float: left;
47 | width: 34px;
48 | height: 32px;
49 | overflow: hidden;
50 | text-indent: -999em;
51 | cursor: pointer;
52 | }
53 | .star,
54 | .star a {background: app-asset-url("star.png") no-repeat 0 0px;}
55 |
56 | .cancel a,
57 | .star a {
58 | display: block;
59 | width: 100%;
60 | height: 100%;
61 | background-position: 0 0px; // white
62 | }
63 |
64 | div.rating div.on a {
65 | background-position: 0 -32px; // yellow
66 | }
67 |
68 | div.rating div.hover a,
69 | div.rating.mine div.on a,
70 | div.rating div a:hover {
71 | background-position: 0 -64px; // red
72 | }
73 |
74 | .average-first, .average-overview{
75 | display: none;
76 | }
77 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | :warning: *Use of this software is subject to important terms and conditions as set forth in the License file* :warning:
2 |
3 | # Back@Ya 
4 |
5 | ## Description:
6 |
7 | ### Install Back@Ya to allow your agents to rate your customers
8 |
9 | ### Rate customers for any purpose you choose:
10 | - Measure agent satisfaction by ticket and build an average agent satisfaction score by individual customer
11 | - Report (in Good Data) on agent satisfaction rating by customer and compare to their account
12 | - Route negative customer interactions to speciality agents to try and improve their support experience
13 | - Build custom workflows around customers with low or high agent satisfaction scores
14 | - Identify evangelists through high agent satisfaction scores
15 |
16 | ## Screenshot(s):
17 |
18 | Unrated view, see average of other agents:
19 | 
20 |
21 | Rated view, see your rating and average:
22 | 
23 |
24 | See ratings of other agents:
25 | 
26 |
27 | Translated in 12 languages:
28 | 
29 |
30 | Error message when misconfigured:
31 | 
32 |
33 | ### Install
34 |
35 | Within your Zendesk account (where you are an admin):
36 |
37 | - Download .zip file from http://tinyurl.com/asatapp
38 | - Click the gear symbol in the lower left corner
39 | - Under the Apps menu, select Manage Apps
40 | - Click on Upload App
41 | - Upload .zip file as a new App
42 | - Create Custom User Fields:
43 | - agent_satisfaction (text)
44 | - agent_satisfaction_average (decimal)
45 |
46 | ### After Installation
47 |
48 | Rating a customer for the first time:
49 |
50 | - Open a ticket and you'll see the app in the right sidebar
51 | - Select a rating (from 1 to 5 stars) based on your interaction with the customer (green stars)
52 | - After a customer has been rated at least once, you'll see an agent average (yellow stars) and have the ability to see a list of all the agents that have rated this customer
53 | - If your agents have questions on how to use this app, simple access documentation in the app via the question mark and a hover menu will pop up
54 |
55 | Reporting on Back@Ya:
56 |
57 | - Select “# of Ratings” to see tickets numbers and agents for all ratings this customer has received
58 | - Use “Agent Satisfaction Average” via Good Data to leverage for reporting
59 | - Ratings are stored in two user fields which can be used in business rules and with views: agent_satisfaction and rating average is stored in agent_satisfaction_average
60 |
61 | ### App location:
62 |
63 | * Ticket sidebar
64 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2013 Zendesk
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
14 |
15 | Capitalized terms used herein have the meaning set forth in the Zendesk, Inc.
16 | (“Zendesk”) Terms of Service (available at www.zendesk.com/company/terms) (the “Terms”).
17 | The software made available herein constitutes “ZendeskLabs Software” which may be
18 | implemented to enable features or functionality to be utilized in connection with a
19 | subscription to the Service.
20 | Notwithstanding anything to the contrary set forth in the Terms or any other
21 | agreement by and between you and Zendesk, ZendeskLabs Software is provided
22 | “AS IS” and on an “AS AVAILABLE” basis, and that Zendesk makes no warranty
23 | as to the ZendeskLabs Software.
24 |
25 | ZENDESK DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
26 | TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
27 | NONINFRINGEMENT AND THOSE ARISING FROM A COURSE OF DEALING OR USAGE OF TRADE
28 | RELATED TO THE ZENDESKLABS SOFTWARE, ITS USE OR ANY INABILITY TO USE IT OR
29 | THE RESULTS OF ITS USE.
30 |
31 | Use of ZendeskLabs Software is subject to the following risks and conditions:
32 | (i) the ZendeskLabs Software is not an component of the Service that
33 | has been designed for commercial release for by Zendesk;
34 |
35 | (ii) the ZendeskLabs Software may not be in final form and may contain errors,
36 | design flaws or other problems; (iii) the ZendeskLabs Software is not expected to
37 | function fully or adequately upon installation, and it is expected and anticipated that
38 | further testing, modification and development may be necessary to make the
39 | ZendeskLabs Software functional;
40 |
41 | (iv) it may not be possible to make the ZendeskLabs Software functional;
42 |
43 | (v) use of the ZendeskLabs Software may result in unexpected results, loss of data,
44 | project delays or other unpredictable damage or loss; and
45 |
46 | (vi) Zendesk is under no obligation to release and/or offer for sale commercial
47 | versions of the ZendeskLabs Software, and Zendesk has the right to unilaterally
48 | abandon development or availability of the ZendeskLabs Software at any time and
49 | without any obligation or liability to You. You further agree that Zendesk shall
50 | have no obligation to correct any bugs, defects or errors in the ZendeskLabs Software
51 | or otherwise to support or maintain the ZendeskLabs Software.
52 |
53 | If you elect to utilize any ZendeskLabs Software, you are agreeing to release Zendesk
54 | from any claim with regard to the ZendeskLabs Software, its operation, availability or
55 | its failure to operate or be available. Without limiting the generality of the foregoing,
56 |
57 | You acknowledge and agree that neither the use, availability nor operation of any
58 | ZendeskLabs Software shall be subject to any service level commitment applicable to the Service.
--------------------------------------------------------------------------------
/app.js:
--------------------------------------------------------------------------------
1 | (function() {
2 | return {
3 | requests: {
4 | load: function(user_id) {
5 | return {
6 | url: helpers.fmt('/api/v2/users/%@.json', user_id),
7 | dataType: 'JSON',
8 | type: 'GET',
9 | contentType: 'application/json'
10 | };
11 | },
12 | save: function(user_id, data) {
13 | return {
14 | url: helpers.fmt('/api/v2/users/%@.json', user_id),
15 | dataType: 'JSON',
16 | type: 'PUT',
17 | contentType: 'application/json',
18 | data: JSON.stringify(data)
19 | };
20 | },
21 | many: function(user_ids){
22 | return {
23 | url: helpers.fmt('/api/v2/users/show_many.json?ids=%@', user_ids),
24 | dataType: 'JSON',
25 | type: 'GET',
26 | contentType: 'application/json'
27 | };
28 | }
29 | },
30 |
31 | events: {
32 | 'app.activated': 'init',
33 | 'click .faq': 'faq',
34 | 'click .list_ratings': 'list'
35 | },
36 |
37 | init: function() {
38 | var requester = this.ticket().requester();
39 | this.$(".heading").html(this.I18n.t("rate_requester") + requester.name());
40 |
41 | if(requester){
42 | this.loading(this.$(".rating"));
43 | this._handleRequest(this.ajax('load', requester.id()), function(data){
44 | this.switchTo('form');
45 | if(data.user.user_fields.agent_satisfaction !== undefined && data.user.user_fields.agent_satisfaction_average !== undefined){
46 | this.requester = data.user;
47 | this.rateit(this.$);
48 | } else {
49 | this.$(".rating").hide();
50 | this.$(".field_error").show();
51 | }
52 | }, this.notifyFail);
53 | } else {
54 | alert("TODO NO REQUESTER");
55 | }
56 | },
57 |
58 | // toggle the faq page
59 | faq: function(){
60 | this.$(".form, .faq_content").toggle();
61 | },
62 |
63 | list: function(){
64 | this.showingList = !this.showingList;
65 | var dom = this.$(".rating_list");
66 | dom.toggle(this.showingList);
67 | if(this.showingList){
68 | // show loading
69 | this.loading(dom);
70 |
71 | // get ids of all raters
72 | var ratings = this.ratings.replace(";", "").split(";");
73 | var ids = [];
74 | for(var x = 0; x < ratings.length; x ++) {
75 | ids.push(ratings[x].split(",")[0]);
76 | }
77 |
78 | // fetch these users and build html
79 | var user, values;
80 | var list = "";
81 | list += "| "+this.I18n.t("heading_ticket") + " | ";
82 | list += ""+this.I18n.t("heading_agent")+" | ";
83 | list += ""+this.I18n.t("heading_rating")+" |
";
84 | this._handleRequest(this.ajax('many', ids.join(",")), function(data){
85 | for(var x = 0; x < ratings.length; x ++) {
86 | for(var y = 0; y < data.users.length; y ++) {
87 | user = data.users[y];
88 | values = ratings[x].split(",");
89 | if(user.id === parseInt(values[0], 10)){
90 | // link to ticket + link to user + rating
91 | list += "";
92 | list += "| #"+values[1]+" | ";
93 | list += ""+user.name+" | ";
94 | list += "" + values[2] +" | ";
95 | list += "
";
96 | }
97 | }
98 | }
99 | list += "
";
100 |
101 | // fill list
102 | dom.html(list);
103 | }, this.notifyFail);
104 | }
105 | },
106 |
107 | loading: function(dom){
108 | dom.html("
");
109 | },
110 |
111 | rateit: function($){
112 | var jQuery = $;
113 | var self = this;
114 | var current = this.requester.user_fields.agent_satisfaction_average || 0;
115 | this.ratings = (this.requester.user_fields.agent_satisfaction || "");
116 | var container = $(".rating");
117 | this.updateAverage(this.ratings, current);
118 |
119 | // show my rating if I have rated
120 | var match = this.ratings.match(new RegExp(this.mine() + "(\\d)"));
121 | if(match){
122 | current = parseInt(match[1], 10);
123 | container.addClass("mine");
124 | }
125 |
126 | // Rest
127 | var settings = {
128 | maxvalue : 5, // max number of stars
129 | curvalue : Math.round(current || 0) // number of selected stars
130 | };
131 |
132 | container.averageRating = settings.curvalue;
133 |
134 | for(var i= 1; i <= settings.maxvalue ; i++){
135 | var div;
136 | var size = i;
137 | div = '';
138 | container.append(div);
139 | }
140 |
141 | var stars = container.children('.star');
142 |
143 | stars
144 | .mouseover(function(){
145 | event.drain();
146 | event.fill(this);
147 | })
148 | .mouseout(function(){
149 | event.drain();
150 | event.reset();
151 | })
152 | .focus(function(){
153 | event.drain();
154 | event.fill(this);
155 | })
156 | .blur(function(){
157 | event.drain();
158 | event.reset();
159 | });
160 |
161 | stars.click(function(){
162 | settings.curvalue = stars.index(this) + 1;
163 | var rating = jQuery(this).children('a')[0].href.split('#')[1];
164 | self.submitRating(rating);
165 | container.addClass("mine");
166 | return false;
167 | });
168 |
169 | var event = {
170 | fill: function(el){ // fill to the current mouse position.
171 | var index = stars.index(el) + 1;
172 | stars
173 | .children('a').css('width', '100%').end()
174 | .slice(0, index).addClass('hover').end();
175 | },
176 | drain: function() { // drain all the stars.
177 | stars
178 | .filter('.on').removeClass('on').end()
179 | .filter('.hover').removeClass('hover').end();
180 | },
181 | reset: function(){ // Reset the stars to the default index.
182 | stars.slice(0, settings.curvalue).addClass('on').end();
183 | }
184 | };
185 | event.reset();
186 | },
187 |
188 | mine: function(){
189 | return ";" + this.currentUser().id() + "," + this.ticket().id() + ",";
190 | },
191 |
192 | updateAverage: function(ratings, average){
193 | this.$(".average-overview").toggle(average !== 0);
194 | this.$(".average-first").toggle(average === 0);
195 | this.$(".average").html(average);
196 | this.$(".ratings_count").html(ratings.split(";").length - 1);
197 | },
198 |
199 | submitRating: function(rating){
200 | if(this.showingList){ this.list(); } // close the list so we do not show inconsistent data
201 |
202 | var mine = this.mine();
203 | this.ratings = this.ratings.replace(new RegExp(mine + "\\d"), "");
204 | this.ratings += mine + rating;
205 | var average = this.average(this.ratings);
206 | this.updateAverage(this.ratings, average);
207 |
208 | var data = {
209 | "user": {
210 | "user_fields": {
211 | "agent_satisfaction": this.ratings,
212 | "agent_satisfaction_average": average
213 | }
214 | }
215 | };
216 |
217 | this._handleRequest(this.ajax('save', this.requester.id, data), this.notifySuccess, this.notifyFail);
218 | },
219 |
220 | average: function(ratings){
221 | ratings = ratings.replace(";","").split(";");
222 | var sum = 0;
223 | var els;
224 | for(var x = 0; x < ratings.length; x ++) {
225 | els = ratings[x].split(",");
226 | sum += parseInt(els[els.length - 1], 10);
227 | }
228 |
229 | return sum / ratings.length;
230 | },
231 |
232 | _handleRequest: function(request, success, fail) {
233 | this.when.apply(this, [request]).done(_.bind(success, this))
234 | .fail(_.bind(fail, this));
235 | },
236 |
237 | notifySuccess: function() {
238 | services.notify(this.I18n.t('rate_success'));
239 | },
240 |
241 | notifyFail: function() {
242 | services.notify(this.I18n.t('rate_error_request'), 'error');
243 | }
244 | };
245 | }());
246 |
--------------------------------------------------------------------------------