1
0
mirror of synced 2024-11-22 04:26:01 +03:00

add localization, improve template

This commit is contained in:
DmitryZagorulko 2018-05-18 18:11:09 +03:00 committed by Alex Lushpai
parent 1009eb57e9
commit 204266df16
7 changed files with 206 additions and 75 deletions

View File

@ -10,15 +10,43 @@ import (
"regexp"
"github.com/getsentry/raven-go"
"github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/retailcrm/api-client-go/v5"
"github.com/retailcrm/mg-transport-api-client-go/v1"
"golang.org/x/text/language"
"gopkg.in/yaml.v2"
)
var (
templates = template.Must(template.ParseFiles("templates/form.html", "templates/home.html"))
templates = template.Must(template.ParseFiles("templates/header.html", "templates/form.html", "templates/home.html"))
validPath = regexp.MustCompile("^/(save|settings)/([a-zA-Z0-9]+)$")
localizer *i18n.Localizer
bundle = &i18n.Bundle{DefaultLanguage: language.English}
matcher = language.NewMatcher([]language.Tag{
language.English,
language.Russian,
language.Spanish,
})
)
func init() {
bundle.RegisterUnmarshalFunc("yml", yaml.Unmarshal)
files, err := ioutil.ReadDir("translate")
if err != nil {
logger.Error(err)
}
for _, f := range files {
if !f.IsDir() {
bundle.MustLoadMessageFile("translate/" + f.Name())
}
}
}
func setLocale(al string) {
tag, _ := language.MatchStrings(matcher, al)
localizer = i18n.NewLocalizer(bundle, tag.String())
}
// Response struct
type Response struct {
Success bool `json:"success"`
@ -53,8 +81,19 @@ func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.Handl
}
func connectHandler(w http.ResponseWriter, r *http.Request) {
setLocale(r.Header.Get("Accept-Language"))
p := Connection{}
renderTemplate(w, "home", &p)
res := struct {
Conn *Connection
Locale map[string]interface{}
}{
&p,
map[string]interface{}{
"ButConnect": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "but_connect"}),
},
}
renderTemplate(w, "home", &res)
}
func addBotHandler(w http.ResponseWriter, r *http.Request) {
@ -73,13 +112,13 @@ func addBotHandler(w http.ResponseWriter, r *http.Request) {
}
if b.Token == "" {
http.Error(w, "set bot token", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "no_bot_token"}), http.StatusInternalServerError)
return
}
cl, _ := getBotByToken(b.Token)
if cl.ID != 0 {
http.Error(w, "bot already created", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "bot_already_created"}), http.StatusInternalServerError)
return
}
@ -94,13 +133,13 @@ func addBotHandler(w http.ResponseWriter, r *http.Request) {
c, err := getConnection(b.ClientID)
if err != nil {
http.Error(w, "could not find account, please contact technical support", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "not_find_account"}), http.StatusInternalServerError)
logger.Error(b.ClientID, err.Error())
return
}
if c.MGURL == "" || c.MGToken == "" {
http.Error(w, "could not find account, please contact technical support", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "not_find_account"}), http.StatusInternalServerError)
logger.Error(b.ClientID)
return
}
@ -118,7 +157,7 @@ func addBotHandler(w http.ResponseWriter, r *http.Request) {
var client = v1.New(c.MGURL, c.MGToken)
data, status, err := client.ActivateTransportChannel(ch)
if status != http.StatusCreated {
http.Error(w, "error while activating the channel", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "error_activating_channel"}), http.StatusInternalServerError)
logger.Error(c.APIURL, status, err.Error(), data)
return
}
@ -133,7 +172,9 @@ func addBotHandler(w http.ResponseWriter, r *http.Request) {
return
}
jsonString, _ := json.Marshal(b)
w.WriteHeader(http.StatusCreated)
w.Write(jsonString)
}
func activityBotHandler(w http.ResponseWriter, r *http.Request) {
@ -164,14 +205,14 @@ func activityBotHandler(w http.ResponseWriter, r *http.Request) {
c, err := getConnection(b.ClientID)
if err != nil {
http.Error(w, "could not find account, please contact technical support", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "not_find_account"}), http.StatusInternalServerError)
logger.Error(b.ClientID, err.Error())
return
}
if c.MGURL == "" || c.MGToken == "" {
http.Error(w, "could not find account, please contact technical support", http.StatusInternalServerError)
logger.Error(b.ClientID, "could not find account, please contact technical support")
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "not_find_account"}), http.StatusInternalServerError)
logger.Error(b.ClientID, "not find account")
return
}
@ -180,14 +221,14 @@ func activityBotHandler(w http.ResponseWriter, r *http.Request) {
if b.Active {
data, status, err := client.DeactivateTransportChannel(ch.ID)
if status > http.StatusOK {
http.Error(w, "error while deactivating the channel", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "error_deactivating_channel"}), http.StatusInternalServerError)
logger.Error(b.ClientID, status, err.Error(), data)
return
}
} else {
data, status, err := client.ActivateTransportChannel(ch)
if status > http.StatusCreated {
http.Error(w, "error while activating the channel", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "error_activating_channel"}), http.StatusInternalServerError)
logger.Error(b.ClientID, status, err.Error(), data)
return
}
@ -228,6 +269,8 @@ func mappingHandler(w http.ResponseWriter, r *http.Request) {
}
func settingsHandler(w http.ResponseWriter, r *http.Request, uid string) {
setLocale(r.Header.Get("Accept-Language"))
p, err := getConnection(uid)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
@ -249,10 +292,22 @@ func settingsHandler(w http.ResponseWriter, r *http.Request, uid string) {
Conn *Connection
Bots Bots
Sites map[string]v5.Site
Locale map[string]interface{}
}{
p,
bots,
sites.Sites,
map[string]interface{}{
"ButConnect": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "but_connect"}),
"TabSettings": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "tab_settings"}),
"TabBots": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "tab_bots"}),
"TabMapping": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "tab_mapping"}),
"TableName": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "table_name"}),
"TableToken": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "table_token"}),
"TableActivity": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "table_activity"}),
"MapSites": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "map_sites"}),
"MapOption": localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "map_option"}),
},
}
renderTemplate(w, "form", res)
@ -292,6 +347,7 @@ func saveHandler(w http.ResponseWriter, r *http.Request) {
}
func createHandler(w http.ResponseWriter, r *http.Request) {
setLocale(r.Header.Get("Accept-Language"))
c := Connection{
ClientID: GenerateToken(),
APIURL: string([]byte(r.FormValue("api_url"))),
@ -307,7 +363,7 @@ func createHandler(w http.ResponseWriter, r *http.Request) {
cl, _ := getConnectionByURL(c.APIURL)
if cl.ID != 0 {
http.Error(w, "connection already created", http.StatusBadRequest)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "connection_already_created"}), http.StatusBadRequest)
return
}
@ -315,13 +371,13 @@ func createHandler(w http.ResponseWriter, r *http.Request) {
cr, status, errr := client.APICredentials()
if errr.RuntimeErr != nil {
http.Error(w, "set correct crm url or key", http.StatusBadRequest)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "incorrect_url_key"}), http.StatusBadRequest)
logger.Error(c.APIURL, status, err.Error(), cr)
return
}
if !cr.Success {
http.Error(w, "set correct crm url or key", http.StatusBadRequest)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "incorrect_url_key"}), http.StatusBadRequest)
logger.Error(c.APIURL, status, err.Error(), cr)
return
}
@ -351,7 +407,7 @@ func createHandler(w http.ResponseWriter, r *http.Request) {
data, status, errr := client.IntegrationModuleEdit(integration)
if errr.RuntimeErr != nil {
http.Error(w, "error while creating integration", http.StatusBadRequest)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "error_creating_integration"}), http.StatusBadRequest)
logger.Error(c.APIURL, status, errr.RuntimeErr, data)
return
}
@ -368,7 +424,7 @@ func createHandler(w http.ResponseWriter, r *http.Request) {
err = c.createConnection()
if err != nil {
raven.CaptureErrorAndWait(err, nil)
http.Error(w, "error while creating connection", http.StatusInternalServerError)
http.Error(w, localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "error_creating_connection"}), http.StatusInternalServerError)
return
}
@ -381,7 +437,7 @@ func activityHandler(w http.ResponseWriter, r *http.Request) {
res := Response{Success: false}
if r.Method != http.MethodPost {
res.Error = "set POST"
res.Error = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "set_method"})
jsonString, _ := json.Marshal(res)
w.Write(jsonString)
return
@ -390,7 +446,7 @@ func activityHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
res.Error = "incorrect data"
res.Error = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "incorrect_data"})
jsonString, _ := json.Marshal(res)
w.Write(jsonString)
return
@ -401,7 +457,7 @@ func activityHandler(w http.ResponseWriter, r *http.Request) {
err = json.Unmarshal(body, &rec)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
res.Error = "incorrect data"
res.Error = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "incorrect_data"})
jsonString, _ := json.Marshal(res)
w.Write(jsonString)
return
@ -409,7 +465,7 @@ func activityHandler(w http.ResponseWriter, r *http.Request) {
if err := rec.setConnectionActivity(); err != nil {
raven.CaptureErrorAndWait(err, nil)
res.Error = "incorrect data"
res.Error = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "incorrect_data"})
jsonString, _ := json.Marshal(res)
w.Write(jsonString)
return
@ -422,11 +478,11 @@ func activityHandler(w http.ResponseWriter, r *http.Request) {
func validate(c Connection) error {
if c.APIURL == "" || c.APIKEY == "" {
return errors.New("missing crm url or key")
return errors.New(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "missing_url_key"}))
}
if res, _ := regexp.MatchString(`https://?[\da-z\.-]+\.(retailcrm\.(ru|pro)|ecomlogic\.com)`, c.APIURL); !res {
return errors.New("set correct crm url")
return errors.New(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "incorrect_url"}))
}
return nil

1
run.go
View File

@ -49,5 +49,6 @@ func (x *RunCommand) Execute(args []string) error {
func start() {
setWrapperRoutes()
setTransportRoutes()
http.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.Dir("web"))))
http.ListenAndServe(config.HTTPServer.Listen, nil)
}

View File

@ -1,20 +1,11 @@
<html>
<head>
<meta title="Telegram transport">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.4/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.4/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
{{template "header"}}
<div class="container">
<div class="row" style="margin-top: 5%">
<div class="col s8 offset-s3">
<ul class="tabs" id="tab">
<li class="tab col s3"><a class="active" href="#tab1">Settings CRM</a></li>
<li class="tab col s3"><a href="#tab2">Bots</a></li>
<li class="tab col s3"><a href="#tab3">Mapping</a></li>
<li class="tab col s3"><a class="active" href="#tab1">{{.Locale.TabSettings}}</a></li>
<li class="tab col s3"><a href="#tab2">{{.Locale.TabBots}}</a></li>
<li class="tab col s3"><a href="#tab3">{{.Locale.TabMapping}}</a></li>
</ul>
</div>
<div class="col s8 offset-s3">
@ -22,7 +13,7 @@
</div>
<div id="tab1" class="col s12">
<div class="row" style="margin-top: 5%">
<form class="col s8 offset-s2" action="/save/" method="POST">
<form id="save" class="col s8 offset-s2" action="/save/" method="POST">
<input name="clientId" type="hidden" value="{{.Conn.ClientID}}">
<div class="row">
<div class="input-field col s12">
@ -37,7 +28,7 @@
<div class="row">
<div class="input-field col s6 offset-s5">
<button class="btn waves-effect waves-light red lighten-1" type="submit" name="action">
Connect
{{.Locale.ButConnect}}
<i class="material-icons right">sync</i>
</button>
</div>
@ -47,11 +38,11 @@
</div>
<div id="tab2" class="col s12">
<div class="row" style="margin-top: 5%">
<form class="col s8 offset-s2" action="/add-bot/" method="POST">
<form id="add-bot" class="col s8 offset-s2" action="/add-bot/" method="POST">
<input name="clientId" type="hidden" value="{{.Conn.ClientID}}">
<div class="row">
<div class="input-field col s11">
<input placeholder="Bot Token" id="token" name="token" type="text" class="validate">
<input placeholder="{{.Locale.TableToken}}" id="token" name="token" type="text" class="validate">
</div>
<div class="input-field col s1">
<button class="btn btn-meddium waves-effect waves-light red" type="submit" name="action">
@ -64,7 +55,9 @@
<table class="col s8 offset-s2">
<thead>
<tr>
<th>Name</th><th>Token</th><th style="text-align: right">Activity</th>
<th>{{.Locale.TableName}}</th>
<th>{{.Locale.TableToken}}</th>
<th style="text-align: right">{{.Locale.TableActivity}}</th>
</tr>
</thead>
<tbody>
@ -89,12 +82,13 @@
<div class="row" style="margin-top: 5%">
{{ $sites := .Sites }}
{{ $bots := .Bots }}
{{ $locale := .Locale }}
{{if and $sites $bots}}
<table class="col s8 offset-s2">
<thead>
<tr>
<th>Sites</th>
<th>Bots</th>
<th>{{.Locale.MapSites}}</th>
<th>{{.Locale.TabBots}}</th>
</tr>
</thead>
<tbody>
@ -103,7 +97,7 @@
<td>{{$site.Name}}</td>
<td>
<select class="browser-default">
<option value="" disabled selected>Choose your option</option>
<option value="" disabled selected>{{$locale.MapOption}}</option>
{{range $bot := $bots}}
<option data-code="{{$site.Code}}" data-bot="{{$bot.ID}}">{{$bot.Name}}</option>
{{end}}
@ -117,7 +111,7 @@
<div class="row">
<div class="input-field col s6 offset-s5">
<button class="btn btn-meddium waves-effect waves-light red" type="submit" id="map-bot">
save
{{.Locale.ButConnect}}
<i class="material-icons">save</i>
</button>
</div>
@ -128,19 +122,46 @@
</div>
<script>
$("form").each(function() {
$(this).on("submit", function(e) {
$("#save").on("submit", function(e) {
e.preventDefault();
send($(this).attr('action'), formDataToObj($(this).serializeArray()))
send(
$(this).attr('action'),
formDataToObj($(this).serializeArray()),
function (data) {
return 0;
}
)
});
$("#add-bot").on("submit", function(e) {
e.preventDefault();
send(
$(this).attr('action'),
formDataToObj($(this).serializeArray()),
function (data) {
location.reload();
}
)
});
$('.activity-bot').on("click", function(e) {
send("/activity-bot/", {
token: $(this).attr("data-id"),
active: ($(this).attr("data-activity") == 'true'),
let but = $(this);
send("/activity-bot/",
{
token: but.attr("data-id"),
active: (but.attr("data-activity") == 'true'),
clientId: $('input[name=clientId]').val(),
})
},
function (data) {
if (but.attr("data-activity") == 'true') {
but.find('i').replaceWith('<i class="material-icons">play_arrow</i>');
but.attr("data-activity", "false")
} else {
but.find('i').replaceWith('<i class="material-icons">stop</i>');
but.attr("data-activity", "true")
}
}
)
});
$('#map-bot').on("click", function(e) {
@ -159,14 +180,13 @@
}
});
function send(url, data) {
function send(url, data, callback) {
$('#msg').empty();
$.ajax({
url: url,
data: JSON.stringify(data),
type: "POST",
success: function(res){
location.reload();
},
success: callback,
error: function (res){
if (res.status < 400) {
if (res.responseText) {
@ -175,7 +195,7 @@
);
}
} else {
$('#msg').append(res.responseText);
$('#msg').text(res.responseText);
}
}
});

13
templates/header.html Normal file
View File

@ -0,0 +1,13 @@
{{ define "header" }}
<html>
<head>
<meta title="Telegram transport">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="../web/materialize.min.css">
<link rel="stylesheet" href="../web/font.css" >
<script src="../web/materialize.min.js"></script>
<script src="../web/jquery-3.3.1.min.js"></script>
</head>
<body>
{{ end }}

View File

@ -1,13 +1,4 @@
<html>
<head>
<meta title="Telegram transport">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.4/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.4/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
{{template "header"}}
<div class="container">
<div class="row" style="margin-top: 5%">
<form class="col s8 offset-s2" method="POST" id="save-crm" action="/create/">
@ -24,7 +15,8 @@
</div>
<div class="row">
<div class="input-field col s6 offset-s5">
<button class="btn waves-effect waves-light red lighten-1" type="submit" name="action">Connect
<button class="btn waves-effect waves-light red lighten-1" type="submit" name="action">
{{.Locale.ButConnect}}
<i class="material-icons right">sync</i>
</button>
</div>
@ -55,7 +47,7 @@
);
}
} else {
$('#msg').append(res.responseText);
$('#msg').text(res.responseText);
}
}
});

View File

@ -0,0 +1,23 @@
but_connect: Save
tab_settings: Connection settings
tab_bots: Bots
tab_mapping: Mapping
table_name: Bot name
table_token: Bot token
table_activity: Activity
map_sites: Sites
map_option: Choose your option
no_bot_token: Enter the bot token
incorrect_data: Incorrect data
set_method: Set POST method
bot_already_created: Bot already created
not_find_account: Could not find account, please contact technical support
error_activating_channel: Error while activating the channel
error_deactivating_channel: Error while deactivating the channel
incorrect_url_key: Enter the correct CRM url or apiKey
error_creating_integration: Error while creating integration
error_creating_connection: Error while creating connection
connection_already_created: Connection already created
missing_url_key: Missing crm url or apiKey
incorrect_url: Enter the correct CRM url

View File

@ -0,0 +1,26 @@
but_connect: Сохранить
tab_settings: Настройки CRM
tab_bots: Боты
tab_mapping: Cоответствие
table_name: Имя
table_token: Токен
table_activity: Активность
map_sites: Сайты
map_option: Выберите бота
no_bot_token: Введите токен
wrong_data: Неверные данные
set_method: Установить метод POST
bot_already_created: Бот уже создан
not_find_account: Не удалось найти учетную запись, обратитесь в службу технической поддержки
error_activating_channel: Ошибка при активации канала
error_deactivating_channel: Ошибка при отключении канала
correct_url_key: Введите правильный URL или apiKey
error_creating_integration: Ошибка при создании интеграции
error_creating_connection: Ошибка при создании соединения
connection_already_created: Соединение уже создано
missing_url_key: Отсутствует URL или apiKey
incorrect_url: Введите правильный URL CRM