Skip to content

Commit

Permalink
Document printer for auto complite documents fields. (#521)
Browse files Browse the repository at this point in the history
## Описание PR
Был усовершенствован принтер документов. Время, имя и должность
подставляются автоматически на соответствующие "якоря" внутри текста на
бумаге(НУЖНО МЕНЯТЬ ЛОКАЛИЗАЦИЮ!!!!!!!!!! - а конкретно - раскидать там
где нужно "якоря" под поля)

в файле Server.LatheSystem - два вмешательства в двух местах которые
никак не отразятся на работе протолатов(две проверки на наличие
компонента принтера), вся логика происходит в DocumentPrinterSystem

P.S. For another devs - -$time$,$name$,$job$- - "якоря" внутри формы
документа(которые хранятся в .ftl) для обозначения позиции где должна
находиться соответствующая информация. (Грамота - тестовый документ, на
нём наглядно можно посмотреть результат работы скрипта)

![image](https://github.com/user-attachments/assets/e9379db0-43a7-4441-85a1-cf119e303bd7)

**Чейнджлог**

:cl:
- add: Автозаполнение формы документов для принтера документов, на
основе данных пользователя который запустил на печать документ, а
конкретно полей: фио, должность, дата.

---------

Co-authored-by: Korol_Charodey <[email protected]>
  • Loading branch information
KorolCharodey and Korol_Charodey authored Sep 25, 2024
1 parent f35939a commit 06834f7
Show file tree
Hide file tree
Showing 5 changed files with 337 additions and 181 deletions.
113 changes: 113 additions & 0 deletions Content.Server/ADT/DocumentPrinter/DocumentPrinterSystem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using Content.Server.GameTicking;
using Content.Shared.Containers.ItemSlots;
using Content.Shared.Inventory;
using Content.Shared.Paper;
using Content.Shared.PDA;
using Content.Shared.Verbs;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Timing;

namespace Content.Shared.DocumentPrinter;
public sealed class DocumentPrinterSystem : EntitySystem
{
const int TIME_YEAR_SPACE_STATION_ADT = 544;

[Dependency] private readonly GameTicker _ticker = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly SharedAudioSystem _audioSystem = default!;

public override void Initialize()
{
base.Initialize();

SubscribeLocalEvent<DocumentPrinterComponent, PrintingDocumentEvent>(OnPrinting);
SubscribeLocalEvent<DocumentPrinterComponent, GetVerbsEvent<AlternativeVerb>>(AddVerbOnOff);
}

public void AddVerbOnOff(EntityUid uid, DocumentPrinterComponent component, GetVerbsEvent<AlternativeVerb> args)
{
AlternativeVerb verb = new();
if (component.IsOnAutocomplite)
{
verb.Text = "Выкл.";
verb.Act = () =>
{
component.IsOnAutocomplite = false;
_audioSystem.PlayPvs(component.SwitchSound, uid);
};
}
else
{
verb.Text = "Вкл.";
verb.Act = () =>
{
component.IsOnAutocomplite = true;
_audioSystem.PlayPvs(component.SwitchSound, uid);
};
}
args.Verbs.Add(verb);
}

public void OnPrinting(EntityUid uid, DocumentPrinterComponent component, PrintingDocumentEvent args)
{
//coef for YEAR 544
if (!TryComp<PaperComponent>(args.Paper, out var paperComponent)) return;
if (!TryComp<InventoryComponent>(args.Actor, out var inventoryComponent)) return;

string text = paperComponent.Content;

if (component.IsOnAutocomplite)
{
MetaDataComponent? meta_id = null;
PdaComponent? pda = null;
foreach (var slot in inventoryComponent.Containers)
{
if (slot.ID == "id")//for checking only PDA
{
TryComp(slot.ContainedEntity, out pda);
TryComp<ItemSlotsComponent>(slot.ContainedEntity, out var itemslots);
if (itemslots is not null)
TryComp(itemslots.Slots["PDA-id"].Item, out meta_id);
break;
}
}
DateTime time = DateTime.UtcNow.AddYears(TIME_YEAR_SPACE_STATION_ADT).AddHours(3);
text = text.Replace("$time$", $"{_gameTiming.CurTime.Subtract(_ticker.RoundStartTimeSpan).ToString("hh\\:mm\\:ss")} | {(time.Day < 10 ? $"0{time.Day}" : time.Day)}.{(time.Month < 10 ? $"0{time.Month}" : time.Month)}.{time.Year}");
if (pda?.StationName is not null)
{
text = text.Replace("Station XX-000", pda.StationName);
}
if (meta_id is null)
{
text = text.Replace("$name$", "");
text = text.Replace("$job$", "");
}
else
{
int startIndex = meta_id.EntityName.IndexOf("("); int endIndex = meta_id.EntityName.IndexOf(")");
if (startIndex.Equals(-1) || startIndex.Equals(-1))
{
text = text.Replace("$name$", "");
text = text.Replace("$job$", "");
}
else
{
string id_card_word = "ID карта ";
text = text.Replace("$name$", meta_id.EntityName.Replace(id_card_word, "").Substring(0, startIndex - id_card_word.Length - 2));
text = text.Replace("$job$", meta_id.EntityName.Substring(startIndex + 1, endIndex - startIndex - 1));
}
}
paperComponent.Content = text;
// if (!TryComp<MetaDataComponent>(args.Actor, out var comp)) return; // was for test, STFU JUST LEAVE IT HERE
}
else
{
text = text.Replace("$time$", "");
text = text.Replace("$name$", "");
text = text.Replace("$job$", "");
paperComponent.Content = text;
}
}
}

//(C) Korol_Charodey
21 changes: 19 additions & 2 deletions Content.Server/Lathe/LatheSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
using Robust.Shared.Audio.Systems;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
using Content.Shared.DocumentPrinter;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Content.Server.Lathe
{
Expand Down Expand Up @@ -178,7 +180,7 @@ public bool TryAddToQueue(EntityUid uid, LatheRecipePrototype recipe, LatheCompo
foreach (var (mat, amount) in recipe.Materials)
{
var adjustedAmount = recipe.ApplyMaterialDiscount
? (int) (-amount * component.MaterialUseMultiplier)
? (int)(-amount * component.MaterialUseMultiplier)
: -amount;

_materialStorage.TryChangeMaterialAmount(uid, mat, adjustedAmount);
Expand Down Expand Up @@ -223,12 +225,20 @@ public void FinishProducing(EntityUid uid, LatheComponent? comp = null, LathePro
{
if (!Resolve(uid, ref comp, ref prodComp, false))
return;

if (comp.CurrentRecipe != null)
{
if (comp.CurrentRecipe.Result is { } resultProto)
{
var result = Spawn(resultProto, Transform(uid).Coordinates);
//ADT tweak start
if (TryComp<DocumentPrinterComponent>(uid, out var printerComponent))
{
var tuple = printerComponent.Queue.First();
if (tuple.Item2.Result.Equals(resultProto))
RaiseLocalEvent(uid, new PrintingDocumentEvent(result, tuple.Item1));
printerComponent.Queue.Remove(tuple);
}
//ADT tweak end
_stack.TryMergeToContacts(result);
}

Expand Down Expand Up @@ -388,6 +398,13 @@ private void OnLatheQueueRecipeMessage(EntityUid uid, LatheComponent component,
}
}
TryStartProducing(uid, component);
//ADT Tweak start
if (TryComp<DocumentPrinterComponent>(uid, out var comp))
{
if (recipe is not null)
comp.Queue.Add((args.Actor, recipe));
}
//ADT tweak end
UpdateUserInterfaceState(uid, component);
}

Expand Down
25 changes: 25 additions & 0 deletions Content.Shared/ADT/DocumentPrinter/DocumentPrinterComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Content.Shared.Research.Prototypes;
using Robust.Shared.Audio;
using Robust.Shared.GameStates;

namespace Content.Shared.DocumentPrinter;

[RegisterComponent, NetworkedComponent]
public sealed partial class DocumentPrinterComponent : Component
{
public List<(EntityUid, LatheRecipePrototype)> Queue { get; set; } = new();
public SoundSpecifier SwitchSound = new SoundPathSpecifier("/Audio/Machines/machine_switch.ogg");
public bool IsOnAutocomplite = true;
}

public sealed class PrintingDocumentEvent : EntityEventArgs
{
public EntityUid Paper { get; private set; }
public EntityUid Actor { get; private set; }
public PrintingDocumentEvent(EntityUid paper, EntityUid actor)
{
Paper = paper;
Actor = actor;
}
}
//(C) Korol_Charodey
Loading

0 comments on commit 06834f7

Please sign in to comment.