diff --git a/home/__pycache__/admin.cpython-313.pyc b/home/__pycache__/admin.cpython-313.pyc index a0dff41..6145892 100644 Binary files a/home/__pycache__/admin.cpython-313.pyc and b/home/__pycache__/admin.cpython-313.pyc differ diff --git a/home/__pycache__/models.cpython-313.pyc b/home/__pycache__/models.cpython-313.pyc index 09bf542..48b97e4 100644 Binary files a/home/__pycache__/models.cpython-313.pyc and b/home/__pycache__/models.cpython-313.pyc differ diff --git a/home/__pycache__/views.cpython-313.pyc b/home/__pycache__/views.cpython-313.pyc index 411d7a1..8b17fbb 100644 Binary files a/home/__pycache__/views.cpython-313.pyc and b/home/__pycache__/views.cpython-313.pyc differ diff --git a/home/admin.py b/home/admin.py index 72b9a94..903fb61 100644 --- a/home/admin.py +++ b/home/admin.py @@ -3,7 +3,7 @@ from django.contrib import admin from django import forms from .models import ( Noticia, ClienteCategoria, SistemaOperativo, ServerSelection, - RecruitAFriend, DownloadClientPage, ContentCreator, RecruitReward + RecruitAFriend, DownloadClientPage, ContentCreator, RecruitReward, GuildRenameSettings ) from django.db import connections import logging @@ -128,7 +128,18 @@ class ClienteCategoriaAdmin(admin.ModelAdmin): @admin.register(RecruitReward) class RecruitRewardAdmin(admin.ModelAdmin): list_display = ('required_friends', 'reward_name', 'item_id', 'item_quantity', 'icon_class') - search_fields = ('reward_name',) + search_fields = ('reward_name',) + +@admin.register(GuildRenameSettings) +class GuildRenameSettingsAdmin(admin.ModelAdmin): + list_display = ('id', 'cost') + list_display_links = ('id',) # Hacemos que 'id' sea el enlace + list_editable = ('cost',) # Permitimos que 'cost' sea editable + fieldsets = ( + (None, { + 'fields': ('cost',) + }), + ) # Registro de modelos en el admin diff --git a/home/models.py b/home/models.py index 26947d8..620626a 100644 --- a/home/models.py +++ b/home/models.py @@ -118,14 +118,23 @@ class AccountActivation(models.Model): class SecurityToken(models.Model): - user_id = models.IntegerField() # Referencia al ID del usuario en `acore_auth` + user = models.ForeignKey(User, on_delete=models.CASCADE) token = models.CharField(max_length=6) created_at = models.DateTimeField(auto_now_add=True) expires_at = models.DateTimeField() ip_address = models.GenericIPAddressField() def __str__(self): - return f"Token for user_id {self.user_id}" + return f"Token for {self.user.username}" + + +class GuildRenameSettings(models.Model): + cost = models.IntegerField(default=1000, help_text="Costo en Donation Points (DP) para renombrar una hermandad.") + def __str__(self): + return f"Costo actual: {self.cost} DP" + class Meta: + verbose_name = "Configuración de Renombrar Hermandad" + verbose_name_plural = "Configuraciones de Renombrar Hermandad" \ No newline at end of file diff --git a/home/static/nw-themes/nw-ryu/nw-js-handlers/rename_guild_response.js b/home/static/nw-themes/nw-ryu/nw-js-handlers/rename_guild_response.js new file mode 100644 index 0000000..84392ca --- /dev/null +++ b/home/static/nw-themes/nw-ryu/nw-js-handlers/rename_guild_response.js @@ -0,0 +1,79 @@ +if (window.history.replaceState) { + window.history.replaceState(null, null, window.location.href); +}; + +$(function(){ + $(".toggle-token").click(function() { + $(this).toggleClass("fa-eye fa-eye-slash"); + var type = $(this).hasClass("fa-eye-slash") ? "text" : "password"; + $("#security-token").attr("type", type); + }); +}); + +function doRefresh() { + $("#nw-rename-guild-form").load(document.URL + " #nw-rename-guild-form>*", function(){ + $.getScript('nw-js-handlers/rename_guild_response.js'); + }); +} + +$(function(){ + $('select').on('change', function(){ + var select = $(this); + + select.css('color', select.children('option:selected').css('color')); + }); +}); + +$(function(){ + $('.rename-guild-button').on('click', function(e) { + e.preventDefault(); + e.stopPropagation(); + $("#rename-guild-response").empty(); + + var button = $(this); + var buttonoriginal = button.html(); + var bValue = button.data('id'); + var data = {renameguild : bValue}; + data = $("#nw-rename-guild-form").serialize() + '&' + $.param(data); + + var conf = confirm("¿Estás seguro de renombrar la hermandad seleccionada?"); + + if (conf === true) { + changeButton(button, 'Renombrando hermandad'); + + $.ajax({ + type: 'POST', + url: '', + data: data, + dataType: 'json', + success: function(data) { + $("#rename-guild-response").append(data.message).hide().slideDown(); + + if (data.success === true) { + button.html("Hermandad renombrada"); + button.css("color","#d79602"); + setTimeout(function() { + $("#nw-rename-guild-form")[0].reset(); + restoreButton(button, buttonoriginal); + doRefresh(); + }, 5000); + } + else { + setTimeout(function() { + $("#rename-guild-response").slideUp( function() { + $("#rename-guild-response").empty(); + restoreButton(button, buttonoriginal); + }); + }, 5000); + } + }, + error: function() { + setTimeout(function() { + alert("Algo ha salido mal. Por favor intente más tarde"); + window.location.reload(); + }, 2000); + } + }); + }; + }); +}); diff --git a/home/templates/partials/head.html b/home/templates/partials/head.html index 0ea9692..05f7f72 100644 --- a/home/templates/partials/head.html +++ b/home/templates/partials/head.html @@ -50,6 +50,7 @@ + diff --git a/home/templates/partials/rename_guild.html b/home/templates/partials/rename_guild.html index 1ee8279..d6a9456 100644 --- a/home/templates/partials/rename_guild.html +++ b/home/templates/partials/rename_guild.html @@ -1,36 +1,70 @@
-
-
-

Renombrar hermandad

-
- -
-
-

La herramienta Renombrar hermandad te permite cambiar de nombre a una hermandad de la cual seas Maestro de Hermandad.

-
-

A la hora de escoger un nuevo nombre, ten en cuenta:

-

- La longitud máxima es de 24 caracteres.

-

- Los caracteres permitidos son A-Za-z y el espacio.

-
-

Al usar el botón RENOMBRAR HERMANDAD de la hermandad que hayas escogido, se cambiará su nombre al nuevo nombre que hayas ingresado.

-

El cambio de nombre de hermandad es instantáneo. Puede ser necesario que los miembros de la hermandad conectados deban volver a conectar para finalmente ver el nuevo nombre.

-
-
- NOTA -
-

Por favor, asegúrate de haber elegido el nombre correcto ya que esta acción no es reversible una vez realizada.

-
-
-
-
-
-

Requiere 1000 PD

-
- No hay personajes Maestros de hermandad -
-
+
+
+

Renombrar Hermandad

+
+
+

Información

+ + +
+
+
+

La herramienta Renombrar hermandad te permite cambiar de nombre a una hermandad de la cual seas Maestro de Hermandad.

+
+

A la hora de escoger un nuevo nombre, ten en cuenta:

+

- La longitud máxima es de 24 caracteres.

+

- Los caracteres permitidos son A-Za-z y el espacio.

+
+
+ NOTA +
+

Por favor, asegúrate de haber elegido el nombre correcto ya que esta acción no es reversible una vez realizada.

+
+
+
+

Requiere {{ rename_cost }} PD

+
+ + + {% if no_guild_leader_message %} + {{ no_guild_leader_message }} + {% else %} +
+ {% csrf_token %} + + + + + + + + + + + + + + + + + + + +
+ + +
+ +
+
+
+
+ {% endif %}
-
\ No newline at end of file +
+
+
diff --git a/home/views.py b/home/views.py index 1151566..263ec29 100644 --- a/home/views.py +++ b/home/views.py @@ -10,7 +10,7 @@ from django.db import connections from django.contrib import messages from django.contrib.auth import logout from django import forms -from .models import Noticia, ClienteCategoria, ServerSelection, RecruitAFriend, DownloadClientPage, ContentCreator, RecruitReward, ClaimedReward, AccountActivation, SecurityToken +from .models import Noticia, ClienteCategoria, ServerSelection, RecruitAFriend, DownloadClientPage, ContentCreator, RecruitReward, ClaimedReward, AccountActivation, SecurityToken, GuildRenameSettings from django.views.decorators.csrf import csrf_exempt import logging from datetime import datetime, timedelta @@ -967,10 +967,77 @@ def transfer_d_points_view(request): # Renderizar la plantilla para la transferencia de puntos return render(request, 'account/transfer_d_points.html') + +from .models import GuildRenameSettings + def rename_guild_view(request): - # Renderizar la plantilla para la transferencia de puntos - return render(request, 'account/rename_guild.html') - + # Verificar si el usuario está autenticado mediante la sesión + username = request.session.get('username') + if not username: + return redirect('login') + + # Obtener el usuario desde la base de datos `acore_auth` + user_data = get_user_from_acore(username) + if not user_data: + return redirect('login') + + user_id = user_data['id'] + + # Obtener el costo desde la configuración + try: + settings = GuildRenameSettings.objects.first() + rename_cost = settings.cost if settings else 1000 + except GuildRenameSettings.DoesNotExist: + rename_cost = 1000 # Valor predeterminado si no se encuentra la configuración + + # Comprobar si hay personajes que sean líderes de una hermandad + with connections['acore_characters'].cursor() as cursor: + cursor.execute(""" + SELECT g.guildid, g.name, gm.rank, c.name + FROM guild g + JOIN guild_member gm ON g.guildid = gm.guildid + JOIN characters c ON c.guid = gm.guid + WHERE c.account = %s AND gm.rank = 0 + """, [user_id]) + guild_leader_data = cursor.fetchall() + + if not guild_leader_data: + no_guild_leader_message = "No tienes personajes que sean Maestros de Hermandad en tu cuenta." + else: + no_guild_leader_message = None + + if request.method == 'POST': + old_guild_name = request.POST.get('old-guild-name').strip() + new_guild_name = request.POST.get('new-guild-name').strip() + conf_new_guild_name = request.POST.get('conf-new-guild-name').strip() + current_password = request.POST.get('cur-password').strip() + security_token = request.POST.get('security-token').strip() + + # Validar campos vacíos + if not old_guild_name or not new_guild_name or not conf_new_guild_name or not current_password or not security_token: + return JsonResponse({'success': False, 'message': 'Por favor, complete todos los campos.'}) + + # Verificar si el usuario tiene suficientes Donation Points (DP) + with connections['default'].cursor() as cursor: + cursor.execute("SELECT dp FROM home_api_points WHERE accountID = %s", [user_id]) + points_data = cursor.fetchone() + + if not points_data or points_data[0] < rename_cost: + return JsonResponse({'success': False, 'message': f'No tienes suficientes Donation Points (se requieren {rename_cost} DP).'}) + + # Deducir los Donation Points del usuario + with connections['default'].cursor() as cursor: + cursor.execute("UPDATE home_api_points SET dp = dp - %s WHERE accountID = %s", [rename_cost, user_id]) + + return JsonResponse({'success': True, 'message': 'Hermandad renombrada exitosamente.'}) + + return render(request, 'account/rename_guild.html', { + 'guild_leader_data': guild_leader_data, + 'no_guild_leader_message': no_guild_leader_message, + 'rename_cost': rename_cost + }) + + def vote_points_view(request): """ Vista para la página de puntos de votación.